vuer 0.0.46__py3-none-any.whl → 0.0.47__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 +1 -1
- vuer/client_build/assets/chunks/chunk-Bus2d0NA.js +8555 -0
- vuer/client_build/assets/chunks/chunk-Bus2d0NA.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-DG0_h2Gk.js +283 -0
- vuer/client_build/assets/chunks/chunk-DG0_h2Gk.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-DfxwlK4B.js +3 -0
- vuer/client_build/assets/chunks/chunk-DfxwlK4B.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-KiSzgKRl.js +7734 -0
- vuer/client_build/assets/chunks/chunk-KiSzgKRl.js.map +1 -0
- vuer/client_build/assets/chunks/chunk-kyMD9k76.js +102 -0
- vuer/client_build/assets/chunks/chunk-kyMD9k76.js.map +1 -0
- vuer/client_build/assets/entries/entry-client-routing.B_w5XAuR.js +5 -0
- vuer/client_build/assets/entries/entry-client-routing.B_w5XAuR.js.map +1 -0
- vuer/client_build/assets/entries/pages_editor.ZN34izsb.js +2 -0
- vuer/client_build/assets/entries/pages_editor.ZN34izsb.js.map +1 -0
- vuer/client_build/assets/entries/pages_index.BvS3ycqa.js +2 -0
- vuer/client_build/assets/entries/pages_index.BvS3ycqa.js.map +1 -0
- vuer/client_build/assets/entries/pages_simple.DUtDOajn.js +2 -0
- vuer/client_build/assets/entries/pages_simple.DUtDOajn.js.map +1 -0
- vuer/client_build/editor/index.html +4 -4
- vuer/client_build/index.html +4 -4
- vuer/client_build/simple/index.html +3 -3
- vuer/schemas/__pycache__/html_components.cpython-311.pyc +0 -0
- vuer/schemas/__pycache__/scene_components.cpython-311.pyc +0 -0
- vuer/schemas/scene_components.py +1 -0
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/METADATA +30 -33
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/RECORD +31 -13
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/WHEEL +1 -1
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/LICENSE +0 -0
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/entry_points.txt +0 -0
- {vuer-0.0.46.dist-info → vuer-0.0.47.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import{o as Hh,p as ws,u as q,q as Kh,r as wt,t as Kt,z as Q,A as Gd,M as At,Q as It,B as ms,S as ya,E as ze,G as Ot,H as $e,I as Qt,J as uo,K as ot,N as Vi,R as Zt,U as Pn,W as va,X as Rs,Y as ps,$ as me,a0 as oi,a1 as ve,a2 as He,a3 as rt,a4 as pt,a5 as fi,a6 as li,a7 as $h,a8 as Ps,a9 as zn,aa as Yr,ab as Yh,ac as Ba,ad as qn,ae as Nt,af as re,ag as Nd,ah as Hd,ai as Sa,aj as Kd,ak as Oi,al as $d,am as Yd,an as Vh,ao as Vr,ap as pn,aq as En,ar as Xn,as as Vd,at as Jd,au as Ao,av as In,aw as fo,ax as zd,ay as qd,az as Xd,aA as Wd,aB as jd,aC as Zd,aD as tA,aE as eA,aF as iA,aG as sA,aH as nA,aI as go,aJ as Mn,aK as rA,aL as ye,aM as mo,aN as aA,aO as po,aP as As,aQ as fs,aR as Fi,aS as on,aT as ln,aU as oA,aV as lA,aW as hA,aX as cA,aY as uA,aZ as dA,a_ as AA,a$ as fA,b0 as gA,b1 as mA,b2 as Jr,b3 as Jh,b4 as Se,b5 as Ta,b6 as _a,b7 as pA,b8 as zh,b9 as EA,ba as IA,bb as CA,bc as qh,bd as zr,be as Ji,bf as yA,bg as Xh,bh as Wh,bi as vA,bj as BA,bk as SA,bl as jh,bm as Zh,bn as TA,bo as _A,bp as xA,bq as tc,br as ec,bs as xa,bt as ic,bu as DA,bv as RA,bw as sc,bx as nc,by as LA,bz as rc,bA,bB as wA,bC as PA,bD as MA,bE as FA,bF as kA,bG as OA,bH as QA,bI as UA,bJ as GA,bK as NA,bL as HA,bM as KA,bN as $A,bO as YA,bP as VA,bQ as JA,bR as zA,bS as qA,bT as XA,bU as WA,bV as jA,bW as ZA,bX as tf,bY as ef,bZ as sf,b_ as nf,b$ as rf,c0 as af,c1 as of,c2 as lf,c3 as hf,c4 as cf,c5 as uf,c6 as df,c7 as Af,c8 as ff,c9 as gf,ca as mf,cb as pf,cc as Ef,cd as If,ce as Cf,cf as yf,cg as vf,ch as Bf,ci as Sf,cj as Tf,ck as _f,cl as xf,cm as Df,cn as Rf,co as Lf,cp as bf,cq as wf,cr as Pf,cs as Mf,ct as Ff,cu as kf,cv as Of,cw as Qf,cx as Uf,cy as Gf,cz as Nf,cA as Hf,cB as Kf,cC as $f,cD as Yf,cE as Vf,cF as Jf,cG as zf,cH as qf,cI as Xf,cJ as Wf,cK as jf,cL as Zf,cM as tg,cN as eg,cO as ig,cP as sg,cQ as ng,cR as rg,cS as ag,cT as og,cU as lg,cV as hg,cW as cg,cX as ug,cY as dg,cZ as Ag,c_ as fg,c$ as gg,d0 as mg,d1 as pg,d2 as Eg,d3 as Ig,d4 as Cg,d5 as yg,d6 as vg,d7 as Bg,d8 as Sg,d9 as Tg,da as _g,db as xg,dc as Dg,dd as Rg,de as Lg,df as bg,dg as wg,dh as Pg,di as Mg,dj as Fg,dk as kg,dl as Og,dm as Qg,dn as Ug,dp as Gg,dq as Ng,dr as Hg,ds as Kg,dt as $g,du as Yg,dv as Vg,dw as Jg,dx as zg,dy as qg,dz as Xg,dA as Wg,dB as jg,dC as Zg,dD as tm,dE as em,dF as im,dG as sm,dH as nm,dI as rm,dJ as am,dK as om,dL as lm,dM as hm,dN as cm,dO as um,dP as dm,dQ as Am,dR as fm,dS as gm,dT as mm,dU as pm,dV as Em,dW as Da,dX as Ra,dY as Fn,dZ as La,d_ as Im,d$ as Cm,e0 as ym,e1 as vm,e2 as Bm,e3 as Sm,e4 as Tm,e5 as _m,e6 as xm,e7 as Dm,e8 as Rm,e9 as Lm,ea as bm,eb as wm,ec as Pm,ed as Mm,ee as Fm,ef as km,eg as Om,eh as Qm,ei as Um,ej as Gm,ek as Nm,el as Hm,em as Km,en as $m,eo as Ym,ep as Vm,eq as Jm,er as zm,es as qm,et as Xm,eu as Wm,ev as jm,ew as Zm,ex as tp,ey as ep,ez as ip,eA as sp,eB as np,eC as rp,eD as ap,eE as op,eF as lp,eG as hp,eH as cp,eI as up,eJ as dp,eK as Ap,eL as fp,eM as gp,eN as mp,eO as pp,eP as Ep,eQ as Ip,eR as Cp,eS as yp,eT as vp,eU as Bp,eV as Sp,eW as Tp,eX as _p,eY as xp,eZ as Dp,e_ as Rp,e$ as Lp,f0 as bp,f1 as wp,f2 as Pp,f3 as Mp,f4 as Fp,f5 as kp,f6 as Op,f7 as Qp,f8 as Up,f9 as Gp,fa as Np,fb as Hp,fc as Kp,fd as $p,fe as Yp,ff as Vp,fg as Jp,fh as zp,fi as qp,fj as Xp}from"./chunk-KiSzgKRl.js";import{r as S,f as Wp,g as jp,h as Zp,j as Ve}from"./chunk-WT4fnZC5.js";import{_ as t0}from"./chunk-D7HrI6pR.js";function e0(a,t="pointer",e="auto",i=document.body){S.useEffect(()=>{if(a)return i.style.cursor=t,()=>void(i.style.cursor=e)},[a])}let Wi=0;const ba=Hh(a=>(ws.onStart=(t,e,i)=>{a({active:!0,item:t,loaded:e,total:i,progress:(e-Wi)/(i-Wi)*100})},ws.onLoad=()=>{a({active:!1})},ws.onError=t=>a(e=>({errors:[...e.errors,t]})),ws.onProgress=(t,e,i)=>{e===i&&(Wi=i),a({active:!0,item:t,loaded:e,total:i,progress:(e-Wi)/(i-Wi)*100||100})},{errors:[],active:!1,progress:0,item:"",loaded:0,total:0}));function i0({children:a}){const t=ba();return S.createElement(S.Fragment,null,a==null?void 0:a(t))}const s0=a=>`Loading ${a.toFixed(2)}%`;function n0({containerStyles:a,innerStyles:t,barStyles:e,dataStyles:i,dataInterpolation:s=s0,initialState:n=r=>r}){const{active:r,progress:o}=ba(),l=S.useRef(0),h=S.useRef(0),u=S.useRef(null),[c,d]=S.useState(n(r));S.useEffect(()=>{let f;return r!==c&&(f=setTimeout(()=>d(r),300)),()=>clearTimeout(f)},[c,r]);const A=S.useCallback(()=>{u.current&&(l.current+=(o-l.current)/2,(l.current>.95*o||o===100)&&(l.current=o),u.current.innerText=s(l.current),l.current<o&&(h.current=requestAnimationFrame(A)))},[s,o]);return S.useEffect(()=>(A(),()=>cancelAnimationFrame(h.current)),[A]),c?S.createElement("div",{style:{...Ms.container,opacity:r?1:0,...a}},S.createElement("div",null,S.createElement("div",{style:{...Ms.inner,...t}},S.createElement("div",{style:{...Ms.bar,transform:`scaleX(${o/100})`,...e}}),S.createElement("span",{ref:u,style:{...Ms.data,...i}})))):null}const Ms={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"}},Wn=new Q,Eo=new Kt,hi=new Q,Fs=new Q,ji=new Q,Io=new Gd,r0=S.forwardRef(({autoTransform:a=!0,matrix:t,axisLock:e,dragLimits:i,onHover:s,onDragStart:n,onDrag:r,onDragEnd:o,children:l,dragConfig:h,...u},c)=>{const d=q(E=>E.controls),{camera:A,size:f,raycaster:g,invalidate:m}=q(),p=S.useRef(null),C=Kh({onHover:({hovering:E})=>s&&s(E??!1),onDragStart:({event:E})=>{d&&(d.enabled=!1);const{point:y}=E;p.current.matrix.decompose(Wn,new It,new Q),hi.copy(y),Fs.copy(hi).sub(Wn),n&&n(Wn),m()},onDrag:({xy:[E,y],intentional:v})=>{if(!v)return;const T=(E-f.left)/f.width*2-1,B=-((y-f.top)/f.height)*2+1;if(Eo.set(T,B),g.setFromCamera(Eo,A),!e)A.getWorldDirection(ji).negate();else switch(e){case"x":ji.set(1,0,0);break;case"y":ji.set(0,1,0);break;case"z":ji.set(0,0,1);break}Io.setFromNormalAndCoplanarPoint(ji,hi),g.ray.intersectPlane(Io,hi);const _=p.current.matrix.clone(),D=p.current.matrixWorld.clone(),x=new Q(hi.x-Fs.x,hi.y-Fs.y,hi.z-Fs.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),a){p.current.matrix.setPosition(x);const M=p.current.matrix.clone().multiply(_.invert()),k=p.current.matrix.clone().multiply(D.invert());r&&r(p.current.matrix,M,p.current.matrixWorld,k)}else{const M=new At().copy(p.current.matrix);M.setPosition(x);const k=M.clone().multiply(_.invert()),X=M.clone().multiply(D.invert());r&&r(M,k,p.current.matrixWorld,X)}m()},onDragEnd:()=>{d&&(d.enabled=!0),o&&o(),m()}},{drag:{filterTaps:!0,threshold:1,...typeof h=="object"?h:{}}});return S.useImperativeHandle(c,()=>p.current,[]),S.useLayoutEffect(()=>{t&&(p.current.matrix=t)},[t]),S.createElement("group",wt({ref:p},C(),{matrix:t,matrixAutoUpdate:!1},u),l)});function Es(a,t,e){return t in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function qr(a,t){return qr=Object.setPrototypeOf||function(i,s){return i.__proto__=s,i},qr(a,t)}function a0(){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 o0(){for(var a=arguments.length,t=new Array(a),e=0;e<a;e++)t[e]=arguments[e];var i=t[0],s=t[1],n=t[2],r=t[3],o=t[4],l=t[5],h=t[6],u=t[7],c=t[8];return i*o*c+s*l*h+n*r*u-n*o*h-s*r*c-i*l*u}function Co(a,t){for(var e=[],i=a.toArray(),s=t.toArray(),n=0;n<i.length;n++)e[n]=i[n]+s[n];return new ms().fromArray(e)}function l0(a){if(Array.isArray(a))return a}function h0(a,t){var e=a==null?null:typeof Symbol<"u"&&a[Symbol.iterator]||a["@@iterator"];if(e!=null){var i=[],s=!0,n=!1,r,o;try{for(e=e.call(a);!(s=(r=e.next()).done)&&(i.push(r.value),!(t&&i.length===t));s=!0);}catch(l){n=!0,o=l}finally{try{!s&&e.return!=null&&e.return()}finally{if(n)throw o}}return i}}function Xr(a,t){(t==null||t>a.length)&&(t=a.length);for(var e=0,i=new Array(t);e<t;e++)i[e]=a[e];return i}function ac(a,t){if(a){if(typeof a=="string")return Xr(a,t);var e=Object.prototype.toString.call(a).slice(8,-1);if(e==="Object"&&a.constructor&&(e=a.constructor.name),e==="Map"||e==="Set")return Array.from(a);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return Xr(a,t)}}function c0(){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 Me(a,t){return l0(a)||h0(a,t)||ac(a,t)||c0()}function u0(a){if(Array.isArray(a))return Xr(a)}function d0(a){if(typeof Symbol<"u"&&a[Symbol.iterator]!=null||a["@@iterator"]!=null)return Array.from(a)}function A0(){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 Cn(a){return u0(a)||d0(a)||ac(a)||A0()}function hn(a,t,e){return a0()?hn=Reflect.construct:hn=function(s,n,r){var o=[null];o.push.apply(o,n);var l=Function.bind.apply(s,o),h=new l;return r&&qr(h,r.prototype),h},hn.apply(null,arguments)}function f0(a){var t=Me(a[0],2),e=t[0],i=t[1],s=Me(a[1],2),n=s[0],r=s[1],o=Me(a[2],2),l=o[0],h=o[1];return o0(e,i,1,n,r,1,l,h,1)}function g0(a){return f0(a)===0}var m0=new Kt,p0=new Kt;function yo(a){var t=a.map(function(h){return Array.isArray(h)?hn(Kt,Cn(h)):h}),e=Me(t,3),i=e[0],s=e[1],n=e[2];if(g0(a))return!1;var r=m0.subVectors(s,i),o=p0.subVectors(n,i),l=o.cross(r);return l>0}function oc(a,t,e){return Math.max(t,Math.min(e,a))}function lc(a,t){return oc(a-Math.floor(a/t)*t,0,t)}function hc(a,t){var e=lc(t-a,Math.PI*2);return e>Math.PI&&(e-=Math.PI*2),e}function E0(a){return a/180*Math.PI}function I0(a){return a*180/Math.PI}function C0(a,t){for(var e=t.radius,i=e===void 0?1:e,s=a.length/3,n=2/s,r=Math.PI*(3-2.2360679775),o=0;o<a.length;o+=3){var l=o*n-1+n/2,h=Math.sqrt(1-Math.pow(l,2)),u=o%s*r,c=Math.cos(u)*h,d=Math.sin(u)*h;a[o]=c*i,a[o+1]=l*i,a[o+2]=d*i}}function y0(a,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Number.EPSILON;return Math.abs(a.x-t.x)<e&&Math.abs(a.y-t.y)<e&&Math.abs(a.z-t.z)<e}function cc(a,t){return a.x===t.x?typeof a.z<"u"&&a.y===t.y?a.z-t.z:a.y-t.y:a.x-t.x}function v0(a){for(var t=a.sort(cc),e=[t[0],t[1]],i=2;i<t.length;i++)for(e.push(t[i]);e.length>2&&yo(Cn(e.slice(-3)));)e.splice(e.length-2,1);for(var s=[t[t.length-1],t[t.length-2]],n=t.length-3;n>=0;n--)for(s.push(t[n]);s.length>2&&yo(Cn(s.slice(-3)));)s.splice(s.length-2,1);s.splice(0,1),s.splice(s.length-1,1);var r=[].concat(e,s);return r}function B0(a,t,e){var i=Me(t,2),s=i[0],n=i[1],r=Me(e,2),o=r[0],l=r[1];return o+(a-s)*(l-o)/(n-s)}function S0(a){return a*a*a*(a*(a*6-15)+10)}function T0(a,t,e){return a*(1-e)+t*e}function uc(a,t,e){return(e-a)/(t-a)}function _0(a,t,e){var i=Math.sqrt(a*a+t*t+e*e);return[a/i,t/i,e/i]}function x0(a,t,e){var i=a*a,s=t*t,n=e*e,r=a*Math.sqrt(1-(s+n)/2+s*n/3),o=t*Math.sqrt(1-(n+i)/2+n*i/3),l=e*Math.sqrt(1-(i+s)/2+i*s/3);return[r,o,l]}function dc(a,t){var e=new Q().crossVectors(a,t),i=a.dot(t),s=new ms().identity(),n=new ms().set(0,-e.z,e.y,e.z,0,-e.x,-e.y,e.x,0),r=new ms().multiplyMatrices(n,n).multiplyScalar(1/(1+i)),o=Co(Co(s,n),r);return o}function D0(a,t,e){var i=Math.asin(t),s=Math.atan2(a,-e);return[i,s]}function R0(a,t){var e=Math.sin(a),i=Math.cos(a),s=Math.sin(t)*i,n=-Math.cos(t)*i;return[s,e,n]}function L0(a,t){var e=Me(t,2),i=e[0],s=e[1],n=dc(a.normal,new Q(0,1,0)),r=uc(i.clone().applyMatrix3(n).y,s.clone().applyMatrix3(n).y,0);return new Q().lerpVectors(i,s,r)}function b0(a,t){var e=t.normal.dot(a);return e}function w0(a,t){var e=Me(a,3),i=e[0],s=e[1],n=e[2],r=Me(t,2),o=r[0],l=r[1];return n*o*l+s*o+i}function P0(a,t){var e=Me(t,2),i=e[0],s=e[1],n=i*s,r=a/n,o=a-n*r,l=o/i,h=o%i;return[h,l,r]}function M0(a,t){return a[0]+t[0]*a[1]}function F0(a,t){var e=a%t,i=Math.floor(a/t);return[e,i]}var ks=Object.freeze({__proto__:null,clamp:oc,repeat:lc,deltaAngle:hc,degToRad:E0,radToDeg:I0,fibonacciOnSphere:C0,vectorEquals:y0,lexicographic:cc,convexHull:v0,remap:B0,fade:S0,lerp:T0,inverseLerp:uc,normalize:_0,pointOnCubeToPointOnSphere:x0,rotateVectorOnVector:dc,pointToCoordinate:D0,coordinateToPoint:R0,planeSegmentIntersection:L0,pointToPlaneDistance:b0,getIndexFrom3D:w0,get3DFromIndex:P0,getIndexFrom2D:M0,get2DFromIndex:F0});function Ac(a,t){if(!(a instanceof t))throw new TypeError("Cannot call a class as a function")}var le=function a(t,e,i){var s=this;Ac(this,a),Es(this,"dot2",function(n,r){return s.x*n+s.y*r}),Es(this,"dot3",function(n,r,o){return s.x*n+s.y*r+s.z*o}),this.x=t,this.y=e,this.z=i},k0=[new le(1,1,0),new le(-1,1,0),new le(1,-1,0),new le(-1,-1,0),new le(1,0,1),new le(-1,0,1),new le(1,0,-1),new le(-1,0,-1),new le(0,1,1),new le(0,-1,1),new le(0,1,-1),new le(0,-1,-1)],vo=[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],Bo=new Array(512),So=new Array(512),O0=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=vo[e]^t&255:i=vo[e]^t>>8&255,Bo[e]=Bo[e+256]=i,So[e]=So[e+256]=k0[i%12]}};O0(0);function Q0(a){if(typeof a=="number")a=Math.abs(a);else if(typeof a=="string"){var t=a;a=0;for(var e=0;e<t.length;e++)a=(a+(e+1)*(t.charCodeAt(e)%96))%2147483647}return a===0&&(a=311),a}function To(a){var t=Q0(a);return function(){var e=t*48271%2147483647;return t=e,e/2147483647}}var U0=function a(t){var e=this;Ac(this,a),Es(this,"seed",0),Es(this,"init",function(i){e.seed=i,e.value=To(i)}),Es(this,"value",To(this.seed)),this.init(t)};new U0(Math.random());var G0=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)},fc=function(t){return 1/(1+t+.48*t*t+.235*t*t*t)},N0=function(t){return t},H0={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}},K0={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}},$0={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}},Y0={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}},V0={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}},J0={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(a,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,n=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,r=arguments.length>6&&arguments[6]!==void 0?arguments[6]:fc,o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,l="velocity_"+t;if(a.__damp===void 0&&(a.__damp={}),a.__damp[l]===void 0&&(a.__damp[l]=0),Math.abs(a[t]-e)<=o)return a[t]=e,!1;i=Math.max(1e-4,i);var h=2/i,u=r(h*s),c=a[t]-e,d=e,A=n*i;c=Math.min(Math.max(c,-A),A),e=a[t]-c;var f=(a.__damp[l]+h*c)*s;a.__damp[l]=(a.__damp[l]-h*f)*u;var g=e+(c+f)*u;return d-a[t]>0==g>d&&(g=d,a.__damp[l]=(g-d)/s),a[t]=g,!0}var z0=function(t){return t&&t.isCamera},q0=function(t){return t&&t.isLight},Zi=new Q,_o=new It,xo=new It,ts=new At,jn=new Q;function X0(a,t,e,i,s,n,r){typeof t=="number"?Zi.setScalar(t):Array.isArray(t)?Zi.set(t[0],t[1],t[2]):Zi.copy(t);var o=a.parent;a.updateWorldMatrix(!0,!1),jn.setFromMatrixPosition(a.matrixWorld),z0(a)||q0(a)?ts.lookAt(jn,Zi,a.up):ts.lookAt(Zi,jn,a.up),yn(a.quaternion,xo.setFromRotationMatrix(ts),e,i,s,n,r),o&&(ts.extractRotation(o.matrixWorld),_o.setFromRotationMatrix(ts),yn(a.quaternion,xo.copy(a.quaternion).premultiply(_o.invert()),e,i,s,n,r))}function Qi(a,t,e,i,s,n,r,o){return Yt(a,t,a[t]+hc(a[t],e),i,s,n,r,o)}var es=new Kt,Do,Ro;function W0(a,t,e,i,s,n,r){return typeof t=="number"?es.setScalar(t):Array.isArray(t)?es.set(t[0],t[1]):es.copy(t),Do=Yt(a,"x",es.x,e,i,s,n,r),Ro=Yt(a,"y",es.y,e,i,s,n,r),Do||Ro}var Ci=new Q,Lo,bo,wo;function Wr(a,t,e,i,s,n,r){return typeof t=="number"?Ci.setScalar(t):Array.isArray(t)?Ci.set(t[0],t[1],t[2]):Ci.copy(t),Lo=Yt(a,"x",Ci.x,e,i,s,n,r),bo=Yt(a,"y",Ci.y,e,i,s,n,r),wo=Yt(a,"z",Ci.z,e,i,s,n,r),Lo||bo||wo}var ci=new ze,Po,Mo,Fo,ko;function j0(a,t,e,i,s,n,r){return typeof t=="number"?ci.setScalar(t):Array.isArray(t)?ci.set(t[0],t[1],t[2],t[3]):ci.copy(t),Po=Yt(a,"x",ci.x,e,i,s,n,r),Mo=Yt(a,"y",ci.y,e,i,s,n,r),Fo=Yt(a,"z",ci.z,e,i,s,n,r),ko=Yt(a,"w",ci.w,e,i,s,n,r),Po||Mo||Fo||ko}var is=new $e,Oo,Qo,Uo;function Z0(a,t,e,i,s,n,r){return Array.isArray(t)?is.set(t[0],t[1],t[2],t[3]):is.copy(t),Oo=Qi(a,"x",is.x,e,i,s,n,r),Qo=Qi(a,"y",is.y,e,i,s,n,r),Uo=Qi(a,"z",is.z,e,i,s,n,r),Oo||Qo||Uo}var yi=new Ot,Go,No,Ho;function tE(a,t,e,i,s,n,r){return t instanceof Ot?yi.copy(t):Array.isArray(t)?yi.setRGB(t[0],t[1],t[2]):yi.set(t),Go=Yt(a,"r",yi.r,e,i,s,n,r),No=Yt(a,"g",yi.g,e,i,s,n,r),Ho=Yt(a,"b",yi.b,e,i,s,n,r),Go||No||Ho}var pe=new It,ke=new ze,Ko=new ze,ss=new ze,$o,Yo,Vo,Jo;function yn(a,t,e,i,s,n,r){var o=a;Array.isArray(t)?pe.set(t[0],t[1],t[2],t[3]):pe.copy(t);var l=a.dot(pe)>0?1:-1;return pe.x*=l,pe.y*=l,pe.z*=l,pe.w*=l,$o=Yt(a,"x",pe.x,e,i,s,n,r),Yo=Yt(a,"y",pe.y,e,i,s,n,r),Vo=Yt(a,"z",pe.z,e,i,s,n,r),Jo=Yt(a,"w",pe.w,e,i,s,n,r),ke.set(a.x,a.y,a.z,a.w).normalize(),Ko.set(o.__damp.velocity_x,o.__damp.velocity_y,o.__damp.velocity_z,o.__damp.velocity_w),ss.copy(ke).multiplyScalar(Ko.dot(ke)/ke.dot(ke)),o.__damp.velocity_x-=ss.x,o.__damp.velocity_y-=ss.y,o.__damp.velocity_z-=ss.z,o.__damp.velocity_w-=ss.w,a.set(ke.x,ke.y,ke.z,ke.w),$o||Yo||Vo||Jo}var ns=new ya,zo,qo,Xo;function eE(a,t,e,i,s,n,r){return Array.isArray(t)?ns.set(t[0],t[1],t[2]):ns.copy(t),zo=Yt(a,"radius",ns.radius,e,i,s,n,r),qo=Qi(a,"phi",ns.phi,e,i,s,n,r),Xo=Qi(a,"theta",ns.theta,e,i,s,n,r),zo||qo||Xo}var Os=new At,Wo=new Q,jo=new It,Zo=new Q,tl,el,il;function iE(a,t,e,i,s,n,r){var o=a;return o.__damp===void 0&&(o.__damp={position:new Q,rotation:new It,scale:new Q},a.decompose(o.__damp.position,o.__damp.rotation,o.__damp.scale)),Array.isArray(t)?Os.set.apply(Os,Cn(t)):Os.copy(t),Os.decompose(Wo,jo,Zo),tl=Wr(o.__damp.position,Wo,e,i,s,n,r),el=yn(o.__damp.rotation,jo,e,i,s,n,r),il=Wr(o.__damp.scale,Zo,e,i,s,n,r),a.compose(o.__damp.position,o.__damp.rotation,o.__damp.scale),tl||el||il}var si=Object.freeze({__proto__:null,rsqw:G0,exp:fc,linear:N0,sine:H0,cubic:K0,quint:$0,circ:Y0,quart:V0,expo:J0,damp:Yt,dampLookAt:X0,dampAngle:Qi,damp2:W0,damp3:Wr,damp4:j0,dampE:Z0,dampC:tE,dampQ:yn,dampS:eE,dampM:iE});const wa=S.createContext(null);function Pa(){return S.useContext(wa)}function sE({eps:a=1e-5,enabled:t=!0,infinite:e,horizontal:i,pages:s=1,distance:n=1,damping:r=.25,maxSpeed:o=1/0,prepend:l=!1,style:h={},children:u}){const{get:c,setEvents:d,gl:A,size:f,invalidate:g,events:m}=q(),[p]=S.useState(()=>document.createElement("div")),[C]=S.useState(()=>document.createElement("div")),[E]=S.useState(()=>document.createElement("div")),y=A.domElement.parentNode,v=S.useRef(0),T=S.useMemo(()=>({el:p,eps:a,fill:C,fixed:E,horizontal:i,damping:r,offset:0,delta:0,scroll:v,pages:s,range(D,x,M=0){const k=D-M,X=k+x+M*2;return this.offset<k?0:this.offset>X?1:(this.offset-k)/(X-k)},curve(D,x,M=0){return Math.sin(this.range(D,x,M)*Math.PI)},visible(D,x,M=0){const k=D-M,X=k+x+M*2;return this.offset>=k&&this.offset<=X}}),[a,r,i,s]);S.useEffect(()=>{p.style.position="absolute",p.style.width="100%",p.style.height="100%",p.style[i?"overflowX":"overflowY"]="auto",p.style[i?"overflowY":"overflowX"]="hidden",p.style.top="0px",p.style.left="0px";for(const x in h)p.style[x]=h[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",p.appendChild(E),C.style.height=i?"100%":`${s*n*100}%`,C.style.width=i?`${s*n*100}%`:"100%",C.style.pointerEvents="none",p.appendChild(C),l?y.prepend(p):y.appendChild(p),p[i?"scrollLeft":"scrollTop"]=1;const _=m.connected||A.domElement;requestAnimationFrame(()=>m.connect==null?void 0:m.connect(p));const D=c().events.compute;return d({compute(x,M){const{left:k,top:X}=y.getBoundingClientRect(),W=x.clientX-k,H=x.clientY-X;M.pointer.set(W/M.size.width*2-1,-(H/M.size.height)*2+1),M.raycaster.setFromCamera(M.pointer,M.camera)}}),()=>{y.removeChild(p),d({compute:D}),m.connect==null||m.connect(_)}},[s,n,i,p,C,E,y]),S.useEffect(()=>{if(m.connected===p){const _=f[i?"width":"height"],D=p[i?"scrollWidth":"scrollHeight"],x=D-_;let M=0,k=!0,X=!0;const W=()=>{if(!(!t||X)&&(g(),M=p[i?"scrollLeft":"scrollTop"],v.current=M/x,e)){if(!k){if(M>=x){const Y=1-T.offset;p[i?"scrollLeft":"scrollTop"]=1,v.current=T.offset=-Y,k=!0}else if(M<=0){const Y=1+T.offset;p[i?"scrollLeft":"scrollTop"]=D,v.current=T.offset=Y,k=!0}}k&&setTimeout(()=>k=!1,40)}};p.addEventListener("scroll",W,{passive:!0}),requestAnimationFrame(()=>X=!1);const H=Y=>p.scrollLeft+=Y.deltaY/2;return i&&p.addEventListener("wheel",H,{passive:!0}),()=>{p.removeEventListener("scroll",W),i&&p.removeEventListener("wheel",H)}}},[p,m,f,e,T,g,i,t]);let B=0;return Qt((_,D)=>{B=T.offset,si.damp(T,"offset",v.current,r,D,o,void 0,a),si.damp(T,"delta",Math.abs(B-T.offset),r,D,o,void 0,a),T.delta>a&&g()}),S.createElement(wa.Provider,{value:T},u)}const nE=S.forwardRef(({children:a},t)=>{const e=S.useRef(null);S.useImperativeHandle(t,()=>e.current,[]);const i=Pa(),{width:s,height:n}=q(r=>r.viewport);return Qt(()=>{e.current.position.x=i.horizontal?-s*(i.pages-1)*i.offset:0,e.current.position.y=i.horizontal?0:n*(i.pages-1)*i.offset}),S.createElement("group",{ref:e},a)}),rE=S.forwardRef(({children:a,style:t,...e},i)=>{const s=Pa(),n=S.useRef(null);S.useImperativeHandle(i,()=>n.current,[]);const{width:r,height:o}=q(u=>u.size),l=S.useContext(uo),h=S.useMemo(()=>Wp(s.fixed),[s.fixed]);return Qt(()=>{s.delta>s.eps&&(n.current.style.transform=`translate3d(${s.horizontal?-r*(s.pages-1)*s.offset:0}px,${s.horizontal?0:o*(s.pages-1)*-s.offset}px,0)`)}),h.render(S.createElement("div",wt({ref:n,style:{...t,position:"absolute",top:0,left:0,willChange:"transform"}},e),S.createElement(wa.Provider,{value:s},S.createElement(uo.Provider,{value:l},a)))),null}),aE=S.forwardRef(({html:a,...t},e)=>{const i=a?rE:nE;return S.createElement(i,wt({ref:e},t))});function oE({enabled:a=!0,snap:t,global:e,domElement:i,cursor:s=!0,children:n,speed:r=1,rotation:o=[0,0,0],zoom:l=1,polar:h=[0,Math.PI/2],azimuth:u=[-1/0,1/0],damping:c=.25}){const d=q(T=>T.events),A=q(T=>T.gl),f=i||d.connected||A.domElement,{size:g}=q(),m=S.useMemo(()=>[o[0]+h[0],o[0]+h[1]],[o[0],h[0],h[1]]),p=S.useMemo(()=>[o[1]+u[0],o[1]+u[1]],[o[1],u[0],u[1]]),C=S.useMemo(()=>[ot.clamp(o[0],...m),ot.clamp(o[1],...p),o[2]],[o[0],o[1],o[2],m,p]);S.useEffect(()=>{if(e&&s&&a)return f.style.cursor="grab",A.domElement.style.cursor="",()=>{f.style.cursor="default",A.domElement.style.cursor="default"}},[e,s,f,a]);const[E]=S.useState({scale:1,rotation:C,damping:c}),y=S.useRef(null);Qt((T,B)=>{si.damp3(y.current.scale,E.scale,E.damping,B),si.dampE(y.current.rotation,E.rotation,E.damping,B)});const v=Kh({onHover:({last:T})=>{s&&!e&&a&&(f.style.cursor=T?"auto":"grab")},onDrag:({down:T,delta:[B,_],memo:[D,x]=E.rotation||C})=>a?(s&&(f.style.cursor=T?"grabbing":"grab"),B=ot.clamp(x+B/g.width*Math.PI*r,...p),_=ot.clamp(D+_/g.height*Math.PI*r,...m),E.scale=T&&_>m[1]/2?l:1,E.rotation=t&&!T?C:[_,B,0],E.damping=t&&!T&&typeof t!="boolean"?t:c,[_,B]):[_,B]},{target:e?f:void 0});return S.createElement("group",wt({ref:y},v==null?void 0:v()),n)}const lE=a=>(t,e,i)=>{const s=i.subscribe;return i.subscribe=(r,o,l)=>{let h=r;if(o){const u=(l==null?void 0:l.equalityFn)||Object.is;let c=r(i.getState());h=d=>{const A=r(d);if(!u(c,A)){const f=c;o(c=A,f)}},l!=null&&l.fireImmediately&&o(c,c)}return s(h)},a(t,e,i)},hE=lE,gc=S.createContext(null);function cE({map:a,children:t,onChange:e,domElement:i}){const s=a.map(l=>l.name+l.keys).join("-"),n=S.useMemo(()=>Hh(hE(()=>a.reduce((l,h)=>({...l,[h.name]:!1}),{}))),[s]),r=S.useMemo(()=>[n.subscribe,n.getState,n],[s]),o=n.setState;return S.useEffect(()=>{const h=a.map(({name:A,keys:f,up:g})=>({keys:f,up:g,fn:m=>{o({[A]:m}),e&&e(A,m,r[1]())}})).reduce((A,{keys:f,fn:g,up:m=!0})=>(f.forEach(p=>A[p]={fn:g,pressed:!1,up:m}),A),{}),u=({key:A,code:f})=>{const g=h[A]||h[f];if(!g)return;const{fn:m,pressed:p,up:C}=g;g.pressed=!0,(C||!p)&&m(!0)},c=({key:A,code:f})=>{const g=h[A]||h[f];if(!g)return;const{fn:m,up:p}=g;g.pressed=!1,p&&m(!1)},d=i||window;return d.addEventListener("keydown",u,{passive:!0}),d.addEventListener("keyup",c,{passive:!0}),()=>{d.removeEventListener("keydown",u),d.removeEventListener("keyup",c)}},[i,s]),S.createElement(gc.Provider,{value:r,children:t})}function uE(a){const[t,e,i]=S.useContext(gc);return a?i(a):[t,e]}var dE=Object.defineProperty,AE=(a,t,e)=>t in a?dE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,ht=(a,t,e)=>(AE(a,typeof t!="symbol"?t+"":t,e),e);const sl=new Q;let fE=class extends Vi{constructor(t,e){super(),ht(this,"object"),ht(this,"domElement"),ht(this,"enabled",!0),ht(this,"movementSpeed",1),ht(this,"lookSpeed",.005),ht(this,"lookVertical",!0),ht(this,"autoForward",!1),ht(this,"activeLook",!0),ht(this,"heightSpeed",!1),ht(this,"heightCoef",1),ht(this,"heightMin",0),ht(this,"heightMax",1),ht(this,"constrainVertical",!1),ht(this,"verticalMin",0),ht(this,"verticalMax",Math.PI),ht(this,"mouseDragOn",!1),ht(this,"autoSpeedFactor",0),ht(this,"mouseX",0),ht(this,"mouseY",0),ht(this,"moveForward",!1),ht(this,"moveBackward",!1),ht(this,"moveLeft",!1),ht(this,"moveRight",!1),ht(this,"moveUp",!1),ht(this,"moveDown",!1),ht(this,"viewHalfX",0),ht(this,"viewHalfY",0),ht(this,"lat",0),ht(this,"lon",0),ht(this,"lookDirection",new Q),ht(this,"spherical",new ya),ht(this,"target",new Q),ht(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()}),ht(this,"dispose",()=>{var i,s,n,r;(i=this.domElement)==null||i.removeEventListener("contextmenu",this.contextmenu),(s=this.domElement)==null||s.removeEventListener("mousedown",this.onMouseDown),(n=this.domElement)==null||n.removeEventListener("mousemove",this.onMouseMove),(r=this.domElement)==null||r.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}),ht(this,"handleResize",()=>{this.domElement&&(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}),ht(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}),ht(this,"onMouseUp",i=>{if(this.activeLook)switch(i.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}),ht(this,"onMouseMove",i=>{this.domElement&&(this.mouseX=i.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=i.pageY-this.domElement.offsetTop-this.viewHalfY)}),ht(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}}),ht(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}}),ht(this,"lookAt",(i,s,n)=>(i instanceof Q?this.target.copy(i):s&&n&&this.target.set(i,s,n),this.object.lookAt(this.target),this.setOrientation(),this)),ht(this,"update",i=>{if(!this.enabled)return;if(this.heightSpeed){const c=ot.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=i*(c*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 n=i*this.lookSpeed;this.activeLook||(n=0);let r=1;this.constrainVertical&&(r=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.mouseX*n,this.lookVertical&&(this.lat-=this.mouseY*n*r),this.lat=Math.max(-85,Math.min(85,this.lat));let o=ot.degToRad(90-this.lat);const l=ot.degToRad(this.lon);this.constrainVertical&&(o=ot.mapLinear(o,0,Math.PI,this.verticalMin,this.verticalMax));const h=this.object.position;sl.setFromSphericalCoords(1,o,l).add(h),this.object.lookAt(sl)}),ht(this,"contextmenu",i=>i.preventDefault()),ht(this,"setOrientation",()=>{this.lookDirection.set(0,0,-1).applyQuaternion(this.object.quaternion),this.spherical.setFromVector3(this.lookDirection),this.lat=90-ot.radToDeg(this.spherical.phi),this.lon=ot.radToDeg(this.spherical.theta)}),this.object=t,this.domElement=e,this.setOrientation(),e&&this.connect(e)}};var gE=Object.defineProperty,mE=(a,t,e)=>t in a?gE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,O=(a,t,e)=>(mE(a,typeof t!="symbol"?t+"":t,e),e);let pE=class extends Zt{constructor(t,e){super(),O(this,"isTransformControls",!0),O(this,"visible",!1),O(this,"domElement"),O(this,"raycaster",new Pn),O(this,"gizmo"),O(this,"plane"),O(this,"tempVector",new Q),O(this,"tempVector2",new Q),O(this,"tempQuaternion",new It),O(this,"unit",{X:new Q(1,0,0),Y:new Q(0,1,0),Z:new Q(0,0,1)}),O(this,"pointStart",new Q),O(this,"pointEnd",new Q),O(this,"offset",new Q),O(this,"rotationAxis",new Q),O(this,"startNorm",new Q),O(this,"endNorm",new Q),O(this,"rotationAngle",0),O(this,"cameraPosition",new Q),O(this,"cameraQuaternion",new It),O(this,"cameraScale",new Q),O(this,"parentPosition",new Q),O(this,"parentQuaternion",new It),O(this,"parentQuaternionInv",new It),O(this,"parentScale",new Q),O(this,"worldPositionStart",new Q),O(this,"worldQuaternionStart",new It),O(this,"worldScaleStart",new Q),O(this,"worldPosition",new Q),O(this,"worldQuaternion",new It),O(this,"worldQuaternionInv",new It),O(this,"worldScale",new Q),O(this,"eye",new Q),O(this,"positionStart",new Q),O(this,"quaternionStart",new It),O(this,"scaleStart",new Q),O(this,"camera"),O(this,"object"),O(this,"enabled",!0),O(this,"axis",null),O(this,"mode","translate"),O(this,"translationSnap",null),O(this,"rotationSnap",null),O(this,"scaleSnap",null),O(this,"space","world"),O(this,"size",1),O(this,"dragging",!1),O(this,"showX",!0),O(this,"showY",!0),O(this,"showZ",!0),O(this,"changeEvent",{type:"change"}),O(this,"mouseDownEvent",{type:"mouseDown",mode:this.mode}),O(this,"mouseUpEvent",{type:"mouseUp",mode:this.mode}),O(this,"objectChangeEvent",{type:"objectChange"}),O(this,"intersectObjectWithRay",(s,n,r)=>{const o=n.intersectObject(s,!0);for(let l=0;l<o.length;l++)if(o[l].object.visible||r)return o[l];return!1}),O(this,"attach",s=>(this.object=s,this.visible=!0,this)),O(this,"detach",()=>(this.object=void 0,this.visible=!1,this.axis=null,this)),O(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),O(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()}),O(this,"pointerHover",s=>{if(this.object===void 0||this.dragging===!0)return;this.raycaster.setFromCamera(s,this.camera);const n=this.intersectObjectWithRay(this.gizmo.picker[this.mode],this.raycaster);n?this.axis=n.object.name:this.axis=null}),O(this,"pointerDown",s=>{if(!(this.object===void 0||this.dragging===!0||s.button!==0)&&this.axis!==null){this.raycaster.setFromCamera(s,this.camera);const n=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(n){let r=this.space;if(this.mode==="scale"?r="local":(this.axis==="E"||this.axis==="XYZE"||this.axis==="XYZ")&&(r="world"),r==="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(n.point).sub(this.worldPositionStart)}this.dragging=!0,this.mouseDownEvent.mode=this.mode,this.dispatchEvent(this.mouseDownEvent)}}),O(this,"pointerMove",s=>{const n=this.axis,r=this.mode,o=this.object;let l=this.space;if(r==="scale"?l="local":(n==="E"||n==="XYZE"||n==="XYZ")&&(l="world"),o===void 0||n===null||this.dragging===!1||s.button!==-1)return;this.raycaster.setFromCamera(s,this.camera);const h=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(h){if(this.pointEnd.copy(h.point).sub(this.worldPositionStart),r==="translate")this.offset.copy(this.pointEnd).sub(this.pointStart),l==="local"&&n!=="XYZ"&&this.offset.applyQuaternion(this.worldQuaternionInv),n.indexOf("X")===-1&&(this.offset.x=0),n.indexOf("Y")===-1&&(this.offset.y=0),n.indexOf("Z")===-1&&(this.offset.z=0),l==="local"&&n!=="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()),n.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),n.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),n.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)),n.search("X")!==-1&&(o.position.x=Math.round(o.position.x/this.translationSnap)*this.translationSnap),n.search("Y")!==-1&&(o.position.y=Math.round(o.position.y/this.translationSnap)*this.translationSnap),n.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(r==="scale"){if(n.search("XYZ")!==-1){let u=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(u*=-1),this.tempVector2.set(u,u,u)}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),n.search("X")===-1&&(this.tempVector2.x=1),n.search("Y")===-1&&(this.tempVector2.y=1),n.search("Z")===-1&&(this.tempVector2.z=1);o.scale.copy(this.scaleStart).multiply(this.tempVector2),this.scaleSnap&&this.object&&(n.search("X")!==-1&&(this.object.scale.x=Math.round(o.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),n.search("Y")!==-1&&(o.scale.y=Math.round(o.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),n.search("Z")!==-1&&(o.scale.z=Math.round(o.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(r==="rotate"){this.offset.copy(this.pointEnd).sub(this.pointStart);const u=20/this.worldPosition.distanceTo(this.tempVector.setFromMatrixPosition(this.camera.matrixWorld));n==="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):n==="XYZE"?(this.rotationAxis.copy(this.offset).cross(this.eye).normalize(),this.rotationAngle=this.offset.dot(this.tempVector.copy(this.rotationAxis).cross(this.eye))*u):(n==="X"||n==="Y"||n==="Z")&&(this.rotationAxis.copy(this.unit[n]),this.tempVector.copy(this.unit[n]),l==="local"&&this.tempVector.applyQuaternion(this.worldQuaternion),this.rotationAngle=this.offset.dot(this.tempVector.cross(this.eye).normalize())*u),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),l==="local"&&n!=="E"&&n!=="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)}}),O(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)}),O(this,"getPointer",s=>{var n;if(this.domElement&&((n=this.domElement.ownerDocument)!=null&&n.pointerLockElement))return{x:0,y:0,button:s.button};{const r=s.changedTouches?s.changedTouches[0]:s,o=this.domElement.getBoundingClientRect();return{x:(r.clientX-o.left)/o.width*2-1,y:-(r.clientY-o.top)/o.height*2+1,button:s.button}}}),O(this,"onPointerHover",s=>{if(this.enabled)switch(s.pointerType){case"mouse":case"pen":this.pointerHover(this.getPointer(s));break}}),O(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)))}),O(this,"onPointerMove",s=>{this.enabled&&this.pointerMove(this.getPointer(s))}),O(this,"onPointerUp",s=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="",this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.pointerUp(this.getPointer(s)))}),O(this,"getMode",()=>this.mode),O(this,"setMode",s=>{this.mode=s}),O(this,"setTranslationSnap",s=>{this.translationSnap=s}),O(this,"setRotationSnap",s=>{this.rotationSnap=s}),O(this,"setScaleSnap",s=>{this.scaleSnap=s}),O(this,"setSize",s=>{this.size=s}),O(this,"setSpace",s=>{this.space=s}),O(this,"update",()=>{console.warn("THREE.TransformControls: update function has no more functionality and therefore has been deprecated.")}),O(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)}),O(this,"dispose",()=>{var s,n,r,o,l,h;(s=this.domElement)==null||s.removeEventListener("pointerdown",this.onPointerDown),(n=this.domElement)==null||n.removeEventListener("pointermove",this.onPointerHover),(o=(r=this.domElement)==null?void 0:r.ownerDocument)==null||o.removeEventListener("pointermove",this.onPointerMove),(h=(l=this.domElement)==null?void 0:l.ownerDocument)==null||h.removeEventListener("pointerup",this.onPointerUp),this.traverse(u=>{const c=u;c.geometry&&c.geometry.dispose(),c.material&&c.material.dispose()})}),this.domElement=e,this.camera=t,this.gizmo=new EE,this.add(this.gizmo),this.plane=new IE,this.add(this.plane);const i=(s,n)=>{let r=n;Object.defineProperty(this,s,{get:function(){return r!==void 0?r:n},set:function(o){r!==o&&(r=o,this.plane[s]=o,this.gizmo[s]=o,this.dispatchEvent({type:s+"-changed",value:o}),this.dispatchEvent(this.changeEvent))}}),this[s]=n,this.plane[s]=n,this.gizmo[s]=n};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 EE extends Zt{constructor(){super(),O(this,"isTransformControlsGizmo",!0),O(this,"type","TransformControlsGizmo"),O(this,"tempVector",new Q(0,0,0)),O(this,"tempEuler",new $e),O(this,"alignVector",new Q(0,1,0)),O(this,"zeroVector",new Q(0,0,0)),O(this,"lookAtMatrix",new At),O(this,"tempQuaternion",new It),O(this,"tempQuaternion2",new It),O(this,"identityQuaternion",new It),O(this,"unitX",new Q(1,0,0)),O(this,"unitY",new Q(0,1,0)),O(this,"unitZ",new Q(0,0,1)),O(this,"gizmo"),O(this,"picker"),O(this,"helper"),O(this,"rotationAxis",new Q),O(this,"cameraPosition",new Q),O(this,"worldPositionStart",new Q),O(this,"worldQuaternionStart",new It),O(this,"worldPosition",new Q),O(this,"worldQuaternion",new It),O(this,"eye",new Q),O(this,"camera",null),O(this,"enabled",!0),O(this,"axis",null),O(this,"mode","translate"),O(this,"space","world"),O(this,"size",1),O(this,"dragging",!1),O(this,"showX",!0),O(this,"showY",!0),O(this,"showZ",!0),O(this,"updateMatrixWorld",()=>{let F=this.space;this.mode==="scale"&&(F="local");const N=F==="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 K=[];K=K.concat(this.picker[this.mode].children),K=K.concat(this.gizmo[this.mode].children),K=K.concat(this.helper[this.mode].children);for(let $=0;$<K.length;$++){const R=K[$];R.visible=!0,R.rotation.set(0,0,0),R.position.copy(this.worldPosition);let tt;if(this.camera.isOrthographicCamera?tt=(this.camera.top-this.camera.bottom)/this.camera.zoom:tt=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),R.scale.set(1,1,1).multiplyScalar(tt*this.size/7),R.tag==="helper"){R.visible=!1,R.name==="AXIS"?(R.position.copy(this.worldPositionStart),R.visible=!!this.axis,this.axis==="X"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,0)),R.quaternion.copy(N).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(N).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Y"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,Math.PI/2)),R.quaternion.copy(N).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(N).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Z"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),R.quaternion.copy(N).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(N).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="XYZE"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),this.alignVector.copy(this.rotationAxis),R.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.zeroVector,this.alignVector,this.unitY)),R.quaternion.multiply(this.tempQuaternion),R.visible=this.dragging),this.axis==="E"&&(R.visible=!1)):R.name==="START"?(R.position.copy(this.worldPositionStart),R.visible=this.dragging):R.name==="END"?(R.position.copy(this.worldPosition),R.visible=this.dragging):R.name==="DELTA"?(R.position.copy(this.worldPositionStart),R.quaternion.copy(this.worldQuaternionStart),this.tempVector.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),this.tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()),R.scale.copy(this.tempVector),R.visible=this.dragging):(R.quaternion.copy(N),this.dragging?R.position.copy(this.worldPositionStart):R.position.copy(this.worldPosition),this.axis&&(R.visible=this.axis.search(R.name)!==-1));continue}R.quaternion.copy(N),this.mode==="translate"||this.mode==="scale"?((R.name==="X"||R.name==="XYZX")&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(N).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),(R.name==="Y"||R.name==="XYZY")&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(N).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),(R.name==="Z"||R.name==="XYZZ")&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(N).dot(this.eye))>.99&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="XY"&&Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(N).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="YZ"&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(N).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name==="XZ"&&Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(N).dot(this.eye))<.2&&(R.scale.set(1e-10,1e-10,1e-10),R.visible=!1),R.name.search("X")!==-1&&(this.alignVector.copy(this.unitX).applyQuaternion(N).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.x*=-1:R.tag==="bwd"&&(R.visible=!1)),R.name.search("Y")!==-1&&(this.alignVector.copy(this.unitY).applyQuaternion(N).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.y*=-1:R.tag==="bwd"&&(R.visible=!1)),R.name.search("Z")!==-1&&(this.alignVector.copy(this.unitZ).applyQuaternion(N).dot(this.eye)<0?R.tag==="fwd"?R.visible=!1:R.scale.z*=-1:R.tag==="bwd"&&(R.visible=!1))):this.mode==="rotate"&&(this.tempQuaternion2.copy(N),this.alignVector.copy(this.eye).applyQuaternion(this.tempQuaternion.copy(N).invert()),R.name.search("E")!==-1&&R.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.eye,this.zeroVector,this.unitY)),R.name==="X"&&(this.tempQuaternion.setFromAxisAngle(this.unitX,Math.atan2(-this.alignVector.y,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion)),R.name==="Y"&&(this.tempQuaternion.setFromAxisAngle(this.unitY,Math.atan2(this.alignVector.x,this.alignVector.z)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion)),R.name==="Z"&&(this.tempQuaternion.setFromAxisAngle(this.unitZ,Math.atan2(this.alignVector.y,this.alignVector.x)),this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2,this.tempQuaternion),R.quaternion.copy(this.tempQuaternion))),R.visible=R.visible&&(R.name.indexOf("X")===-1||this.showX),R.visible=R.visible&&(R.name.indexOf("Y")===-1||this.showY),R.visible=R.visible&&(R.name.indexOf("Z")===-1||this.showZ),R.visible=R.visible&&(R.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),R.material.tempOpacity=R.material.tempOpacity||R.material.opacity,R.material.tempColor=R.material.tempColor||R.material.color.clone(),R.material.color.copy(R.material.tempColor),R.material.opacity=R.material.tempOpacity,this.enabled?this.axis&&(R.name===this.axis?(R.material.opacity=1,R.material.color.lerp(new Ot(1,1,1),.5)):this.axis.split("").some(function(it){return R.name===it})?(R.material.opacity=1,R.material.color.lerp(new Ot(1,1,1),.5)):(R.material.opacity*=.25,R.material.color.lerp(new Ot(1,1,1),.5))):(R.material.opacity*=.5,R.material.color.lerp(new Ot(1,1,1),.5))}super.updateMatrixWorld()});const t=new va({depthTest:!1,depthWrite:!1,transparent:!0,side:Rs,fog:!1,toneMapped:!1}),e=new ps({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 n=t.clone();n.color.set(16711680);const r=t.clone();r.color.set(65280);const o=t.clone();o.color.set(255);const l=t.clone();l.opacity=.25;const h=l.clone();h.color.set(16776960);const u=l.clone();u.color.set(65535);const c=l.clone();c.color.set(16711935),t.clone().color.set(16776960);const A=e.clone();A.color.set(16711680);const f=e.clone();f.color.set(65280);const g=e.clone();g.color.set(255);const m=e.clone();m.color.set(65535);const p=e.clone();p.color.set(16711935);const C=e.clone();C.color.set(16776960);const E=e.clone();E.color.set(7895160);const y=C.clone();y.opacity=.25;const v=new me(0,.05,.2,12,1,!1),T=new oi(.125,.125,.125),B=new ve;B.setAttribute("position",new He([0,0,0,1,0,0],3));const _=(F,N)=>{const K=new ve,$=[];for(let R=0;R<=64*N;++R)$.push(0,Math.cos(R/32*Math.PI)*F,Math.sin(R/32*Math.PI)*F);return K.setAttribute("position",new He($,3)),K},D=()=>{const F=new ve;return F.setAttribute("position",new He([0,0,0,1,1,1],3)),F},x={X:[[new rt(v,n),[1,0,0],[0,0,-Math.PI/2],null,"fwd"],[new rt(v,n),[1,0,0],[0,0,Math.PI/2],null,"bwd"],[new pt(B,A)]],Y:[[new rt(v,r),[0,1,0],null,null,"fwd"],[new rt(v,r),[0,1,0],[Math.PI,0,0],null,"bwd"],[new pt(B,f),null,[0,0,Math.PI/2]]],Z:[[new rt(v,o),[0,0,1],[Math.PI/2,0,0],null,"fwd"],[new rt(v,o),[0,0,1],[-Math.PI/2,0,0],null,"bwd"],[new pt(B,g),null,[0,-Math.PI/2,0]]],XYZ:[[new rt(new li(.1,0),l.clone()),[0,0,0],[0,0,0]]],XY:[[new rt(new fi(.295,.295),h.clone()),[.15,.15,0]],[new pt(B,C),[.18,.3,0],null,[.125,1,1]],[new pt(B,C),[.3,.18,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new rt(new fi(.295,.295),u.clone()),[0,.15,.15],[0,Math.PI/2,0]],[new pt(B,m),[0,.18,.3],[0,0,Math.PI/2],[.125,1,1]],[new pt(B,m),[0,.3,.18],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new rt(new fi(.295,.295),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]],[new pt(B,p),[.18,0,.3],null,[.125,1,1]],[new pt(B,p),[.3,0,.18],[0,-Math.PI/2,0],[.125,1,1]]]},M={X:[[new rt(new me(.2,0,1,4,1,!1),i),[.6,0,0],[0,0,-Math.PI/2]]],Y:[[new rt(new me(.2,0,1,4,1,!1),i),[0,.6,0]]],Z:[[new rt(new me(.2,0,1,4,1,!1),i),[0,0,.6],[Math.PI/2,0,0]]],XYZ:[[new rt(new li(.2,0),i)]],XY:[[new rt(new fi(.4,.4),i),[.2,.2,0]]],YZ:[[new rt(new fi(.4,.4),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new rt(new fi(.4,.4),i),[.2,0,.2],[-Math.PI/2,0,0]]]},k={START:[[new rt(new li(.01,2),s),null,null,null,"helper"]],END:[[new rt(new li(.01,2),s),null,null,null,"helper"]],DELTA:[[new pt(D(),s),null,null,null,"helper"]],X:[[new pt(B,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new pt(B,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new pt(B,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},X={X:[[new pt(_(1,.5),A)],[new rt(new li(.04,0),n),[0,0,.99],null,[1,3,1]]],Y:[[new pt(_(1,.5),f),null,[0,0,-Math.PI/2]],[new rt(new li(.04,0),r),[0,0,.99],null,[3,1,1]]],Z:[[new pt(_(1,.5),g),null,[0,Math.PI/2,0]],[new rt(new li(.04,0),o),[.99,0,0],null,[1,3,1]]],E:[[new pt(_(1.25,1),y),null,[0,Math.PI/2,0]],[new rt(new me(.03,0,.15,4,1,!1),y),[1.17,0,0],[0,0,-Math.PI/2],[1,1,.001]],[new rt(new me(.03,0,.15,4,1,!1),y),[-1.17,0,0],[0,0,Math.PI/2],[1,1,.001]],[new rt(new me(.03,0,.15,4,1,!1),y),[0,-1.17,0],[Math.PI,0,0],[1,1,.001]],[new rt(new me(.03,0,.15,4,1,!1),y),[0,1.17,0],[0,0,0],[1,1,.001]]],XYZE:[[new pt(_(1,1),E),null,[0,Math.PI/2,0]]]},W={AXIS:[[new pt(B,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},H={X:[[new rt(new Ps(1,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new rt(new Ps(1,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new rt(new Ps(1,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new rt(new Ps(1.25,.1,2,24),i)]],XYZE:[[new rt(new $h(.7,10,8),i)]]},Y={X:[[new rt(T,n),[.8,0,0],[0,0,-Math.PI/2]],[new pt(B,A),null,null,[.8,1,1]]],Y:[[new rt(T,r),[0,.8,0]],[new pt(B,f),null,[0,0,Math.PI/2],[.8,1,1]]],Z:[[new rt(T,o),[0,0,.8],[Math.PI/2,0,0]],[new pt(B,g),null,[0,-Math.PI/2,0],[.8,1,1]]],XY:[[new rt(T,h),[.85,.85,0],null,[2,2,.2]],[new pt(B,C),[.855,.98,0],null,[.125,1,1]],[new pt(B,C),[.98,.855,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new rt(T,u),[0,.85,.85],null,[.2,2,2]],[new pt(B,m),[0,.855,.98],[0,0,Math.PI/2],[.125,1,1]],[new pt(B,m),[0,.98,.855],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new rt(T,c),[.85,0,.85],null,[2,.2,2]],[new pt(B,p),[.855,0,.98],null,[.125,1,1]],[new pt(B,p),[.98,0,.855],[0,-Math.PI/2,0],[.125,1,1]]],XYZX:[[new rt(new oi(.125,.125,.125),l.clone()),[1.1,0,0]]],XYZY:[[new rt(new oi(.125,.125,.125),l.clone()),[0,1.1,0]]],XYZZ:[[new rt(new oi(.125,.125,.125),l.clone()),[0,0,1.1]]]},z={X:[[new rt(new me(.2,0,.8,4,1,!1),i),[.5,0,0],[0,0,-Math.PI/2]]],Y:[[new rt(new me(.2,0,.8,4,1,!1),i),[0,.5,0]]],Z:[[new rt(new me(.2,0,.8,4,1,!1),i),[0,0,.5],[Math.PI/2,0,0]]],XY:[[new rt(T,i),[.85,.85,0],null,[3,3,.2]]],YZ:[[new rt(T,i),[0,.85,.85],null,[.2,3,3]]],XZ:[[new rt(T,i),[.85,0,.85],null,[3,.2,3]]],XYZX:[[new rt(new oi(.2,.2,.2),i),[1.1,0,0]]],XYZY:[[new rt(new oi(.2,.2,.2),i),[0,1.1,0]]],XYZZ:[[new rt(new oi(.2,.2,.2),i),[0,0,1.1]]]},J={X:[[new pt(B,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new pt(B,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new pt(B,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},U=F=>{const N=new Zt;for(let K in F)for(let $=F[K].length;$--;){const R=F[K][$][0].clone(),tt=F[K][$][1],it=F[K][$][2],lt=F[K][$][3],Dt=F[K][$][4];R.name=K,R.tag=Dt,tt&&R.position.set(tt[0],tt[1],tt[2]),it&&R.rotation.set(it[0],it[1],it[2]),lt&&R.scale.set(lt[0],lt[1],lt[2]),R.updateMatrix();const qt=R.geometry.clone();qt.applyMatrix4(R.matrix),R.geometry=qt,R.renderOrder=1/0,R.position.set(0,0,0),R.rotation.set(0,0,0),R.scale.set(1,1,1),N.add(R)}return N};this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=U(x)),this.add(this.gizmo.rotate=U(X)),this.add(this.gizmo.scale=U(Y)),this.add(this.picker.translate=U(M)),this.add(this.picker.rotate=U(H)),this.add(this.picker.scale=U(z)),this.add(this.helper.translate=U(k)),this.add(this.helper.rotate=U(W)),this.add(this.helper.scale=U(J)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}}class IE extends rt{constructor(){super(new fi(1e5,1e5,2,2),new va({visible:!1,wireframe:!0,side:Rs,transparent:!0,opacity:.1,toneMapped:!1})),O(this,"isTransformControlsPlane",!0),O(this,"type","TransformControlsPlane"),O(this,"unitX",new Q(1,0,0)),O(this,"unitY",new Q(0,1,0)),O(this,"unitZ",new Q(0,0,1)),O(this,"tempVector",new Q),O(this,"dirVector",new Q),O(this,"alignVector",new Q),O(this,"tempMatrix",new At),O(this,"identityQuaternion",new It),O(this,"cameraQuaternion",new It),O(this,"worldPosition",new Q),O(this,"worldQuaternion",new It),O(this,"eye",new Q),O(this,"axis",null),O(this,"mode","translate"),O(this,"space","world"),O(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 CE=Object.defineProperty,yE=(a,t,e)=>t in a?CE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Ut=(a,t,e)=>(yE(a,typeof t!="symbol"?t+"":t,e),e);const vi=new $e(0,0,0,"YXZ"),Bi=new Q,vE={type:"change"},BE={type:"lock"},SE={type:"unlock"},nl=Math.PI/2;let TE=class extends Vi{constructor(t,e){super(),Ut(this,"camera"),Ut(this,"domElement"),Ut(this,"isLocked"),Ut(this,"minPolarAngle"),Ut(this,"maxPolarAngle"),Ut(this,"pointerSpeed"),Ut(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(nl-this.maxPolarAngle,Math.min(nl-this.minPolarAngle,vi.x)),this.camera.quaternion.setFromEuler(vi),this.dispatchEvent(vE))}),Ut(this,"onPointerlockChange",()=>{this.domElement&&(this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(BE),this.isLocked=!0):(this.dispatchEvent(SE),this.isLocked=!1))}),Ut(this,"onPointerlockError",()=>{console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}),Ut(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))}),Ut(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))}),Ut(this,"dispose",()=>{this.disconnect()}),Ut(this,"getObject",()=>this.camera),Ut(this,"direction",new Q(0,0,-1)),Ut(this,"getDirection",i=>i.copy(this.direction).applyQuaternion(this.camera.quaternion)),Ut(this,"moveForward",i=>{Bi.setFromMatrixColumn(this.camera.matrix,0),Bi.crossVectors(this.camera.up,Bi),this.camera.position.addScaledVector(Bi,i)}),Ut(this,"moveRight",i=>{Bi.setFromMatrixColumn(this.camera.matrix,0),this.camera.position.addScaledVector(Bi,i)}),Ut(this,"lock",()=>{this.domElement&&this.domElement.requestPointerLock()}),Ut(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 _E=Object.defineProperty,xE=(a,t,e)=>t in a?_E(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Gt=(a,t,e)=>(xE(a,typeof t!="symbol"?t+"":t,e),e);let DE=class extends Vi{constructor(t){super(),Gt(this,"object"),Gt(this,"changeEvent",{type:"change"}),Gt(this,"EPS",1e-6),Gt(this,"enabled",!0),Gt(this,"deviceOrientation",{alpha:0,beta:0,gamma:0}),Gt(this,"screenOrientation",0),Gt(this,"alphaOffset",0),Gt(this,"onDeviceOrientationChangeEvent",e=>{this.deviceOrientation=e}),Gt(this,"onScreenOrientationChangeEvent",()=>{this.screenOrientation=window.orientation||0}),Gt(this,"zee",new Q(0,0,1)),Gt(this,"euler",new $e),Gt(this,"q0",new It),Gt(this,"q1",new It(-Math.sqrt(.5),0,0,Math.sqrt(.5))),Gt(this,"setObjectQuaternion",(e,i,s,n,r)=>{this.euler.set(s,i,-n,"YXZ"),e.setFromEuler(this.euler),e.multiply(this.q1),e.multiply(this.q0.setFromAxisAngle(this.zee,-r))}),Gt(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}),Gt(this,"disconnect",()=>{window.removeEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.removeEventListener("deviceorientation",this.onDeviceOrientationChangeEvent),this.enabled=!1}),Gt(this,"lastQuaternion",new It),Gt(this,"update",()=>{if(this.enabled===!1)return;const e=this.deviceOrientation;if(e){const i=e.alpha?ot.degToRad(e.alpha)+this.alphaOffset:0,s=e.beta?ot.degToRad(e.beta):0,n=e.gamma?ot.degToRad(e.gamma):0,r=this.screenOrientation?ot.degToRad(this.screenOrientation):0;this.setObjectQuaternion(this.object.quaternion,i,s,n,r),8*(1-this.lastQuaternion.dot(this.object.quaternion))>this.EPS&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(this.changeEvent))}}),Gt(this,"dispose",()=>this.disconnect()),this.object=t,this.object.rotation.reorder("YXZ"),this.connect()}};var RE=Object.defineProperty,LE=(a,t,e)=>t in a?RE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,V=(a,t,e)=>(LE(a,typeof t!="symbol"?t+"":t,e),e);let bE=class extends Vi{constructor(t,e){super(),V(this,"enabled",!0),V(this,"screen",{left:0,top:0,width:0,height:0}),V(this,"rotateSpeed",1),V(this,"zoomSpeed",1.2),V(this,"panSpeed",.3),V(this,"noRotate",!1),V(this,"noZoom",!1),V(this,"noPan",!1),V(this,"staticMoving",!1),V(this,"dynamicDampingFactor",.2),V(this,"minDistance",0),V(this,"maxDistance",1/0),V(this,"keys",["KeyA","KeyS","KeyD"]),V(this,"mouseButtons",{LEFT:zn.ROTATE,MIDDLE:zn.DOLLY,RIGHT:zn.PAN}),V(this,"object"),V(this,"domElement"),V(this,"cursorZoom",!1),V(this,"target",new Q),V(this,"mousePosition",new Kt),V(this,"STATE",{NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4}),V(this,"EPS",1e-6),V(this,"lastZoom",1),V(this,"lastPosition",new Q),V(this,"cursorVector",new Q),V(this,"targetVector",new Q),V(this,"_state",this.STATE.NONE),V(this,"_keyState",this.STATE.NONE),V(this,"_eye",new Q),V(this,"_movePrev",new Kt),V(this,"_moveCurr",new Kt),V(this,"_lastAxis",new Q),V(this,"_lastAngle",0),V(this,"_zoomStart",new Kt),V(this,"_zoomEnd",new Kt),V(this,"_touchZoomDistanceStart",0),V(this,"_touchZoomDistanceEnd",0),V(this,"_panStart",new Kt),V(this,"_panEnd",new Kt),V(this,"target0"),V(this,"position0"),V(this,"up0"),V(this,"zoom0"),V(this,"changeEvent",{type:"change"}),V(this,"startEvent",{type:"start"}),V(this,"endEvent",{type:"end"}),V(this,"onScreenVector",new Kt),V(this,"getMouseOnScreen",(i,s)=>(this.onScreenVector.set((i-this.screen.left)/this.screen.width,(s-this.screen.top)/this.screen.height),this.onScreenVector)),V(this,"onCircleVector",new Kt),V(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)),V(this,"axis",new Q),V(this,"quaternion",new It),V(this,"eyeDirection",new Q),V(this,"objectUpDirection",new Q),V(this,"objectSidewaysDirection",new Q),V(this,"moveDirection",new Q),V(this,"angle",0),V(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)}),V(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()}}),V(this,"mouseChange",new Kt),V(this,"objectUp",new Q),V(this,"pan",new Q),V(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,n=(i.top-i.bottom)/this.object.zoom;this.mouseChange.x*=s,this.mouseChange.y*=n}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))}}),V(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)))}),V(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}),V(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")}),V(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}),V(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)))}),V(this,"onPointerDown",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseDown(i);break}}),V(this,"onPointerMove",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseMove(i);break}}),V(this,"onPointerUp",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseUp();break}}),V(this,"keyup",()=>{this.enabled!==!1&&(this._keyState=this.STATE.NONE,window.addEventListener("keydown",this.keydown))}),V(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)}),V(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))}),V(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))}),V(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)}}),V(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,n=i.touches[0].pageY-i.touches[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(s*s+n*n);const r=(i.touches[0].pageX+i.touches[1].pageX)/2,o=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panStart.copy(this.getMouseOnScreen(r,o)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(this.startEvent)}}),V(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,n=i.touches[0].pageY-i.touches[1].pageY;this._touchZoomDistanceEnd=Math.sqrt(s*s+n*n);const r=(i.touches[0].pageX+i.touches[1].pageX)/2,o=(i.touches[0].pageY+i.touches[1].pageY)/2;this._panEnd.copy(this.getMouseOnScreen(r,o));break}}),V(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)}}),V(this,"contextmenu",i=>{this.enabled!==!1&&i.preventDefault()}),V(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()}),V(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 wE=Object.defineProperty,PE=(a,t,e)=>t in a?wE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,w=(a,t,e)=>(PE(a,typeof t!="symbol"?t+"":t,e),e);const st={IDLE:Symbol(),ROTATE:Symbol(),PAN:Symbol(),SCALE:Symbol(),FOV:Symbol(),FOCUS:Symbol(),ZROTATE:Symbol(),ANIMATION_FOCUS:Symbol(),ANIMATION_ROTATE:Symbol()},Tt={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()},ut={x:0,y:0},ne={camera:new At,gizmos:new At},bt={type:"change"},Ee={type:"start"},he={type:"end"};let ME=class extends Vi{constructor(t,e=null,i=null){super(),w(this,"camera"),w(this,"domElement"),w(this,"scene"),w(this,"mouseActions"),w(this,"_mouseOp"),w(this,"_v2_1"),w(this,"_v3_1"),w(this,"_v3_2"),w(this,"_m4_1"),w(this,"_m4_2"),w(this,"_quat"),w(this,"_translationMatrix"),w(this,"_rotationMatrix"),w(this,"_scaleMatrix"),w(this,"_rotationAxis"),w(this,"_cameraMatrixState"),w(this,"_cameraProjectionState"),w(this,"_fovState"),w(this,"_upState"),w(this,"_zoomState"),w(this,"_nearPos"),w(this,"_farPos"),w(this,"_gizmoMatrixState"),w(this,"_up0"),w(this,"_zoom0"),w(this,"_fov0"),w(this,"_initialNear"),w(this,"_nearPos0"),w(this,"_initialFar"),w(this,"_farPos0"),w(this,"_cameraMatrixState0"),w(this,"_gizmoMatrixState0"),w(this,"_button"),w(this,"_touchStart"),w(this,"_touchCurrent"),w(this,"_input"),w(this,"_switchSensibility"),w(this,"_startFingerDistance"),w(this,"_currentFingerDistance"),w(this,"_startFingerRotation"),w(this,"_currentFingerRotation"),w(this,"_devPxRatio"),w(this,"_downValid"),w(this,"_nclicks"),w(this,"_downEvents"),w(this,"_clickStart"),w(this,"_maxDownTime"),w(this,"_maxInterval"),w(this,"_posThreshold"),w(this,"_movementThreshold"),w(this,"_currentCursorPosition"),w(this,"_startCursorPosition"),w(this,"_grid"),w(this,"_gridPosition"),w(this,"_gizmos"),w(this,"_curvePts"),w(this,"_timeStart"),w(this,"_animationId"),w(this,"focusAnimationTime"),w(this,"_timePrev"),w(this,"_timeCurrent"),w(this,"_anglePrev"),w(this,"_angleCurrent"),w(this,"_cursorPosPrev"),w(this,"_cursorPosCurr"),w(this,"_wPrev"),w(this,"_wCurr"),w(this,"adjustNearFar"),w(this,"scaleFactor"),w(this,"dampingFactor"),w(this,"wMax"),w(this,"enableAnimations"),w(this,"enableGrid"),w(this,"cursorZoom"),w(this,"minFov"),w(this,"maxFov"),w(this,"enabled"),w(this,"enablePan"),w(this,"enableRotate"),w(this,"enableZoom"),w(this,"minDistance"),w(this,"maxDistance"),w(this,"minZoom"),w(this,"maxZoom"),w(this,"target"),w(this,"_currentTarget"),w(this,"_tbRadius"),w(this,"_state"),w(this,"onWindowResize",()=>{const s=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3;if(this.camera){const h=this.calculateTbRadius(this.camera);h!==void 0&&(this._tbRadius=h)}const n=this._tbRadius/s,o=new qn(0,0,n,n).getPoints(this._curvePts),l=new ve().setFromPoints(o);for(const h in this._gizmos.children){const u=this._gizmos.children[h];u.geometry=l}this.dispatchEvent(bt)}),w(this,"onContextMenu",s=>{if(this.enabled){for(let n=0;n<this.mouseActions.length;n++)if(this.mouseActions[n].mouse==2){s.preventDefault();break}}}),w(this,"onPointerCancel",()=>{this._touchStart.splice(0,this._touchStart.length),this._touchCurrent.splice(0,this._touchCurrent.length),this._input=Tt.NONE}),w(this,"onPointerDown",s=>{if(s.button==0&&s.isPrimary?(this._downValid=!0,this._downEvents.push(s)):this._downValid=!1,s.pointerType=="touch"&&this._input!=Tt.CURSOR)switch(this._touchStart.push(s),this._touchCurrent.push(s),this._input){case Tt.NONE:this._input=Tt.ONE_FINGER,this.onSinglePanStart(s,"ROTATE"),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp);break;case Tt.ONE_FINGER:case Tt.ONE_FINGER_SWITCHED:this._input=Tt.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case Tt.TWO_FINGER:this._input=Tt.MULT_FINGER,this.onTriplePanStart();break}else if(s.pointerType!="touch"&&this._input==Tt.NONE){let n=null;s.ctrlKey||s.metaKey?n="CTRL":s.shiftKey&&(n="SHIFT"),this._mouseOp=this.getOpFromAction(s.button,n),this._mouseOp&&(window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),this._input=Tt.CURSOR,this._button=s.button,this.onSinglePanStart(s,this._mouseOp))}}),w(this,"onPointerMove",s=>{if(s.pointerType=="touch"&&this._input!=Tt.CURSOR)switch(this._input){case Tt.ONE_FINGER:this.updateTouchEvent(s),this.onSinglePanMove(s,st.ROTATE);break;case Tt.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],s)*this._devPxRatio>=this._switchSensibility){this._input=Tt.ONE_FINGER,this.updateTouchEvent(s),this.onSinglePanStart(s,"ROTATE");break}break;case Tt.TWO_FINGER:this.updateTouchEvent(s),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case Tt.MULT_FINGER:this.updateTouchEvent(s),this.onTriplePanMove();break}else if(s.pointerType!="touch"&&this._input==Tt.CURSOR){let n=null;s.ctrlKey||s.metaKey?n="CTRL":s.shiftKey&&(n="SHIFT");const r=this.getOpStateFromAction(this._button,n);r&&this.onSinglePanMove(s,r)}this._downValid&&this.calculatePointersDistance(this._downEvents[this._downEvents.length-1],s)*this._devPxRatio>this._movementThreshold&&(this._downValid=!1)}),w(this,"onPointerUp",s=>{if(s.pointerType=="touch"&&this._input!=Tt.CURSOR){const n=this._touchCurrent.length;for(let r=0;r<n;r++)if(this._touchCurrent[r].pointerId==s.pointerId){this._touchCurrent.splice(r,1),this._touchStart.splice(r,1);break}switch(this._input){case Tt.ONE_FINGER:case Tt.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Tt.NONE,this.onSinglePanEnd();break;case Tt.TWO_FINGER:this.onDoublePanEnd(),this.onPinchEnd(),this.onRotateEnd(),this._input=Tt.ONE_FINGER_SWITCHED;break;case Tt.MULT_FINGER:this._touchCurrent.length==0&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Tt.NONE,this.onTriplePanEnd());break}}else s.pointerType!="touch"&&this._input==Tt.CURSOR&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Tt.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 r=s.timeStamp-this._clickStart,o=this.calculatePointersDistance(this._downEvents[1],this._downEvents[0])*this._devPxRatio;r<=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)}),w(this,"onWheel",s=>{var n,r;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 h=125;let u=s.deltaY/h,c=1;switch(u>0?c=1/this.scaleFactor:u<0&&(c=this.scaleFactor),l){case"ZOOM":if(this.updateTbState(st.SCALE,!0),u>0?c=1/Math.pow(this.scaleFactor,u):u<0&&(c=Math.pow(this.scaleFactor,-u)),this.cursorZoom&&this.enablePan){let d;this.camera instanceof re&&(d=(n=this.unprojectOnTbPlane(this.camera,s.clientX,s.clientY,this.domElement))==null?void 0:n.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position)),this.camera instanceof Nt&&(d=(r=this.unprojectOnTbPlane(this.camera,s.clientX,s.clientY,this.domElement))==null?void 0:r.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)),d!==void 0&&this.applyTransformMatrix(this.applyScale(c,d))}else this.applyTransformMatrix(this.applyScale(c,this._gizmos.position));this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(st.IDLE,!1),this.dispatchEvent(bt),this.dispatchEvent(he);break;case"FOV":if(this.camera instanceof Nt){this.updateTbState(st.FOV,!0),s.deltaX!=0&&(u=s.deltaX/h,c=1,u>0?c=1/Math.pow(this.scaleFactor,u):u<0&&(c=Math.pow(this.scaleFactor,-u))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const d=this._v3_1.distanceTo(this._gizmos.position);let A=d/c;A=ot.clamp(A,this.minDistance,this.maxDistance);const f=d*Math.tan(ot.DEG2RAD*this.camera.fov*.5);let g=ot.RAD2DEG*(Math.atan(f/A)*2);g>this.maxFov?g=this.maxFov:g<this.minFov&&(g=this.minFov);const m=f/Math.tan(ot.DEG2RAD*(g/2));c=d/m,this.setFov(g),this.applyTransformMatrix(this.applyScale(c,this._gizmos.position,!1))}this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(st.IDLE,!1),this.dispatchEvent(bt),this.dispatchEvent(he);break}}}}),w(this,"onSinglePanStart",(s,n)=>{if(this.enabled&&this.domElement)switch(this.dispatchEvent(Ee),this.setCenter(s.clientX,s.clientY),n){case"PAN":if(!this.enablePan)return;if(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(bt)),this.camera){this.updateTbState(st.PAN,!0);const r=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement);r!==void 0&&this._startCursorPosition.copy(r),this.enableGrid&&(this.drawGrid(),this.dispatchEvent(bt))}break;case"ROTATE":if(!this.enableRotate)return;if(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1),this.camera){this.updateTbState(st.ROTATE,!0);const r=this.unprojectOnTbSurface(this.camera,ut.x,ut.y,this.domElement,this._tbRadius);r!==void 0&&this._startCursorPosition.copy(r),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(bt);break;case"FOV":if(!this.enableZoom)return;this.camera instanceof Nt&&(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(bt)),this.updateTbState(st.FOV,!0),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.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(bt)),this.updateTbState(st.SCALE,!0),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition);break}}),w(this,"onSinglePanMove",(s,n)=>{if(this.enabled&&this.domElement){const r=n!=this._state;switch(this.setCenter(s.clientX,s.clientY),n){case st.PAN:if(this.enablePan&&this.camera)if(r){this.dispatchEvent(he),this.dispatchEvent(Ee),this.updateTbState(n,!0);const o=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement);o!==void 0&&this._startCursorPosition.copy(o),this.enableGrid&&this.drawGrid(),this.activateGizmos(!1)}else{const o=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement);o!==void 0&&this._currentCursorPosition.copy(o),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition))}break;case st.ROTATE:if(this.enableRotate&&this.camera)if(r){this.dispatchEvent(he),this.dispatchEvent(Ee),this.updateTbState(n,!0);const o=this.unprojectOnTbSurface(this.camera,ut.x,ut.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,ut.x,ut.y,this.domElement,this._tbRadius);o!==void 0&&this._currentCursorPosition.copy(o);const l=this._startCursorPosition.distanceTo(this._currentCursorPosition),h=this._startCursorPosition.angleTo(this._currentCursorPosition),u=Math.max(l/this._tbRadius,h);this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition,this._currentCursorPosition),u)),this.enableAnimations&&(this._timePrev=this._timeCurrent,this._timeCurrent=performance.now(),this._anglePrev=this._angleCurrent,this._angleCurrent=u,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 st.SCALE:if(this.enableZoom)if(r)this.dispatchEvent(he),this.dispatchEvent(Ee),this.updateTbState(n,!0),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let h=1;l<0?h=1/Math.pow(this.scaleFactor,-l*8):l>0&&(h=Math.pow(this.scaleFactor,l*8)),this.applyTransformMatrix(this.applyScale(h,this._gizmos.position))}break;case st.FOV:if(this.enableZoom&&this.camera instanceof Nt)if(r)this.dispatchEvent(he),this.dispatchEvent(Ee),this.updateTbState(n,!0),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1);else{this._currentCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let h=1;l<0?h=1/Math.pow(this.scaleFactor,-l*8):l>0&&(h=Math.pow(this.scaleFactor,l*8)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const u=this._v3_1.distanceTo(this._gizmos.position);let c=u/h;c=ot.clamp(c,this.minDistance,this.maxDistance);const d=u*Math.tan(ot.DEG2RAD*this._fovState*.5);let A=ot.RAD2DEG*(Math.atan(d/c)*2);A=ot.clamp(A,this.minFov,this.maxFov);const f=d/Math.tan(ot.DEG2RAD*(A/2));h=u/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(A),this.applyTransformMatrix(this.applyScale(h,this._v3_2,!1));const g=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(f/u);this._m4_1.makeTranslation(g.x,g.y,g.z)}break}this.dispatchEvent(bt)}}),w(this,"onSinglePanEnd",()=>{if(this._state==st.ROTATE){if(!this.enableRotate)return;if(this.enableAnimations)if(performance.now()-this._timeCurrent<120){const n=Math.abs((this._wPrev+this._wCurr)/2),r=this;this._animationId=window.requestAnimationFrame(function(o){r.updateTbState(st.ANIMATION_ROTATE,!0);const l=r.calculateRotationAxis(r._cursorPosPrev,r._cursorPosCurr);r.onRotationAnim(o,l,Math.min(n,r.wMax))})}else this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(bt);else this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(bt)}else(this._state==st.PAN||this._state==st.IDLE)&&(this.updateTbState(st.IDLE,!1),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1),this.dispatchEvent(bt));this.dispatchEvent(he)}),w(this,"onDoubleTap",s=>{if(this.enabled&&this.enablePan&&this.scene&&this.camera&&this.domElement){this.dispatchEvent(Ee),this.setCenter(s.clientX,s.clientY);const n=this.unprojectOnObj(this.getCursorNDC(ut.x,ut.y,this.domElement),this.camera);if(n&&this.enableAnimations){const r=this;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),this._timeStart=-1,this._animationId=window.requestAnimationFrame(function(o){r.updateTbState(st.ANIMATION_FOCUS,!0),r.onFocusAnim(o,n,r._cameraMatrixState,r._gizmoMatrixState)})}else n&&!this.enableAnimations&&(this.updateTbState(st.FOCUS,!0),this.focus(n,this.scaleFactor),this.updateTbState(st.IDLE,!1),this.dispatchEvent(bt))}this.dispatchEvent(he)}),w(this,"onDoublePanStart",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.dispatchEvent(Ee),this.updateTbState(st.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,ut.x,ut.y,this.domElement,!0);s!==void 0&&this._startCursorPosition.copy(s),this._currentCursorPosition.copy(this._startCursorPosition),this.activateGizmos(!1)}}),w(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!=st.PAN&&(this.updateTbState(st.PAN,!0),this._startCursorPosition.copy(this._currentCursorPosition));const s=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement,!0);s!==void 0&&this._currentCursorPosition.copy(s),this.applyTransformMatrix(this.pan(this._startCursorPosition,this._currentCursorPosition,!0)),this.dispatchEvent(bt)}}),w(this,"onDoublePanEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),w(this,"onRotateStart",()=>{var s;this.enabled&&this.enableRotate&&(this.dispatchEvent(Ee),this.updateTbState(st.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))}),w(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 n;this._state!=st.ZROTATE&&(this.updateTbState(st.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),n=(s=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement))==null?void 0:s.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._v3_2)):n=new Q().setFromMatrixPosition(this._gizmoMatrixState);const r=ot.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);n!==void 0&&this.applyTransformMatrix(this.zRotate(n,r)),this.dispatchEvent(bt)}}),w(this,"onRotateEnd",()=>{this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(he)}),w(this,"onPinchStart",()=>{this.enabled&&this.enableZoom&&(this.dispatchEvent(Ee),this.updateTbState(st.SCALE,!0),this._startFingerDistance=this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),this._currentFingerDistance=this._startFingerDistance,this.activateGizmos(!1))}),w(this,"onPinchMove",()=>{var s,n;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 r=12;this._state!=st.SCALE&&(this._startFingerDistance=this._currentFingerDistance,this.updateTbState(st.SCALE,!0)),this._currentFingerDistance=Math.max(this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),r*this._devPxRatio);const o=this._currentFingerDistance/this._startFingerDistance;let l;this.enablePan?this.camera instanceof re?l=(s=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement))==null?void 0:s.applyQuaternion(this.camera.quaternion).multiplyScalar(1/this.camera.zoom).add(this._gizmos.position):this.camera instanceof Nt&&(l=(n=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement))==null?void 0:n.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)):l=this._gizmos.position,l!==void 0&&this.applyTransformMatrix(this.applyScale(o,l)),this.dispatchEvent(bt)}}),w(this,"onPinchEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),w(this,"onTriplePanStart",()=>{if(this.enabled&&this.enableZoom&&this.domElement){this.dispatchEvent(Ee),this.updateTbState(st.SCALE,!0);let s=0,n=0;const r=this._touchCurrent.length;for(let o=0;o<r;o++)s+=this._touchCurrent[o].clientX,n+=this._touchCurrent[o].clientY;this.setCenter(s/r,n/r),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition)}}),w(this,"onTriplePanMove",()=>{if(this.enabled&&this.enableZoom&&this.camera&&this.domElement){let s=0,n=0;const r=this._touchCurrent.length;for(let m=0;m<r;m++)s+=this._touchCurrent[m].clientX,n+=this._touchCurrent[m].clientY;this.setCenter(s/r,n/r);const o=8;this._currentCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5);const l=this._currentCursorPosition.y-this._startCursorPosition.y;let h=1;l<0?h=1/Math.pow(this.scaleFactor,-l*o):l>0&&(h=Math.pow(this.scaleFactor,l*o)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const u=this._v3_1.distanceTo(this._gizmos.position);let c=u/h;c=ot.clamp(c,this.minDistance,this.maxDistance);const d=u*Math.tan(ot.DEG2RAD*this._fovState*.5);let A=ot.RAD2DEG*(Math.atan(d/c)*2);A=ot.clamp(A,this.minFov,this.maxFov);const f=d/Math.tan(ot.DEG2RAD*(A/2));h=u/f,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(A),this.applyTransformMatrix(this.applyScale(h,this._v3_2,!1));const g=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(f/u);this._m4_1.makeTranslation(g.x,g.y,g.z),this.dispatchEvent(bt)}}),w(this,"onTriplePanEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),w(this,"setCenter",(s,n)=>{ut.x=s,ut.y=n}),w(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")}),w(this,"setMouseAction",(s,n,r=null)=>{const o=["PAN","ROTATE","ZOOM","FOV"],l=[0,1,2,"WHEEL"],h=["CTRL","SHIFT",null];let u;if(!o.includes(s)||!l.includes(n)||!h.includes(r)||n=="WHEEL"&&s!="ZOOM"&&s!="FOV")return!1;switch(s){case"PAN":u=st.PAN;break;case"ROTATE":u=st.ROTATE;break;case"ZOOM":u=st.SCALE;break;case"FOV":u=st.FOV;break}const c={operation:s,mouse:n,key:r,state:u};for(let d=0;d<this.mouseActions.length;d++)if(this.mouseActions[d].mouse==c.mouse&&this.mouseActions[d].key==c.key)return this.mouseActions.splice(d,1,c),!0;return this.mouseActions.push(c),!0}),w(this,"getOpFromAction",(s,n)=>{let r;for(let o=0;o<this.mouseActions.length;o++)if(r=this.mouseActions[o],r.mouse==s&&r.key==n)return r.operation;if(n){for(let o=0;o<this.mouseActions.length;o++)if(r=this.mouseActions[o],r.mouse==s&&r.key==null)return r.operation}return null}),w(this,"getOpStateFromAction",(s,n)=>{let r;for(let o=0;o<this.mouseActions.length;o++)if(r=this.mouseActions[o],r.mouse==s&&r.key==n)return r.state;if(n){for(let o=0;o<this.mouseActions.length;o++)if(r=this.mouseActions[o],r.mouse==s&&r.key==null)return r.state}return null}),w(this,"getAngle",(s,n)=>Math.atan2(n.clientY-s.clientY,n.clientX-s.clientX)*180/Math.PI),w(this,"updateTouchEvent",s=>{for(let n=0;n<this._touchCurrent.length;n++)if(this._touchCurrent[n].pointerId==s.pointerId){this._touchCurrent.splice(n,1,s);break}}),w(this,"calculateAngularSpeed",(s,n,r,o)=>{const l=n-s,h=(o-r)/1e3;return h==0?0:l/h}),w(this,"calculatePointersDistance",(s,n)=>Math.sqrt(Math.pow(n.clientX-s.clientX,2)+Math.pow(n.clientY-s.clientY,2))),w(this,"calculateRotationAxis",(s,n)=>(this._rotationMatrix.extractRotation(this._cameraMatrixState),this._quat.setFromRotationMatrix(this._rotationMatrix),this._rotationAxis.crossVectors(s,n).applyQuaternion(this._quat),this._rotationAxis.normalize().clone())),w(this,"calculateTbRadius",s=>{const r=s.position.distanceTo(this._gizmos.position);if(s instanceof Nt){const o=ot.DEG2RAD*s.fov*.5,l=Math.atan(s.aspect*Math.tan(o));return Math.tan(Math.min(o,l))*r*.67}else if(s instanceof re)return Math.min(s.top,s.right)*.67}),w(this,"focus",(s,n,r=1)=>{if(this.camera){const o=s.clone();o.sub(this._gizmos.position).multiplyScalar(r),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 h=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(n,this._gizmos.position)),this._gizmoMatrixState.copy(l),this._cameraMatrixState.copy(h)}}),w(this,"drawGrid",()=>{if(this.scene){let r,o,l,h;if(this.camera instanceof re){const u=this.camera.right-this.camera.left,c=this.camera.bottom-this.camera.top;l=Math.max(u,c),h=l/20,r=l/this.camera.zoom*3,o=r/h*this.camera.zoom}else if(this.camera instanceof Nt){const u=this.camera.position.distanceTo(this._gizmos.position),c=ot.DEG2RAD*this.camera.fov*.5,d=Math.atan(this.camera.aspect*Math.tan(c));l=Math.tan(Math.max(c,d))*u*2,h=l/20,r=l*3,o=r/h}this._grid==null&&this.camera&&(this._grid=new Nd(r,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))}}),w(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)}),w(this,"dispose",()=>{var s,n,r,o,l;this._animationId!=-1&&window.cancelAnimationFrame(this._animationId),(s=this.domElement)==null||s.removeEventListener("pointerdown",this.onPointerDown),(n=this.domElement)==null||n.removeEventListener("pointercancel",this.onPointerCancel),(r=this.domElement)==null||r.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()}),w(this,"disposeGrid",()=>{this._grid&&this.scene&&(this.scene.remove(this._grid),this._grid=null)}),w(this,"easeOutCubic",s=>1-Math.pow(1-s,3)),w(this,"activateGizmos",s=>{for(const n of this._gizmos.children)n.material.setValues({opacity:s?1:.6})}),w(this,"getCursorNDC",(s,n,r)=>{const o=r.getBoundingClientRect();return this._v2_1.setX((s-o.left)/o.width*2-1),this._v2_1.setY((o.bottom-n)/o.height*2-1),this._v2_1.clone()}),w(this,"getCursorPosition",(s,n,r)=>(this._v2_1.copy(this.getCursorNDC(s,n,r)),this.camera instanceof re&&(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())),w(this,"setCamera",s=>{if(s){s.lookAt(this.target),s.updateMatrix(),s instanceof Nt&&(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 n=this.calculateTbRadius(s);n!==void 0&&(this._tbRadius=n),this.makeGizmos(this.target,this._tbRadius)}}),w(this,"makeGizmos",(s,n)=>{const o=new qn(0,0,n,n).getPoints(this._curvePts),l=new ve().setFromPoints(o),h=new ps({color:16744576,fog:!1,transparent:!0,opacity:.6}),u=new ps({color:8454016,fog:!1,transparent:!0,opacity:.6}),c=new ps({color:8421631,fog:!1,transparent:!0,opacity:.6}),d=new pt(l,h),A=new pt(l,u),f=new pt(l,c),g=Math.PI*.5;if(d.rotation.x=g,A.rotation.y=g,this._gizmoMatrixState0.identity().setPosition(s),this._gizmoMatrixState.copy(this._gizmoMatrixState0),this.camera&&this.camera.zoom!=1){const m=1/this.camera.zoom;this._scaleMatrix.makeScale(m,m,m),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(d),this._gizmos.add(A),this._gizmos.add(f)}),w(this,"onFocusAnim",(s,n,r,o)=>{if(this._timeStart==-1&&(this._timeStart=s),this._state==st.ANIMATION_FOCUS){const h=(s-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(o),h>=1)this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(n,this.scaleFactor),this._timeStart=-1,this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(bt);else{const u=this.easeOutCubic(h),c=1-u+this.scaleFactor*u;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(n,c,u),this.dispatchEvent(bt);const d=this;this._animationId=window.requestAnimationFrame(function(A){d.onFocusAnim(A,n,r,o.clone())})}}else this._animationId=-1,this._timeStart=-1}),w(this,"onRotationAnim",(s,n,r)=>{if(this._timeStart==-1&&(this._anglePrev=0,this._angleCurrent=0,this._timeStart=s),this._state==st.ANIMATION_ROTATE){const o=(s-this._timeStart)/1e3;if(r+-this.dampingFactor*o>0){this._angleCurrent=.5*-this.dampingFactor*Math.pow(o,2)+r*o+0,this.applyTransformMatrix(this.rotate(n,this._angleCurrent)),this.dispatchEvent(bt);const h=this;this._animationId=window.requestAnimationFrame(function(u){h.onRotationAnim(u,n,r)})}else this._animationId=-1,this._timeStart=-1,this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(bt)}else this._animationId=-1,this._timeStart=-1,this._state!=st.ROTATE&&(this.activateGizmos(!1),this.dispatchEvent(bt))}),w(this,"pan",(s,n,r=!1)=>{if(this.camera){const o=s.clone().sub(n);if(this.camera instanceof re&&o.multiplyScalar(1/this.camera.zoom),this.camera instanceof Nt&&r){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 ne}),w(this,"reset",()=>{if(this.camera){this.camera.zoom=this._zoom0,this.camera instanceof Nt&&(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(st.IDLE,!1),this.dispatchEvent(bt)}}),w(this,"rotate",(s,n)=>{const r=this._gizmos.position;return this._translationMatrix.makeTranslation(-r.x,-r.y,-r.z),this._rotationMatrix.makeRotationAxis(s,-n),this._m4_1.makeTranslation(r.x,r.y,r.z),this._m4_1.multiply(this._rotationMatrix),this._m4_1.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1),ne}),w(this,"copyState",()=>{if(this.camera){const s=JSON.stringify(this.camera instanceof re?{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)}}),w(this,"pasteState",()=>{const s=this;navigator.clipboard.readText().then(function(r){s.setStateFromJSON(r)})}),w(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 Nt&&(this._fov0=this.camera.fov))}),w(this,"applyScale",(s,n,r=!0)=>{if(!this.camera)return;const o=n.clone();let l=1/s;if(this.camera instanceof re){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 h=o.clone().multiplyScalar(l);return o.sub(h),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),ne}if(this.camera instanceof Nt){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let h=this._v3_1.distanceTo(o),u=h-h*l;const c=h-u;c<this.minDistance?(l=this.minDistance/h,u=h-h*l):c>this.maxDistance&&(l=this.maxDistance/h,u=h-h*l);let d=o.clone().sub(this._v3_1).normalize().multiplyScalar(u);if(this._m4_1.makeTranslation(d.x,d.y,d.z),r){const A=this._v3_2;h=A.distanceTo(o),u=h-h*l,d=o.clone().sub(this._v3_2).normalize().multiplyScalar(u),this._translationMatrix.makeTranslation(A.x,A.y,A.z),this._scaleMatrix.makeScale(l,l,l),this._m4_2.makeTranslation(d.x,d.y,d.z).multiply(this._translationMatrix),this._m4_2.multiply(this._scaleMatrix),this._translationMatrix.makeTranslation(-A.x,-A.y,-A.z),this._m4_2.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1,this._m4_2)}else this.setTransformationMatrices(this._m4_1);return ne}}),w(this,"setFov",s=>{this.camera instanceof Nt&&(this.camera.fov=ot.clamp(s,this.minFov,this.maxFov),this.camera.updateProjectionMatrix())}),w(this,"setTarget",(s,n,r)=>{if(this.camera){this.target.set(s,n,r),this._gizmos.position.set(s,n,r);const o=this.calculateTbRadius(this.camera);o!==void 0&&(this._tbRadius=o),this.makeGizmos(this.target,this._tbRadius),this.camera.lookAt(this.target)}}),w(this,"zRotate",(s,n)=>(this._rotationMatrix.makeRotationAxis(this._rotationAxis,n),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,n),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),ne)),w(this,"unprojectOnObj",(s,n)=>{if(!this.scene)return null;const r=new Pn;r.near=n.near,r.far=n.far,r.setFromCamera(s,n);const o=r.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}),w(this,"unprojectOnTbSurface",(s,n,r,o,l)=>{if(s instanceof re){this._v2_1.copy(this.getCursorPosition(n,r,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0);const h=Math.pow(this._v2_1.x,2),u=Math.pow(this._v2_1.y,2),c=Math.pow(this._tbRadius,2);return h+u<=c*.5?this._v3_1.setZ(Math.sqrt(c-(h+u))):this._v3_1.setZ(c*.5/Math.sqrt(h+u)),this._v3_1}if(s instanceof Nt){this._v2_1.copy(this.getCursorNDC(n,r,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const h=this._v3_1.clone().normalize(),u=s.position.distanceTo(this._gizmos.position),c=Math.pow(l,2),d=this._v3_1.z,A=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));if(A==0)return h.set(this._v3_1.x,this._v3_1.y,l),h;const f=d/A,g=u;let m=Math.pow(f,2)+1,p=2*f*g,C=Math.pow(g,2)-c,E=Math.pow(p,2)-4*m*C;if(E>=0&&(this._v2_1.setX((-p-Math.sqrt(E))/(2*m)),this._v2_1.setY(f*this._v2_1.x+g),ot.RAD2DEG*this._v2_1.angle()>=45)){const T=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(u-this._v2_1.y,2));return h.multiplyScalar(T),h.z+=u,h}m=f,p=g,C=-c*.5,E=Math.pow(p,2)-4*m*C,this._v2_1.setX((-p-Math.sqrt(E))/(2*m)),this._v2_1.setY(f*this._v2_1.x+g);const y=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(u-this._v2_1.y,2));return h.multiplyScalar(y),h.z+=u,h}}),w(this,"unprojectOnTbPlane",(s,n,r,o,l=!1)=>{if(s instanceof re)return this._v2_1.copy(this.getCursorPosition(n,r,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0),this._v3_1.clone();if(s instanceof Nt){this._v2_1.copy(this.getCursorNDC(n,r,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,-1),this._v3_1.applyMatrix4(s.projectionMatrixInverse);const h=this._v3_1.clone().normalize(),u=this._v3_1.z,c=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let d;if(l?d=this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):d=s.position.distanceTo(this._gizmos.position),c==0)return h.set(0,0,0),h;const A=u/c,f=d,g=-f/A,m=Math.sqrt(Math.pow(f,2)+Math.pow(g,2));return h.multiplyScalar(m),h.z=0,h}}),w(this,"updateMatrixState",()=>{this.camera&&(this._cameraMatrixState.copy(this.camera.matrix),this._gizmoMatrixState.copy(this._gizmos.matrix),this.camera instanceof re&&(this._cameraProjectionState.copy(this.camera.projectionMatrix),this.camera.updateProjectionMatrix(),this._zoomState=this.camera.zoom),this.camera instanceof Nt&&(this._fovState=this.camera.fov))}),w(this,"updateTbState",(s,n)=>{this._state=s,n&&this.updateMatrixState()}),w(this,"update",()=>{if(!this.target.equals(this._currentTarget)&&this.camera){this._gizmos.position.set(this.target.x,this.target.y,this.target.z);const n=this.calculateTbRadius(this.camera);n!==void 0&&(this._tbRadius=n),this.makeGizmos(this.target,this._tbRadius),this._currentTarget.copy(this.target)}if(this.camera){if(this.camera instanceof re&&(this.camera.zoom>this.maxZoom||this.camera.zoom<this.minZoom)){const n=ot.clamp(this.camera.zoom,this.minZoom,this.maxZoom);this.applyTransformMatrix(this.applyScale(n/this.camera.zoom,this._gizmos.position,!0))}if(this.camera instanceof Nt){const n=this.camera.position.distanceTo(this._gizmos.position);if(n>this.maxDistance+1e-6||n<this.minDistance-1e-6){const l=ot.clamp(n,this.minDistance,this.maxDistance);this.applyTransformMatrix(this.applyScale(l/n,this._gizmos.position)),this.updateMatrixState()}(this.camera.fov<this.minFov||this.camera.fov>this.maxFov)&&(this.camera.fov=ot.clamp(this.camera.fov,this.minFov,this.maxFov),this.camera.updateProjectionMatrix());const r=this._tbRadius,o=this.calculateTbRadius(this.camera);if(o!==void 0&&(this._tbRadius=o),r<this._tbRadius-1e-6||r>this._tbRadius+1e-6){const l=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,h=this._tbRadius/l,c=new qn(0,0,h,h).getPoints(this._curvePts),d=new ve().setFromPoints(c);for(const A in this._gizmos.children){const f=this._gizmos.children[A];f.geometry=d}}}this.camera.lookAt(this._gizmos.position)}}),w(this,"setStateFromJSON",s=>{const n=JSON.parse(s);if(n.arcballState&&this.camera){this._cameraMatrixState.fromArray(n.arcballState.cameraMatrix.elements),this._cameraMatrixState.decompose(this.camera.position,this.camera.quaternion,this.camera.scale),this.camera.up.copy(n.arcballState.cameraUp),this.camera.near=n.arcballState.cameraNear,this.camera.far=n.arcballState.cameraFar,this.camera.zoom=n.arcballState.cameraZoom,this.camera instanceof Nt&&(this.camera.fov=n.arcballState.cameraFov),this._gizmoMatrixState.fromArray(n.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 r=this.calculateTbRadius(this.camera);r!==void 0&&(this._tbRadius=r);const o=new At().copy(this._gizmoMatrixState0);this.makeGizmos(this._gizmos.position,this._tbRadius),this._gizmoMatrixState0.copy(o),this.camera.lookAt(this._gizmos.position),this.updateTbState(st.IDLE,!1),this.dispatchEvent(bt)}}),this.camera=null,this.domElement=e,this.scene=i,this.mouseActions=[],this._mouseOp=null,this._v2_1=new Kt,this._v3_1=new Q,this._v3_2=new Q,this._m4_1=new At,this._m4_2=new At,this._quat=new It,this._translationMatrix=new At,this._rotationMatrix=new At,this._scaleMatrix=new At,this._rotationAxis=new Q,this._cameraMatrixState=new At,this._cameraProjectionState=new At,this._fovState=1,this._upState=new Q,this._zoomState=1,this._nearPos=0,this._farPos=0,this._gizmoMatrixState=new At,this._up0=new Q,this._zoom0=1,this._fov0=0,this._initialNear=0,this._nearPos0=0,this._initialFar=0,this._farPos0=0,this._cameraMatrixState0=new At,this._gizmoMatrixState0=new At,this._button=-1,this._touchStart=[],this._touchCurrent=[],this._input=Tt.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 Q,this._startCursorPosition=new Q,this._grid=null,this._gridPosition=new Q,this._gizmos=new Yr,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 Q,this._cursorPosCurr=new Q,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 Q(0,0,0),this._currentTarget=new Q(0,0,0),this._tbRadius=1,this._state=st.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==st.ROTATE||this._state==st.ZROTATE||this._state==st.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==st.SCALE||this._state==st.FOCUS||this._state==st.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 Yh;s.setFromObject(this._gizmos);const n=new Ba;s.getBoundingSphere(n);const r=Math.max(this._nearPos0,n.radius+n.center.length()),o=i-this._initialNear,l=Math.min(r,o);this.camera.near=i-l;const h=Math.min(this._farPos0,-n.radius+n.center.length()),u=i-this._initialFar,c=Math.min(h,u);this.camera.far=i-c,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(bt)}setTransformationMatrices(t=null,e=null){t?ne.camera?ne.camera.copy(t):ne.camera=t.clone():ne.camera=null,e?ne.gizmos?ne.gizmos.copy(e):ne.gizmos=e.clone():ne.gizmos=null}};var FE=Object.defineProperty,kE=(a,t,e)=>t in a?FE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Rt=(a,t,e)=>(kE(a,typeof t!="symbol"?t+"":t,e),e);function rl(a){a.preventDefault()}let OE=class extends Vi{constructor(t,e){super(),Rt(this,"object"),Rt(this,"domElement",null),Rt(this,"movementSpeed",1),Rt(this,"rollSpeed",.005),Rt(this,"dragToLook",!1),Rt(this,"autoForward",!1),Rt(this,"changeEvent",{type:"change"}),Rt(this,"EPS",1e-6),Rt(this,"tmpQuaternion",new It),Rt(this,"mouseStatus",0),Rt(this,"movementSpeedMultiplier",1),Rt(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}),Rt(this,"moveVector",new Q(0,0,0)),Rt(this,"rotationVector",new Q(0,0,0)),Rt(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()}}),Rt(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()}),Rt(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()}}),Rt(this,"pointermove",i=>{if(!this.dragToLook||this.mouseStatus>0){const s=this.getContainerDimensions(),n=s.size[0]/2,r=s.size[1]/2;this.moveState.yawLeft=-(i.pageX-s.offset[0]-n)/n,this.moveState.pitchDown=(i.pageY-s.offset[1]-r)/r,this.updateRotationVector()}}),Rt(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()}),Rt(this,"lastQuaternion",new It),Rt(this,"lastPosition",new Q),Rt(this,"update",i=>{const s=i*this.movementSpeed,n=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*n,this.rotationVector.y*n,this.rotationVector.z*n,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))}),Rt(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}),Rt(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}),Rt(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]}),Rt(this,"connect",i=>{this.domElement=i,i instanceof Document||i.setAttribute("tabindex",-1),this.domElement.addEventListener("contextmenu",rl),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)}),Rt(this,"dispose",()=>{this.domElement.removeEventListener("contextmenu",rl),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 mc(a,t,e){const i=e.length-a-1;if(t>=e[i])return i-1;if(t<=e[a])return a;let s=a,n=i,r=Math.floor((s+n)/2);for(;t<e[r]||t>=e[r+1];)t<e[r]?n=r:s=r,r=Math.floor((s+n)/2);return r}function QE(a,t,e,i){const s=[],n=[],r=[];s[0]=1;for(let o=1;o<=e;++o){n[o]=t-i[a+1-o],r[o]=i[a+o]-t;let l=0;for(let h=0;h<o;++h){const u=r[h+1],c=n[o-h],d=s[h]/(u+c);s[h]=l+u*d,l=c*d}s[o]=l}return s}function UE(a,t,e,i){const s=mc(a,i,t),n=QE(s,i,a,t),r=new ze(0,0,0,0);for(let o=0;o<=a;++o){const l=e[s-a+o],h=n[o],u=l.w*h;r.x+=l.x*u,r.y+=l.y*u,r.z+=l.z*u,r.w+=l.w*h}return r}function GE(a,t,e,i,s){const n=[];for(let c=0;c<=e;++c)n[c]=0;const r=[];for(let c=0;c<=i;++c)r[c]=n.slice(0);const o=[];for(let c=0;c<=e;++c)o[c]=n.slice(0);o[0][0]=1;const l=n.slice(0),h=n.slice(0);for(let c=1;c<=e;++c){l[c]=t-s[a+1-c],h[c]=s[a+c]-t;let d=0;for(let A=0;A<c;++A){const f=h[A+1],g=l[c-A];o[c][A]=f+g;const m=o[A][c-1]/o[c][A];o[A][c]=d+f*m,d=g*m}o[c][c]=d}for(let c=0;c<=e;++c)r[0][c]=o[c][e];for(let c=0;c<=e;++c){let d=0,A=1;const f=[];for(let g=0;g<=e;++g)f[g]=n.slice(0);f[0][0]=1;for(let g=1;g<=i;++g){let m=0;const p=c-g,C=e-g;c>=g&&(f[A][0]=f[d][0]/o[C+1][p],m=f[A][0]*o[p][C]);const E=p>=-1?1:-p,y=c-1<=C?g-1:e-c;for(let T=E;T<=y;++T)f[A][T]=(f[d][T]-f[d][T-1])/o[C+1][p+T],m+=f[A][T]*o[p+T][C];c<=C&&(f[A][g]=-f[d][g-1]/o[C+1][c],m+=f[A][g]*o[c][C]),r[g][c]=m;const v=d;d=A,A=v}}let u=e;for(let c=1;c<=i;++c){for(let d=0;d<=e;++d)r[c][d]*=u;u*=e-c}return r}function NE(a,t,e,i,s){const n=s<a?s:a,r=[],o=mc(a,i,t),l=GE(o,i,a,n,t),h=[];for(let u=0;u<e.length;++u){const c=e[u].clone(),d=c.w;c.x*=d,c.y*=d,c.z*=d,h[u]=c}for(let u=0;u<=n;++u){const c=h[o-a].clone().multiplyScalar(l[u][0]);for(let d=1;d<=a;++d)c.add(h[o-a+d].clone().multiplyScalar(l[u][d]));r[u]=c}for(let u=n+1;u<=s+1;++u)r[u]=new ze(0,0,0);return r}function HE(a,t){let e=1;for(let s=2;s<=a;++s)e*=s;let i=1;for(let s=2;s<=t;++s)i*=s;for(let s=2;s<=a-t;++s)i*=s;return e/i}function KE(a){const t=a.length,e=[],i=[];for(let n=0;n<t;++n){const r=a[n];e[n]=new Q(r.x,r.y,r.z),i[n]=r.w}const s=[];for(let n=0;n<t;++n){const r=e[n].clone();for(let o=1;o<=n;++o)r.sub(s[n-o].clone().multiplyScalar(HE(n,o)*i[o]));s[n]=r.divideScalar(i[0])}return s}function $E(a,t,e,i,s){const n=NE(a,t,e,i,s);return KE(n)}class al extends Hd{constructor(t,e,i,s,n){super(),this.degree=t,this.knots=e,this.controlPoints=[],this.startKnot=s||0,this.endKnot=n||this.knots.length-1;for(let r=0;r<i.length;++r){const o=i[r];this.controlPoints[r]=new ze(o.x,o.y,o.z,o.w)}}getPoint(t,e){const i=e||new Q,s=this.knots[this.startKnot]+t*(this.knots[this.endKnot]-this.knots[this.startKnot]),n=UE(this.degree,this.knots,this.controlPoints,s);return n.w!=1&&n.divideScalar(n.w),i.set(n.x,n.y,n.z)}getTangent(t,e){const i=e||new Q,s=this.knots[0]+t*(this.knots[this.knots.length-1]-this.knots[0]),n=$E(this.degree,this.knots,this.controlPoints,s,1);return i.copy(n[1]).normalize(),i}}let mt,kt,ie;class Ma extends Sa{constructor(t){super(t)}load(t,e,i,s){const n=this,r=n.path===""?Kd.extractUrlBase(t):n.path,o=new Oi(this.manager);o.setPath(n.path),o.setResponseType("arraybuffer"),o.setRequestHeader(n.requestHeader),o.setWithCredentials(n.withCredentials),o.load(t,function(l){try{e(n.parse(l,r))}catch(h){s?s(h):console.error(h),n.manager.itemError(t)}},i,s)}parse(t,e){if(XE(t))mt=new qE().parse(t);else{const s=Cc(t);if(!WE(s))throw new Error("THREE.FBXLoader: Unknown format.");if(ll(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+ll(s));mt=new zE().parse(s)}const i=new $d(this.manager).setPath(this.resourcePath||e).setCrossOrigin(this.crossOrigin);return new YE(i,this.manager).parse(mt)}}class YE{constructor(t,e){this.textureLoader=t,this.manager=e}parse(){kt=this.parseConnections();const t=this.parseImages(),e=this.parseTextures(t),i=this.parseMaterials(e),s=this.parseDeformers(),n=new VE().parse(s);return this.parseScene(s,n,i),ie}parseConnections(){const t=new Map;return"Connections"in mt&&mt.Connections.connections.forEach(function(i){const s=i[0],n=i[1],r=i[2];t.has(s)||t.set(s,{parents:[],children:[]});const o={ID:n,relationship:r};t.get(s).parents.push(o),t.has(n)||t.set(n,{parents:[],children:[]});const l={ID:s,relationship:r};t.get(n).children.push(l)}),t}parseImages(){const t={},e={};if("Video"in mt.Objects){const i=mt.Objects.Video;for(const s in i){const n=i[s],r=parseInt(s);if(t[r]=n.RelativeFilename||n.Filename,"Content"in n){const o=n.Content instanceof ArrayBuffer&&n.Content.byteLength>0,l=typeof n.Content=="string"&&n.Content!=="";if(o||l){const h=this.parseImage(i[s]);e[n.RelativeFilename||n.Filename]=h}}}}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 n;switch(s){case"bmp":n="image/bmp";break;case"jpg":case"jpeg":n="image/jpeg";break;case"png":n="image/png";break;case"tif":n="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),n="image/tga";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof e=="string")return"data:"+n+";base64,"+e;{const r=new Uint8Array(e);return window.URL.createObjectURL(new Blob([r],{type:n}))}}parseTextures(t){const e=new Map;if("Texture"in mt.Objects){const i=mt.Objects.Texture;for(const s in i){const n=this.parseTexture(i[s],t);e.set(parseInt(s),n)}}return e}parseTexture(t,e){const i=this.loadTexture(t,e);i.ID=t.id,i.name=t.attrName;const s=t.WrapModeU,n=t.WrapModeV,r=s!==void 0?s.value:0,o=n!==void 0?n.value:0;if(i.wrapS=r===0?Vr:pn,i.wrapT=o===0?Vr:pn,"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,n=kt.get(t.id).children;n!==void 0&&n.length>0&&e[n[0].ID]!==void 0&&(i=e[n[0].ID],(i.indexOf("blob:")===0||i.indexOf("data:")===0)&&this.textureLoader.setPath(void 0));let r;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),r=new En):(l.setPath(this.textureLoader.path),r=l.load(i))}else o==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",t.RelativeFilename),r=new En):r=this.textureLoader.load(i);return this.textureLoader.setPath(s),r}parseMaterials(t){const e=new Map;if("Material"in mt.Objects){const i=mt.Objects.Material;for(const s in i){const n=this.parseMaterial(i[s],t);n!==null&&e.set(parseInt(s),n)}}return e}parseMaterial(t,e){const i=t.id,s=t.attrName;let n=t.ShadingModel;if(typeof n=="object"&&(n=n.value),!kt.has(i))return null;const r=this.parseParameters(t,e,i);let o;switch(n.toLowerCase()){case"phong":o=new Xn;break;case"lambert":o=new Vd;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',n),o=new Xn;break}return o.setValues(r),o.name=s,o}parseParameters(t,e,i){const s={};t.BumpFactor&&(s.bumpScale=t.BumpFactor.value),t.Diffuse?s.color=new Ot().fromArray(t.Diffuse.value):t.DiffuseColor&&(t.DiffuseColor.type==="Color"||t.DiffuseColor.type==="ColorRGB")&&(s.color=new Ot().fromArray(t.DiffuseColor.value)),t.DisplacementFactor&&(s.displacementScale=t.DisplacementFactor.value),t.Emissive?s.emissive=new Ot().fromArray(t.Emissive.value):t.EmissiveColor&&(t.EmissiveColor.type==="Color"||t.EmissiveColor.type==="ColorRGB")&&(s.emissive=new Ot().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 Ot().fromArray(t.Specular.value):t.SpecularColor&&t.SpecularColor.type==="Color"&&(s.specular=new Ot().fromArray(t.SpecularColor.value));const n=this;return kt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=n.getTexture(e,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=n.getTexture(e,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=n.getTexture(e,r.ID),s.map!==void 0&&("colorSpace"in s.map?s.map.colorSpace="srgb":s.map.encoding=3001);break;case"DisplacementColor":s.displacementMap=n.getTexture(e,r.ID);break;case"EmissiveColor":s.emissiveMap=n.getTexture(e,r.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=n.getTexture(e,r.ID);break;case"ReflectionColor":s.envMap=n.getTexture(e,r.ID),s.envMap!==void 0&&(s.envMap.mapping=Jd,"colorSpace"in s.envMap?s.envMap.colorSpace="srgb":s.envMap.encoding=3001);break;case"SpecularColor":s.specularMap=n.getTexture(e,r.ID),s.specularMap!==void 0&&("colorSpace"in s.specularMap?s.specularMap.colorSpace="srgb":s.specularMap.encoding=3001);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=n.getTexture(e,r.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 mt.Objects&&e in mt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),e=kt.get(e).children[0].ID),t.get(e)}parseDeformers(){const t={},e={};if("Deformer"in mt.Objects){const i=mt.Objects.Deformer;for(const s in i){const n=i[s],r=kt.get(parseInt(s));if(n.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,t[s]=o}else if(n.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.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 n=e[s.ID];if(n.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new At().fromArray(n.TransformLink.a)};"Indexes"in n&&(r.indices=n.Indexes.a,r.weights=n.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(t,e){const i=[];for(let s=0;s<t.children.length;s++){const n=t.children[s],r=e[n.ID],o={name:r.attrName,initialWeight:r.DeformPercent,id:r.id,fullWeights:r.FullWeights.a};if(r.attrType!=="BlendShapeChannel")return;o.geoID=kt.get(parseInt(n.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,i.push(o)}return i}parseScene(t,e,i){ie=new Yr;const s=this.parseModels(t.skeletons,e,i),n=mt.Objects.Model,r=this;s.forEach(function(l){const h=n[l.ID];r.setLookAtProperties(l,h),kt.get(l.ID).parents.forEach(function(c){const d=s.get(c.ID);d!==void 0&&d.add(l)}),l.parent===null&&ie.add(l)}),this.bindSkeleton(t.skeletons,e,s),this.createAmbientLight(),ie.traverse(function(l){if(l.userData.transformData){l.parent&&(l.userData.transformData.parentMatrix=l.parent.matrix,l.userData.transformData.parentMatrixWorld=l.parent.matrixWorld);const h=Ec(l.userData.transformData);l.applyMatrix4(h),l.updateWorldMatrix()}});const o=new JE().parse();ie.children.length===1&&ie.children[0].isGroup&&(ie.children[0].animations=o,ie=ie.children[0]),ie.animations=o}parseModels(t,e,i){const s=new Map,n=mt.Objects.Model;for(const r in n){const o=parseInt(r),l=n[r],h=kt.get(o);let u=this.buildSkeleton(h,t,o,l.attrName);if(!u){switch(l.attrType){case"Camera":u=this.createCamera(h);break;case"Light":u=this.createLight(h);break;case"Mesh":u=this.createMesh(h,e,i);break;case"NurbsCurve":u=this.createCurve(h,e);break;case"LimbNode":case"Root":u=new Ao;break;case"Null":default:u=new Yr;break}u.name=l.attrName?In.sanitizeNodeName(l.attrName):"",u.ID=o}this.getTransformData(u,l),s.set(o,u)}return s}buildSkeleton(t,e,i,s){let n=null;return t.parents.forEach(function(r){for(const o in e){const l=e[o];l.rawBones.forEach(function(h,u){if(h.ID===r.ID){const c=n;n=new Ao,n.matrixWorld.copy(h.transformLink),n.name=s?In.sanitizeNodeName(s):"",n.ID=i,l.bones[u]=n,c!==null&&n.add(c)}})}}),n}createCamera(t){let e,i;if(t.children.forEach(function(s){const n=mt.Objects.NodeAttribute[s.ID];n!==void 0&&(i=n)}),i===void 0)e=new Zt;else{let s=0;i.CameraProjectionType!==void 0&&i.CameraProjectionType.value===1&&(s=1);let n=1;i.NearPlane!==void 0&&(n=i.NearPlane.value/1e3);let r=1e3;i.FarPlane!==void 0&&(r=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 h=o/l;let u=45;i.FieldOfView!==void 0&&(u=i.FieldOfView.value);const c=i.FocalLength?i.FocalLength.value:null;switch(s){case 0:e=new Nt(u,h,n,r),c!==null&&e.setFocalLength(c);break;case 1:e=new re(-o/2,o/2,l/2,-l/2,n,r);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+s+"."),e=new Zt;break}}return e}createLight(t){let e,i;if(t.children.forEach(function(s){const n=mt.Objects.NodeAttribute[s.ID];n!==void 0&&(i=n)}),i===void 0)e=new Zt;else{let s;i.LightType===void 0?s=0:s=i.LightType.value;let n=16777215;i.Color!==void 0&&(n=new Ot().fromArray(i.Color.value));let r=i.Intensity===void 0?1:i.Intensity.value/100;i.CastLightOnObject!==void 0&&i.CastLightOnObject.value===0&&(r=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 fo(n,r,o,l);break;case 1:e=new qd(n,r);break;case 2:let h=Math.PI/3;i.InnerAngle!==void 0&&(h=ot.degToRad(i.InnerAngle.value));let u=0;i.OuterAngle!==void 0&&(u=ot.degToRad(i.OuterAngle.value),u=Math.max(u,1)),e=new zd(n,r,o,h,u,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),e=new fo(n,r);break}i.CastShadows!==void 0&&i.CastShadows.value===1&&(e.castShadow=!0)}return e}createMesh(t,e,i){let s,n=null,r=null;const o=[];return t.children.forEach(function(l){e.has(l.ID)&&(n=e.get(l.ID)),i.has(l.ID)&&o.push(i.get(l.ID))}),o.length>1?r=o:o.length>0?r=o[0]:(r=new Xn({color:13421772}),o.push(r)),"color"in n.attributes&&o.forEach(function(l){l.vertexColors=!0}),n.FBX_Deformer?(s=new Xd(n,r),s.normalizeSkinWeights()):s=new rt(n,r),s}createCurve(t,e){const i=t.children.reduce(function(n,r){return e.has(r.ID)&&(n=e.get(r.ID)),n},null),s=new ps({color:3342591,linewidth:1});return new pt(i,s)}getTransformData(t,e){const i={};"InheritType"in e&&(i.inheritType=parseInt(e.InheritType.value)),"RotationOrder"in e?i.eulerOrder=Ic(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&&kt.get(t.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const n=mt.Objects.Model[s.ID];if("Lcl_Translation"in n){const r=n.Lcl_Translation.value;t.target!==void 0?(t.target.position.fromArray(r),ie.add(t.target)):t.lookAt(new Q().fromArray(r))}}})}bindSkeleton(t,e,i){const s=this.parsePoseNodes();for(const n in t){const r=t[n];kt.get(parseInt(r.ID)).parents.forEach(function(l){if(e.has(l.ID)){const h=l.ID;kt.get(h).parents.forEach(function(c){i.has(c.ID)&&i.get(c.ID).bind(new Wd(r.bones),s[c.ID])})}})}}parsePoseNodes(){const t={};if("Pose"in mt.Objects){const e=mt.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(n){t[n.Node]=new At().fromArray(n.Matrix.a)}):t[s.Node]=new At().fromArray(s.Matrix.a)}}return t}createAmbientLight(){if("GlobalSettings"in mt&&"AmbientColor"in mt.GlobalSettings){const t=mt.GlobalSettings.AmbientColor.value,e=t[0],i=t[1],s=t[2];if(e!==0||i!==0||s!==0){const n=new Ot(e,i,s);ie.add(new jd(n,1))}}}}class VE{parse(t){const e=new Map;if("Geometry"in mt.Objects){const i=mt.Objects.Geometry;for(const s in i){const n=kt.get(parseInt(s)),r=this.parseGeometry(n,i[s],t);e.set(parseInt(s),r)}}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,n=[],r=t.parents.map(function(c){return mt.Objects.Model[c.ID]});if(r.length===0)return;const o=t.children.reduce(function(c,d){return s[d.ID]!==void 0&&(c=s[d.ID]),c},null);t.children.forEach(function(c){i.morphTargets[c.ID]!==void 0&&n.push(i.morphTargets[c.ID])});const l=r[0],h={};"RotationOrder"in l&&(h.eulerOrder=Ic(l.RotationOrder.value)),"InheritType"in l&&(h.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(h.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(h.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(h.scale=l.GeometricScaling.value);const u=Ec(h);return this.genGeometry(e,o,n,u)}genGeometry(t,e,i,s){const n=new ve;t.attrName&&(n.name=t.attrName);const r=this.parseGeoNode(t,e),o=this.genBuffers(r),l=new He(o.vertex,3);if(l.applyMatrix4(s),n.setAttribute("position",l),o.colors.length>0&&n.setAttribute("color",new He(o.colors,3)),e&&(n.setAttribute("skinIndex",new Zd(o.weightsIndices,4)),n.setAttribute("skinWeight",new He(o.vertexWeights,4)),n.FBX_Deformer=e),o.normal.length>0){const h=new ms().getNormalMatrix(s),u=new He(o.normal,3);u.applyNormalMatrix(h),n.setAttribute("normal",u)}if(o.uvs.forEach(function(h,u){nA==="uv2"&&u++;const c=u===0?"uv":`uv${u}`;n.setAttribute(c,new He(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let h=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(c,d){c!==h&&(n.addGroup(u,d-u,h),h=c,u=d)}),n.groups.length>0){const c=n.groups[n.groups.length-1],d=c.start+c.count;d!==o.materialIndex.length&&n.addGroup(d,o.materialIndex.length-d,h)}n.groups.length===0&&n.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(n,t,i,s),n}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,n){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:n,weight:s.weights[o]})})})),i}genBuffers(t){const e={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,n=!1,r=[],o=[],l=[],h=[],u=[],c=[];const d=this;return t.vertexIndices.forEach(function(A,f){let g,m=!1;A<0&&(A=A^-1,m=!0);let p=[],C=[];if(r.push(A*3,A*3+1,A*3+2),t.color){const E=Qs(f,i,A,t.color);l.push(E[0],E[1],E[2])}if(t.skeleton){if(t.weightTable[A]!==void 0&&t.weightTable[A].forEach(function(E){C.push(E.weight),p.push(E.id)}),C.length>4){n||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),n=!0);const E=[0,0,0,0],y=[0,0,0,0];C.forEach(function(v,T){let B=v,_=p[T];y.forEach(function(D,x,M){if(B>D){M[x]=B,B=D;const k=E[x];E[x]=_,_=k}})}),p=E,C=y}for(;C.length<4;)C.push(0),p.push(0);for(let E=0;E<4;++E)u.push(C[E]),c.push(p[E])}if(t.normal){const E=Qs(f,i,A,t.normal);o.push(E[0],E[1],E[2])}t.material&&t.material.mappingType!=="AllSame"&&(g=Qs(f,i,A,t.material)[0]),t.uv&&t.uv.forEach(function(E,y){const v=Qs(f,i,A,E);h[y]===void 0&&(h[y]=[]),h[y].push(v[0]),h[y].push(v[1])}),s++,m&&(d.genFace(e,t,r,g,o,l,h,u,c,s),i++,s=0,r=[],o=[],l=[],h=[],u=[],c=[])}),e}genFace(t,e,i,s,n,r,o,l,h,u){for(let c=2;c<u;c++)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[(c-1)*3]]),t.vertex.push(e.vertexPositions[i[(c-1)*3+1]]),t.vertex.push(e.vertexPositions[i[(c-1)*3+2]]),t.vertex.push(e.vertexPositions[i[c*3]]),t.vertex.push(e.vertexPositions[i[c*3+1]]),t.vertex.push(e.vertexPositions[i[c*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[(c-1)*4]),t.vertexWeights.push(l[(c-1)*4+1]),t.vertexWeights.push(l[(c-1)*4+2]),t.vertexWeights.push(l[(c-1)*4+3]),t.vertexWeights.push(l[c*4]),t.vertexWeights.push(l[c*4+1]),t.vertexWeights.push(l[c*4+2]),t.vertexWeights.push(l[c*4+3]),t.weightsIndices.push(h[0]),t.weightsIndices.push(h[1]),t.weightsIndices.push(h[2]),t.weightsIndices.push(h[3]),t.weightsIndices.push(h[(c-1)*4]),t.weightsIndices.push(h[(c-1)*4+1]),t.weightsIndices.push(h[(c-1)*4+2]),t.weightsIndices.push(h[(c-1)*4+3]),t.weightsIndices.push(h[c*4]),t.weightsIndices.push(h[c*4+1]),t.weightsIndices.push(h[c*4+2]),t.weightsIndices.push(h[c*4+3])),e.color&&(t.colors.push(r[0]),t.colors.push(r[1]),t.colors.push(r[2]),t.colors.push(r[(c-1)*3]),t.colors.push(r[(c-1)*3+1]),t.colors.push(r[(c-1)*3+2]),t.colors.push(r[c*3]),t.colors.push(r[c*3+1]),t.colors.push(r[c*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(n[0]),t.normal.push(n[1]),t.normal.push(n[2]),t.normal.push(n[(c-1)*3]),t.normal.push(n[(c-1)*3+1]),t.normal.push(n[(c-1)*3+2]),t.normal.push(n[c*3]),t.normal.push(n[c*3+1]),t.normal.push(n[c*3+2])),e.uv&&e.uv.forEach(function(d,A){t.uvs[A]===void 0&&(t.uvs[A]=[]),t.uvs[A].push(o[A][0]),t.uvs[A].push(o[A][1]),t.uvs[A].push(o[A][(c-1)*2]),t.uvs[A].push(o[A][(c-1)*2+1]),t.uvs[A].push(o[A][c*2]),t.uvs[A].push(o[A][c*2+1])})}addMorphTargets(t,e,i,s){if(i.length===0)return;t.morphTargetsRelative=!0,t.morphAttributes.position=[];const n=this;i.forEach(function(r){r.rawTargets.forEach(function(o){const l=mt.Objects.Geometry[o.geoID];l!==void 0&&n.genMorphGeometry(t,e,l,s,o.name)})})}genMorphGeometry(t,e,i,s,n){const r=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],o=i.Vertices!==void 0?i.Vertices.a:[],l=i.Indexes!==void 0?i.Indexes.a:[],h=t.attributes.position.count*3,u=new Float32Array(h);for(let f=0;f<l.length;f++){const g=l[f]*3;u[g]=o[f*3],u[g+1]=o[f*3+1],u[g+2]=o[f*3+2]}const c={vertexIndices:r,vertexPositions:u},d=this.genBuffers(c),A=new He(d.vertex,3);A.name=n||i.attrName,A.applyMatrix4(s),t.morphAttributes.position.push(A)}parseNormals(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.Normals.a;let n=[];return i==="IndexToDirect"&&("NormalIndex"in t?n=t.NormalIndex.a:"NormalsIndex"in t&&(n=t.NormalsIndex.a)),{dataSize:3,buffer:s,indices:n,mappingType:e,referenceType:i}}parseUVs(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.UV.a;let n=[];return i==="IndexToDirect"&&(n=t.UVIndex.a),{dataSize:2,buffer:s,indices:n,mappingType:e,referenceType:i}}parseVertexColors(t){const e=t.MappingInformationType,i=t.ReferenceInformationType,s=t.Colors.a;let n=[];return i==="IndexToDirect"&&(n=t.ColorIndex.a),{dataSize:4,buffer:s,indices:n,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,n=[];for(let r=0;r<s.length;++r)n.push(r);return{dataSize:1,buffer:s,indices:n,mappingType:e,referenceType:i}}parseNurbsGeometry(t){if(al===void 0)return console.error("THREE.FBXLoader: The loader relies on NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry."),new ve;const e=parseInt(t.Order);if(isNaN(e))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",t.Order,t.id),new ve;const i=e-1,s=t.KnotVector.a,n=[],r=t.Points.a;for(let c=0,d=r.length;c<d;c+=4)n.push(new ze().fromArray(r,c));let o,l;if(t.Form==="Closed")n.push(n[0]);else if(t.Form==="Periodic"){o=i,l=s.length-1-o;for(let c=0;c<i;++c)n.push(n[c])}const u=new al(i,s,n,o,l).getPoints(n.length*12);return new ve().setFromPoints(u)}}class JE{parse(){const t=[],e=this.parseClips();if(e!==void 0)for(const i in e){const s=e[i],n=this.addClip(s);t.push(n)}return t}parseClips(){if(mt.Objects.AnimationCurve===void 0)return;const t=this.parseAnimationCurveNodes();this.parseAnimationCurves(t);const e=this.parseAnimationLayers(t);return this.parseAnimStacks(e)}parseAnimationCurveNodes(){const t=mt.Objects.AnimationCurveNode,e=new Map;for(const i in t){const s=t[i];if(s.attrName.match(/S|R|T|DeformPercent/)!==null){const n={id:s.id,attr:s.attrName,curves:{}};e.set(n.id,n)}}return e}parseAnimationCurves(t){const e=mt.Objects.AnimationCurve;for(const i in e){const s={id:e[i].id,times:e[i].KeyTime.a.map(jE),values:e[i].KeyValueFloat.a},n=kt.get(s.id);if(n!==void 0){const r=n.parents[0].ID,o=n.parents[0].relationship;o.match(/X/)?t.get(r).curves.x=s:o.match(/Y/)?t.get(r).curves.y=s:o.match(/Z/)?t.get(r).curves.z=s:o.match(/d|DeformPercent/)&&t.has(r)&&(t.get(r).curves.morph=s)}}}parseAnimationLayers(t){const e=mt.Objects.AnimationLayer,i=new Map;for(const s in e){const n=[],r=kt.get(parseInt(s));r!==void 0&&(r.children.forEach(function(l,h){if(t.has(l.ID)){const u=t.get(l.ID);if(u.curves.x!==void 0||u.curves.y!==void 0||u.curves.z!==void 0){if(n[h]===void 0){const c=kt.get(l.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(c!==void 0){const d=mt.Objects.Model[c.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const A={modelName:d.attrName?In.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ie.traverse(function(f){f.ID===d.id&&(A.transform=f.matrix,f.userData.transformData&&(A.eulerOrder=f.userData.transformData.eulerOrder))}),A.transform||(A.transform=new At),"PreRotation"in d&&(A.preRotation=d.PreRotation.value),"PostRotation"in d&&(A.postRotation=d.PostRotation.value),n[h]=A}}n[h]&&(n[h][u.attr]=u)}else if(u.curves.morph!==void 0){if(n[h]===void 0){const c=kt.get(l.ID).parents.filter(function(p){return p.relationship!==void 0})[0].ID,d=kt.get(c).parents[0].ID,A=kt.get(d).parents[0].ID,f=kt.get(A).parents[0].ID,g=mt.Objects.Model[f],m={modelName:g.attrName?In.sanitizeNodeName(g.attrName):"",morphName:mt.Objects.Deformer[c].attrName};n[h]=m}n[h][u.attr]=u}}}),i.set(parseInt(s),n))}return i}parseAnimStacks(t){const e=mt.Objects.AnimationStack,i={};for(const s in e){const n=kt.get(parseInt(s)).children;n.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=t.get(n[0].ID);i[s]={name:e[s].attrName,layer:r}}return i}addClip(t){let e=[];const i=this;return t.layer.forEach(function(s){e=e.concat(i.generateTracks(s))}),new tA(t.name,-1,e)}generateTracks(t){const e=[];let i=new Q,s=new It,n=new Q;if(t.transform&&t.transform.decompose(i,s,n),i=i.toArray(),s=new $e().setFromQuaternion(s,t.eulerOrder).toArray(),n=n.toArray(),t.T!==void 0&&Object.keys(t.T.curves).length>0){const r=this.generateVectorTrack(t.modelName,t.T.curves,i,"position");r!==void 0&&e.push(r)}if(t.R!==void 0&&Object.keys(t.R.curves).length>0){const r=this.generateRotationTrack(t.modelName,t.R.curves,s,t.preRotation,t.postRotation,t.eulerOrder);r!==void 0&&e.push(r)}if(t.S!==void 0&&Object.keys(t.S.curves).length>0){const r=this.generateVectorTrack(t.modelName,t.S.curves,n,"scale");r!==void 0&&e.push(r)}if(t.DeformPercent!==void 0){const r=this.generateMorphTrack(t);r!==void 0&&e.push(r)}return e}generateVectorTrack(t,e,i,s){const n=this.getTimesForAllAxes(e),r=this.getKeyframeTrackValues(n,e,i);return new eA(t+"."+s,n,r)}generateRotationTrack(t,e,i,s,n,r){e.x!==void 0&&(this.interpolateRotations(e.x),e.x.values=e.x.values.map(ot.degToRad)),e.y!==void 0&&(this.interpolateRotations(e.y),e.y.values=e.y.values.map(ot.degToRad)),e.z!==void 0&&(this.interpolateRotations(e.z),e.z.values=e.z.values.map(ot.degToRad));const o=this.getTimesForAllAxes(e),l=this.getKeyframeTrackValues(o,e,i);s!==void 0&&(s=s.map(ot.degToRad),s.push(r),s=new $e().fromArray(s),s=new It().setFromEuler(s)),n!==void 0&&(n=n.map(ot.degToRad),n.push(r),n=new $e().fromArray(n),n=new It().setFromEuler(n).invert());const h=new It,u=new $e,c=[];for(let d=0;d<l.length;d+=3)u.set(l[d],l[d+1],l[d+2],r),h.setFromEuler(u),s!==void 0&&h.premultiply(s),n!==void 0&&h.multiply(n),h.toArray(c,d/3*4);return new iA(t+".quaternion",o,c)}generateMorphTrack(t){const e=t.DeformPercent.curves.morph,i=e.values.map(function(n){return n/100}),s=ie.getObjectByName(t.modelName).morphTargetDictionary[t.morphName];return new sA(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 n=1;n<e.length;n++){const r=e[n];r!==s&&(e[i]=r,s=r,i++)}e=e.slice(0,i)}return e}getKeyframeTrackValues(t,e,i){const s=i,n=[];let r=-1,o=-1,l=-1;return t.forEach(function(h){if(e.x&&(r=e.x.times.indexOf(h)),e.y&&(o=e.y.times.indexOf(h)),e.z&&(l=e.z.times.indexOf(h)),r!==-1){const u=e.x.values[r];n.push(u),s[0]=u}else n.push(s[0]);if(o!==-1){const u=e.y.values[o];n.push(u),s[1]=u}else n.push(s[1]);if(l!==-1){const u=e.z.values[l];n.push(u),s[2]=u}else n.push(s[2])}),n}interpolateRotations(t){for(let e=1;e<t.values.length;e++){const i=t.values[e-1],s=t.values[e]-i,n=Math.abs(s);if(n>=180){const r=n/180,o=s/r;let l=i+o;const h=t.times[e-1],c=(t.times[e]-h)/r;let d=h+c;const A=[],f=[];for(;d<t.times[e];)A.push(d),d+=c,f.push(l),l+=o;t.times=hl(t.times,e,A),t.values=hl(t.values,e,f)}}}}class zE{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 pc,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const e=this,i=t.split(/[\r\n]+/);return i.forEach(function(s,n){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+e.currentIndent+"}(\\w+):(.*){",""),h=s.match("^\\t{"+e.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(e.currentIndent-1)+"}}");l?e.parseNodeBegin(s,l):h?e.parseNodeProperty(s,h,i[++n]):u?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(/"$/,"")}),n={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,n):i in o?(i==="PoseNode"?o.PoseNode.push(n):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=n)):typeof r.id=="number"?(o[i]={},o[i][r.id]=n):i!=="Properties70"&&(i==="PoseNode"?o[i]=[n]:o[i]=n),typeof r.id=="number"&&(n.id=r.id),r.name!==""&&(n.attrName=r.name),r.type!==""&&(n.attrType=r.type),this.pushStack(n)}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(),n=e[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&n===","&&(n=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(t,s,n);return}if(s==="C"){const l=n.split(",").slice(1),h=parseInt(l[0]),u=parseInt(l[1]);let c=n.split(",").slice(3);c=c.map(function(d){return d.trim().replace(/^"/,"")}),s="connections",n=[h,u],tI(n,c),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=n),s in r&&Array.isArray(r[s])?r[s].push(n):s!=="a"?r[s]=n:r.a=n,this.setCurrentProp(r,s),s==="a"&&n.slice(-1)!==","&&(r.a=tr(n))}parseNodePropertyContinued(t){const e=this.getCurrentNode();e.a+=t,t.slice(-1)!==","&&(e.a=tr(e.a))}parseNodeSpecialProperty(t,e,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),n=s[0],r=s[1],o=s[2],l=s[3];let h=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":h=parseFloat(h);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":h=tr(h);break}this.getPrevNode()[n]={type:r,type2:o,flag:l,value:h},this.setCurrentProp(this.getPrevNode(),n)}}class qE{parse(t){const e=new ol(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 pc;for(;!this.endOfContent(e);){const n=this.parseNode(e,i);n!==null&&s.add(n.name,n)}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(),n=e>=7500?t.getUint64():t.getUint32();e>=7500?t.getUint64():t.getUint32();const r=t.getUint8(),o=t.getString(r);if(s===0)return null;const l=[];for(let d=0;d<n;d++)l.push(this.parseProperty(t));const h=l.length>0?l[0]:"",u=l.length>1?l[1]:"",c=l.length>2?l[2]:"";for(i.singleProperty=n===1&&t.getOffset()===s;s>t.getOffset();){const d=this.parseNode(t,e);d!==null&&this.parseSubNode(o,i,d)}return i.propertyList=l,typeof h=="number"&&(i.id=h),u!==""&&(i.attrName=u),c!==""&&(i.attrType=c),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(n,r){r!==0&&s.push(n)}),e.connections===void 0&&(e.connections=[]),e.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(n){e[n]=i[n]});else if(t==="Properties70"&&i.name==="P"){let s=i.propertyList[0],n=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),n.indexOf("Lcl ")===0&&(n=n.replace("Lcl ","Lcl_")),n==="Color"||n==="ColorRGB"||n==="Vector"||n==="Vector3D"||n.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],e[s]={type:n,type2:r,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(),n=t.getUint32(),r=t.getUint32();if(n===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=Yd(new Uint8Array(t.getArrayBuffer(r))),l=new ol(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 ol{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)),Vh(new Uint8Array(e))}}class pc{add(t,e){this[t]=e}}function XE(a){const t="Kaydara FBX Binary \0";return a.byteLength>=t.length&&t===Cc(a,0,t.length)}function WE(a){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 n=a[s-1];return a=a.slice(e+s),e++,n}for(let s=0;s<t.length;++s)if(i(1)===t[s])return!1;return!0}function ll(a){const t=/FBXVersion: (\d+)/,e=a.match(t);if(e)return parseInt(e[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function jE(a){return a/46186158e3}const ZE=[];function Qs(a,t,e,i){let s;switch(i.mappingType){case"ByPolygonVertex":s=a;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 n=s*i.dataSize,r=n+i.dataSize;return eI(ZE,i.buffer,n,r)}const Zn=new $e,Si=new Q;function Ec(a){const t=new At,e=new At,i=new At,s=new At,n=new At,r=new At,o=new At,l=new At,h=new At,u=new At,c=new At,d=new At,A=a.inheritType?a.inheritType:0;if(a.translation&&t.setPosition(Si.fromArray(a.translation)),a.preRotation){const x=a.preRotation.map(ot.degToRad);x.push(a.eulerOrder),e.makeRotationFromEuler(Zn.fromArray(x))}if(a.rotation){const x=a.rotation.map(ot.degToRad);x.push(a.eulerOrder),i.makeRotationFromEuler(Zn.fromArray(x))}if(a.postRotation){const x=a.postRotation.map(ot.degToRad);x.push(a.eulerOrder),s.makeRotationFromEuler(Zn.fromArray(x)),s.invert()}a.scale&&n.scale(Si.fromArray(a.scale)),a.scalingOffset&&o.setPosition(Si.fromArray(a.scalingOffset)),a.scalingPivot&&r.setPosition(Si.fromArray(a.scalingPivot)),a.rotationOffset&&l.setPosition(Si.fromArray(a.rotationOffset)),a.rotationPivot&&h.setPosition(Si.fromArray(a.rotationPivot)),a.parentMatrixWorld&&(c.copy(a.parentMatrix),u.copy(a.parentMatrixWorld));const f=e.clone().multiply(i).multiply(s),g=new At;g.extractRotation(u);const m=new At;m.copyPosition(u);const p=m.clone().invert().multiply(u),C=g.clone().invert().multiply(p),E=n,y=new At;if(A===0)y.copy(g).multiply(f).multiply(C).multiply(E);else if(A===1)y.copy(g).multiply(C).multiply(f).multiply(E);else{const M=new At().scale(new Q().setFromMatrixScale(c)).clone().invert(),k=C.clone().multiply(M);y.copy(g).multiply(f).multiply(k).multiply(E)}const v=h.clone().invert(),T=r.clone().invert();let B=t.clone().multiply(l).multiply(h).multiply(e).multiply(i).multiply(s).multiply(v).multiply(o).multiply(r).multiply(n).multiply(T);const _=new At().copyPosition(B),D=u.clone().multiply(_);return d.copyPosition(D),B=d.clone().multiply(y),B.premultiply(u.invert()),B}function Ic(a){a=a||0;const t=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return a===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),t[0]):t[a]}function tr(a){return a.split(",").map(function(e){return parseFloat(e)})}function Cc(a,t,e){return t===void 0&&(t=0),e===void 0&&(e=a.byteLength),Vh(new Uint8Array(a,t,e))}function tI(a,t){for(let e=0,i=a.length,s=t.length;e<s;e++,i++)a[i]=t[e]}function eI(a,t,e,i){for(let s=e,n=0;s<i;s++,n++)a[n]=t[s];return a}function hl(a,t,e){return a.slice(0,t).concat(e).concat(a.slice(t))}class iI extends En{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=go,this.minFilter=go,this.wrapR=pn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class sI{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:n,transfer:r}=this.queue.shift();this.workersResolve[t]=s,this.workers[t].postMessage(n,r)}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 yc=0,cl=2,nI=0,rI=0,aI=2,oI=0,lI=0,hI=1,jr=2,cI=0,vc=1,uI=10,dI=64,Bc=0,Sc=9,Tc=15,_c=16,xc=22,Dc=37,Rc=43,Lc=76,bc=83,wc=97,Pc=100,Mc=103,Fc=109,kc=165,Oc=166;class AI{constructor(){this.vkFormat=Bc,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=yc,this.levels=[],this.dataFormatDescriptor=[{vendorId:rI,descriptorType:nI,descriptorBlockSize:0,versionNumber:aI,colorModel:oI,colorPrimaries:vc,transferFunction:jr,flags:lI,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class rs{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 Wt=[171,75,84,88,32,50,48,187,13,10,26,10];function ul(a){return typeof TextDecoder<"u"?new TextDecoder().decode(a):Buffer.from(a).toString("utf8")}function fI(a){const t=new Uint8Array(a.buffer,a.byteOffset,Wt.length);if(t[0]!==Wt[0]||t[1]!==Wt[1]||t[2]!==Wt[2]||t[3]!==Wt[3]||t[4]!==Wt[4]||t[5]!==Wt[5]||t[6]!==Wt[6]||t[7]!==Wt[7]||t[8]!==Wt[8]||t[9]!==Wt[9]||t[10]!==Wt[10]||t[11]!==Wt[11])throw new Error("Missing KTX 2.0 identifier.");const e=new AI,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new rs(a,Wt.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 n=s._nextUint32();e.supercompressionScheme=s._nextUint32();const r=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),h=s._nextUint32(),u=s._nextUint64(),c=s._nextUint64(),d=n*3*8,A=new rs(a,Wt.length+i,d,!0);for(let F=0;F<n;F++)e.levels.push({levelData:new Uint8Array(a.buffer,a.byteOffset+A._nextUint64(),A._nextUint64()),uncompressedByteLength:A._nextUint64()});const f=new rs(a,r,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 F=0;F<C;F++){const N={bitOffset:f._nextUint16(),bitLength:f._nextUint8(),channelType:f._nextUint8(),samplePosition:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};N.channelType&dI?(N.sampleLower=f._nextInt32(),N.sampleUpper=f._nextInt32()):(N.sampleLower=f._nextUint32(),N.sampleUpper=f._nextUint32()),g.samples[F]=N}e.dataFormatDescriptor.length=0,e.dataFormatDescriptor.push(g);const E=new rs(a,l,h,!0);for(;E._offset<h;){const F=E._nextUint32(),N=E._scan(F),K=ul(N);if(e.keyValue[K]=E._nextUint8Array(F-N.byteLength-1),K.match(/^ktx/i)){const R=ul(e.keyValue[K]);e.keyValue[K]=R.substring(0,R.lastIndexOf("\0"))}const $=F%4?4-F%4:0;E._skip($)}if(c<=0)return e;const y=new rs(a,u,c,!0),v=y._nextUint16(),T=y._nextUint16(),B=y._nextUint32(),_=y._nextUint32(),D=y._nextUint32(),x=y._nextUint32(),M=[];for(let F=0;F<n;F++)M.push({imageFlags:y._nextUint32(),rgbSliceByteOffset:y._nextUint32(),rgbSliceByteLength:y._nextUint32(),alphaSliceByteOffset:y._nextUint32(),alphaSliceByteLength:y._nextUint32()});const k=u+y._offset,X=k+B,W=X+_,H=W+D,Y=new Uint8Array(a.buffer,a.byteOffset+k,B),z=new Uint8Array(a.buffer,a.byteOffset+X,_),J=new Uint8Array(a.buffer,a.byteOffset+W,D),U=new Uint8Array(a.buffer,a.byteOffset+H,x);return e.globalData={endpointCount:v,selectorCount:T,imageDescs:M,endpointsData:Y,selectorsData:z,tablesData:J,extendedData:U},e}let as,Ue,Zr;const er={env:{emscripten_notify_memory_growth:function(a){Zr=new Uint8Array(Ue.exports.memory.buffer)}}};class gI{init(){return as||(typeof fetch<"u"?as=fetch("data:application/wasm;base64,"+dl).then(t=>t.arrayBuffer()).then(t=>WebAssembly.instantiate(t,er)).then(this._init):as=WebAssembly.instantiate(Buffer.from(dl,"base64"),er).then(this._init),as)}_init(t){Ue=t.instance,er.env.emscripten_notify_memory_growth(0)}decode(t,e=0){if(!Ue)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=t.byteLength,s=Ue.exports.malloc(i);Zr.set(t,s),e=e||Number(Ue.exports.ZSTD_findDecompressedSize(s,i));const n=Ue.exports.malloc(e),r=Ue.exports.ZSTD_decompress(n,e,s,i),o=Zr.slice(n,n+r);return Ue.exports.free(s),Ue.exports.free(n),o}}const dl="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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQh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ASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigC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C0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/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 mI extends Mn{constructor(t,e,i){super(void 0,t[0].width,t[0].height,e,i,rA),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class pI extends Mn{constructor(t,e,i,s,n,r){super(t,e,i,n,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=pn}}var EI=Object.defineProperty,II=(a,t,e)=>t in a?EI(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Us=(a,t,e)=>(II(a,typeof t!="symbol"?t+"":t,e),e);const Qc=3e3,Uc=3001,Al="",CI="display-p3",yI="display-p3-linear",vI="srgb-linear",Fa="srgb",ir=new WeakMap;let sr=0,nr;const ka=(()=>{const a=class extends Sa{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new sI,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 Oi(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const i=e.loadAsync("basis_transcoder.js"),s=new Oi(this.manager);s.setPath(this.transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([i,n]).then(([r,o])=>{const l=a.BasisWorker.toString(),h=["/* constants */","let _EngineFormat = "+JSON.stringify(a.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(a.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(a.BasisFormat),"/* basis_transcoder.js */",r,"/* worker */",l.substring(l.indexOf("{")+1,l.lastIndexOf("}"))].join(`
|
|
4
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([h])),this.transcoderBinary=o,this.workerPool.setWorkerCreator(()=>{const u=new Worker(this.workerSourceURL),c=this.transcoderBinary.slice(0);return u.postMessage({type:"init",config:this.workerConfig,transcoderBinary:c},[c]),u})}),sr>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),sr++}return this.transcoderPending}load(e,i,s,n){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new Oi(this.manager);r.setResponseType("arraybuffer"),r.setWithCredentials(this.withCredentials),r.load(e,o=>{if(ir.has(o))return ir.get(o).promise.then(i).catch(n);this._createTexture(o).then(l=>i?i(l):null).catch(n)},s,n)}_createTextureFrom(e,i){const{faces:s,width:n,height:r,format:o,type:l,error:h,dfdFlags:u}=e;if(l==="error")return Promise.reject(h);let c;if(i.faceCount===6)c=new mI(s,o,ye);else{const A=s[0].mipmaps;c=i.layerCount>1?new pI(A,n,r,i.layerCount,o,ye):new Mn(A,n,r,o,ye)}c.minFilter=s[0].mipmaps.length===1?mo:aA,c.magFilter=mo,c.generateMipmaps=!1,c.needsUpdate=!0;const d=Gc(i);return"colorSpace"in c?c.colorSpace=d:c.encoding=d===Fa?Uc:Qc,c.premultiplyAlpha=!!(u&hI),c}async _createTexture(e,i={}){const s=fI(new Uint8Array(e));if(s.vkFormat!==Bc)return SI(s);const n=i,r=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e])).then(o=>this._createTextureFrom(o.data,s));return ir.set(e,{promise:r}),r}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),sr--,this}};let t=a;return Us(t,"BasisFormat",{ETC1S:0,UASTC_4x4:1}),Us(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}),Us(t,"EngineFormat",{RGBAFormat:Fi,RGBA_ASTC_4x4_Format:mA,RGBA_BPTC_Format:gA,RGBA_ETC2_EAC_Format:fA,RGBA_PVRTC_4BPPV1_Format:AA,RGBA_S3TC_DXT5_Format:dA,RGB_ETC1_Format:uA,RGB_ETC2_Format:cA,RGB_PVRTC_4BPPV1_Format:hA,RGB_S3TC_DXT1_Format:lA}),Us(t,"BasisWorker",function(){let e,i,s;const n=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",function(m){const p=m.data;switch(p.type){case"init":e=p.config,l(p.transcoderBinary);break;case"transcode":i.then(()=>{try{const{faces:C,buffers:E,width:y,height:v,hasAlpha:T,format:B,dfdFlags:_}=h(p.buffer);self.postMessage({type:"transcode",id:p.id,faces:C,width:y,height:v,hasAlpha:T,format:B,dfdFlags:_},E)}catch(C){console.error(C),self.postMessage({type:"error",id:p.id,error:C.message})}});break}});function l(m){i=new Promise(p=>{s={wasmBinary:m,onRuntimeInitialized:p},BASIS(s)}).then(()=>{s.initializeBasis(),s.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function h(m){const p=new s.KTX2File(new Uint8Array(m));function C(){p.close(),p.delete()}if(!p.isValid())throw C(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");const E=p.isUASTC()?o.UASTC_4x4:o.ETC1S,y=p.getWidth(),v=p.getHeight(),T=p.getLayers()||1,B=p.getLevels(),_=p.getFaces(),D=p.getHasAlpha(),x=p.getDFDFlags(),{transcoderFormat:M,engineFormat:k}=A(E,y,v,D);if(!y||!v||!B)throw C(),new Error("THREE.KTX2Loader: Invalid texture");if(!p.startTranscoding())throw C(),new Error("THREE.KTX2Loader: .startTranscoding failed");const X=[],W=[];for(let H=0;H<_;H++){const Y=[];for(let z=0;z<B;z++){const J=[];let U,F;for(let K=0;K<T;K++){const $=p.getImageLevelInfo(z,K,H);H===0&&z===0&&K===0&&($.origWidth%4!==0||$.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),B>1?(U=$.origWidth,F=$.origHeight):(U=$.width,F=$.height);const R=new Uint8Array(p.getImageTranscodedSizeInBytes(z,K,0,M));if(!p.transcodeImage(R,z,K,H,M,0,-1,-1))throw C(),new Error("THREE.KTX2Loader: .transcodeImage failed.");J.push(R)}const N=g(J);Y.push({data:N,width:U,height:F}),W.push(N.buffer)}X.push({mipmaps:Y,width:y,height:v,format:k})}return C(),{faces:X,buffers:W,width:y,height:v,hasAlpha:D,format:k,dfdFlags:x}}const u=[{if:"astcSupported",basisFormat:[o.UASTC_4x4],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC1,r.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],c=u.sort(function(m,p){return m.priorityETC1S-p.priorityETC1S}),d=u.sort(function(m,p){return m.priorityUASTC-p.priorityUASTC});function A(m,p,C,E){let y,v;const T=m===o.ETC1S?c:d;for(let B=0;B<T.length;B++){const _=T[B];if(e[_.if]&&_.basisFormat.includes(m)&&!(E&&_.transcoderFormat.length<2)&&!(_.needsPowerOfTwo&&!(f(p)&&f(C))))return y=_.transcoderFormat[E?1:0],v=_.engineFormat[E?1:0],{transcoderFormat:y,engineFormat:v}}return console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."),y=r.RGBA32,v=n.RGBAFormat,{transcoderFormat:y,engineFormat:v}}function f(m){return m<=2?!0:(m&m-1)===0&&m!==0}function g(m){if(m.length===1)return m[0];let p=0;for(let y=0;y<m.length;y++){const v=m[y];p+=v.byteLength}const C=new Uint8Array(p);let E=0;for(let y=0;y<m.length;y++){const v=m[y];C.set(v,E),E+=v.byteLength}return C}}),t})(),BI=new Set([Fi,fs,As]),rr={[Fc]:Fi,[wc]:Fi,[Dc]:Fi,[Rc]:Fi,[Mc]:fs,[bc]:fs,[_c]:fs,[xc]:fs,[Pc]:As,[Lc]:As,[Tc]:As,[Sc]:As,[Oc]:po,[kc]:po},ar={[Fc]:ln,[wc]:on,[Dc]:ye,[Rc]:ye,[Mc]:ln,[bc]:on,[_c]:ye,[xc]:ye,[Pc]:ln,[Lc]:on,[Tc]:ye,[Sc]:ye,[Oc]:ye,[kc]:ye};async function SI(a){const{vkFormat:t}=a;if(rr[t]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let e;a.supercompressionScheme===cl&&(nr||(nr=new Promise(async r=>{const o=new gI;await o.init(),r(o)})),e=await nr);const i=[];for(let r=0;r<a.levels.length;r++){const o=Math.max(1,a.pixelWidth>>r),l=Math.max(1,a.pixelHeight>>r),h=a.pixelDepth?Math.max(1,a.pixelDepth>>r):0,u=a.levels[r];let c;if(a.supercompressionScheme===yc)c=u.levelData;else if(a.supercompressionScheme===cl)c=e.decode(u.levelData,u.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let d;ar[t]===ln?d=new Float32Array(c.buffer,c.byteOffset,c.byteLength/Float32Array.BYTES_PER_ELEMENT):ar[t]===on?d=new Uint16Array(c.buffer,c.byteOffset,c.byteLength/Uint16Array.BYTES_PER_ELEMENT):d=c,i.push({data:d,width:o,height:l,depth:h})}let s;if(BI.has(rr[t]))s=a.pixelDepth===0?new oA(i[0].data,a.pixelWidth,a.pixelHeight):new iI(i[0].data,a.pixelWidth,a.pixelHeight,a.pixelDepth);else{if(a.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");s=new Mn(i,a.pixelWidth,a.pixelHeight)}s.mipmaps=i,s.type=ar[t],s.format=rr[t],s.needsUpdate=!0;const n=Gc(a);return"colorSpace"in s?s.colorSpace=n:s.encoding=n===Fa?Uc:Qc,Promise.resolve(s)}function Gc(a){const t=a.dataFormatDescriptor[0];return t.colorPrimaries===vc?t.transferFunction===jr?Fa:vI:t.colorPrimaries===uI?t.transferFunction===jr?CI:yI:(t.colorPrimaries===cI||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),Al)}const or=new WeakMap;class TI extends Sa{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 n=new Oi(this.manager);n.setPath(this.path),n.setResponseType("arraybuffer"),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,r=>{const o={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(r,o).then(e).catch(s)},i,s)}decodeDracoFile(t,e,i,s){const n={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i};this.decodeGeometry(t,n).then(e)}decodeGeometry(t,e){for(const l in e.attributeTypes){const h=e.attributeTypes[l];h.BYTES_PER_ELEMENT!==void 0&&(e.attributeTypes[l]=h.name)}const i=JSON.stringify(e);if(or.has(t)){const l=or.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 n=this.workerNextTaskID++,r=t.byteLength,o=this._getWorker(n,r).then(l=>(s=l,new Promise((h,u)=>{s._callbacks[n]={resolve:h,reject:u},s.postMessage({type:"decode",id:n,taskConfig:e,buffer:t},[t])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&n&&this._releaseTask(s,n)}),or.set(t,{key:i,promise:o}),o}_createGeometry(t){const e=new ve;t.index&&e.setIndex(new Jr(t.index.array,1));for(let i=0;i<t.attributes.length;i++){const s=t.attributes[i],n=s.name,r=s.array,o=s.itemSize;e.setAttribute(n,new Jr(r,o))}return e}_loadLibrary(t,e){const i=new Oi(this.manager);return i.setPath(this.decoderPath),i.setResponseType(e),i.setWithCredentials(this.withCredentials),new Promise((s,n)=>{i.load(t,s,void 0,n)})}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 n=_I.toString(),r=["/* draco decoder */",s,"","/* worker */",n.substring(n.indexOf("{")+1,n.lastIndexOf("}"))].join(`
|
|
5
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),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(n){const r=n.data;switch(r.type){case"decode":s._callbacks[r.id].resolve(r);break;case"error":s._callbacks[r.id].reject(r);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,n){return s._taskLoad>n._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 _I(){let a,t;onmessage=function(r){const o=r.data;switch(o.type){case"init":a=o.decoderConfig,t=new Promise(function(u){a.onModuleLoaded=function(c){u({draco:c})},DracoDecoderModule(a)});break;case"decode":const l=o.buffer,h=o.taskConfig;t.then(u=>{const c=u.draco,d=new c.Decoder,A=new c.DecoderBuffer;A.Init(new Int8Array(l),l.byteLength);try{const f=e(c,d,A,h),g=f.attributes.map(m=>m.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{c.destroy(A),c.destroy(d)}});break}};function e(r,o,l,h){const u=h.attributeIDs,c=h.attributeTypes;let d,A;const f=o.GetEncodedGeometryType(l);if(f===r.TRIANGULAR_MESH)d=new r.Mesh,A=o.DecodeBufferToMesh(l,d);else if(f===r.POINT_CLOUD)d=new r.PointCloud,A=o.DecodeBufferToPointCloud(l,d);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!A.ok()||d.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+A.error_msg());const g={index:null,attributes:[]};for(const m in u){const p=self[c[m]];let C,E;if(h.useUniqueIDs)E=u[m],C=o.GetAttributeByUniqueId(d,E);else{if(E=o.GetAttributeId(d,r[u[m]]),E===-1)continue;C=o.GetAttribute(d,E)}g.attributes.push(s(r,o,d,m,p,C))}return f===r.TRIANGULAR_MESH&&(g.index=i(r,o,d)),r.destroy(d),g}function i(r,o,l){const u=l.num_faces()*3,c=u*4,d=r._malloc(c);o.GetTrianglesUInt32Array(l,c,d);const A=new Uint32Array(r.HEAPF32.buffer,d,u).slice();return r._free(d),{array:A,itemSize:1}}function s(r,o,l,h,u,c){const d=c.num_components(),f=l.num_points()*d,g=f*u.BYTES_PER_ELEMENT,m=n(r,u),p=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,c,m,g,p);const C=new u(r.HEAPF32.buffer,p,f).slice();return r._free(p),{name:h,array:C,itemSize:d}}function n(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}let Gs;const lr=()=>{if(Gs)return Gs;const a="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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=a;WebAssembly.validate(e)&&(s=t);let n;const r=WebAssembly.instantiate(o(s),{}).then(c=>{n=c.instance,n.exports.__wasm_call_ctors()});function o(c){const d=new Uint8Array(c.length);for(let f=0;f<c.length;++f){const g=c.charCodeAt(f);d[f]=g>96?g-71:g>64?g-65:g>47?g+4:g>46?63:62}let A=0;for(let f=0;f<c.length;++f)d[A++]=d[f]<60?i[d[f]]:(d[f]-60)*64+d[++f];return d.buffer.slice(0,A)}function l(c,d,A,f,g,m){const p=n.exports.sbrk,C=A+3&-4,E=p(C*f),y=p(g.length),v=new Uint8Array(n.exports.memory.buffer);v.set(g,y);const T=c(E,A,f,y,g.length);if(T===0&&m&&m(E,C,f),d.set(v.subarray(E,E+A*f)),p(E-p(0)),T!==0)throw new Error(`Malformed buffer data: ${T}`)}const h={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},u={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return Gs={ready:r,supported:!0,decodeVertexBuffer(c,d,A,f,g){l(n.exports.meshopt_decodeVertexBuffer,c,d,A,f,n.exports[h[g]])},decodeIndexBuffer(c,d,A,f){l(n.exports.meshopt_decodeIndexBuffer,c,d,A,f)},decodeIndexSequence(c,d,A,f){l(n.exports.meshopt_decodeIndexSequence,c,d,A,f)},decodeGltfBuffer(c,d,A,f,g,m){l(n.exports[u[g]],c,d,A,f,n.exports[h[m]])}},Gs},xI=new Q,DI=S.forwardRef(({scale:a=1,...t},e)=>{const i=S.useRef(null);return S.useImperativeHandle(e,()=>i.current,[]),Qt(s=>{const n=i.current;if(!n)return;const r=Jh(n.getWorldPosition(xI),a,s.camera,s.size);n.scale.setScalar(r*a)}),S.createElement("object3D",wt({ref:i},t))});let Ns=null,Nc="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function Hc(a=!0,t=!0,e){return i=>{e&&e(i),a&&(Ns||(Ns=new TI),Ns.setDecoderPath(typeof a=="string"?a:Nc),i.setDRACOLoader(Ns)),t&&i.setMeshoptDecoder(typeof lr=="function"?lr():lr)}}const Ls=(a,t,e,i)=>Se(_a,a,Hc(t,e,i));Ls.preload=(a,t,e,i)=>Se.preload(_a,a,Hc(t,e,i));Ls.clear=a=>Se.clear(_a,a);Ls.setDecoderPath=a=>{Nc=a};const RI=S.forwardRef(({src:a,useDraco:t,useMeshOpt:e,extendLoader:i,...s},n)=>{const{scene:r}=Ls(a,t,e,i);return S.createElement(Ta,wt({ref:n},s,{object:r}))}),LI=S.forwardRef((a,t)=>{const{camera:e,onChange:i,makeDefault:s,...n}=a,r=q(d=>d.camera),o=q(d=>d.invalidate),l=q(d=>d.get),h=q(d=>d.set),u=e||r,c=S.useMemo(()=>new DE(u),[u]);return S.useEffect(()=>{const d=A=>{o(),i&&i(A)};return c==null||c.addEventListener==null||c.addEventListener("change",d),()=>c==null||c.removeEventListener==null?void 0:c.removeEventListener("change",d)},[i,c,o]),Qt(()=>c==null?void 0:c.update(),-1),S.useEffect(()=>{const d=c;return d==null||d.connect(),()=>d==null?void 0:d.dispose()},[c]),S.useEffect(()=>{if(s){const d=l().controls;return h({controls:c}),()=>h({controls:d})}},[s,c]),c?S.createElement("primitive",wt({ref:t,object:c},n)):null}),bI=S.forwardRef(({domElement:a,...t},e)=>{const{onChange:i,makeDefault:s,...n}=t,r=q(f=>f.invalidate),o=q(f=>f.camera),l=q(f=>f.gl),h=q(f=>f.events),u=q(f=>f.get),c=q(f=>f.set),d=a||h.connected||l.domElement,A=S.useMemo(()=>new OE(o),[o]);return S.useEffect(()=>(A.connect(d),()=>void A.dispose()),[d,A,r]),S.useEffect(()=>{const f=g=>{r(),i&&i(g)};return A.addEventListener==null||A.addEventListener("change",f),()=>A.removeEventListener==null?void 0:A.removeEventListener("change",f)},[i,r]),S.useEffect(()=>{if(s){const f=u().controls;return c({controls:A}),()=>c({controls:f})}},[s,A]),Qt((f,g)=>A.update(g)),S.createElement("primitive",wt({ref:e,object:A,args:[o,d]},n))}),wI=S.forwardRef((a={enableDamping:!0},t)=>{const{domElement:e,camera:i,makeDefault:s,onChange:n,onStart:r,onEnd:o,...l}=a,h=q(C=>C.invalidate),u=q(C=>C.camera),c=q(C=>C.gl),d=q(C=>C.events),A=q(C=>C.set),f=q(C=>C.get),g=e||d.connected||c.domElement,m=i||u,p=S.useMemo(()=>new pA(m),[m]);return S.useEffect(()=>{p.connect(g);const C=E=>{h(),n&&n(E)};return p.addEventListener("change",C),r&&p.addEventListener("start",r),o&&p.addEventListener("end",o),()=>{p.dispose(),p.removeEventListener("change",C),r&&p.removeEventListener("start",r),o&&p.removeEventListener("end",o)}},[n,r,o,p,h,g]),S.useEffect(()=>{if(s){const C=f().controls;return A({controls:p}),()=>A({controls:C})}},[s,p]),Qt(()=>p.update(),-1),S.createElement("primitive",wt({ref:t,object:p,enableDamping:!0},l))}),PI=S.forwardRef(({makeDefault:a,camera:t,domElement:e,regress:i,onChange:s,onStart:n,onEnd:r,...o},l)=>{const{invalidate:h,camera:u,gl:c,events:d,set:A,get:f,performance:g,viewport:m}=q(),p=t||u,C=e||d.connected||c.domElement,E=S.useMemo(()=>new bE(p),[p]);return Qt(()=>{E.enabled&&E.update()},-1),S.useEffect(()=>(E.connect(C),()=>void E.dispose()),[C,i,E,h]),S.useEffect(()=>{const y=v=>{h(),i&&g.regress(),s&&s(v)};return E.addEventListener("change",y),n&&E.addEventListener("start",n),r&&E.addEventListener("end",r),()=>{n&&E.removeEventListener("start",n),r&&E.removeEventListener("end",r),E.removeEventListener("change",y)}},[s,n,r,E,h]),S.useEffect(()=>{E.handleResize()},[m]),S.useEffect(()=>{if(a){const y=f().controls;return A({controls:E}),()=>A({controls:y})}},[a,E]),S.createElement("primitive",wt({ref:l,object:E},o))}),MI=S.forwardRef(({camera:a,makeDefault:t,regress:e,domElement:i,onChange:s,onStart:n,onEnd:r,...o},l)=>{const h=q(E=>E.invalidate),u=q(E=>E.camera),c=q(E=>E.gl),d=q(E=>E.events),A=q(E=>E.set),f=q(E=>E.get),g=q(E=>E.performance),m=a||u,p=i||d.connected||c.domElement,C=S.useMemo(()=>new ME(m),[m]);return Qt(()=>{C.enabled&&C.update()},-1),S.useEffect(()=>(C.connect(p),()=>void C.dispose()),[p,e,C,h]),S.useEffect(()=>{const E=y=>{h(),e&&g.regress(),s&&s(y)};return C.addEventListener("change",E),n&&C.addEventListener("start",n),r&&C.addEventListener("end",r),()=>{C.removeEventListener("change",E),n&&C.removeEventListener("start",n),r&&C.removeEventListener("end",r)}},[s,n,r]),S.useEffect(()=>{if(t){const E=f().controls;return A({controls:C}),()=>A({controls:E})}},[t,C]),S.createElement("primitive",wt({ref:l,object:C},o))}),FI=S.forwardRef(({children:a,domElement:t,onChange:e,onMouseDown:i,onMouseUp:s,onObjectChange:n,object:r,makeDefault:o,camera:l,enabled:h,axis:u,mode:c,translationSnap:d,rotationSnap:A,scaleSnap:f,space:g,size:m,showX:p,showY:C,showZ:E,...y},v)=>{const T=q(N=>N.controls),B=q(N=>N.gl),_=q(N=>N.events),D=q(N=>N.camera),x=q(N=>N.invalidate),M=q(N=>N.get),k=q(N=>N.set),X=l||D,W=t||_.connected||B.domElement,H=S.useMemo(()=>new pE(X,W),[X,W]),Y=S.useRef(null);S.useLayoutEffect(()=>(r?H.attach(r instanceof Zt?r:r.current):Y.current instanceof Zt&&H.attach(Y.current),()=>void H.detach()),[r,a,H]),S.useEffect(()=>{if(T){const N=K=>T.enabled=!K.value;return H.addEventListener("dragging-changed",N),()=>H.removeEventListener("dragging-changed",N)}},[H,T]);const z=S.useRef(void 0),J=S.useRef(void 0),U=S.useRef(void 0),F=S.useRef(void 0);return S.useLayoutEffect(()=>void(z.current=e),[e]),S.useLayoutEffect(()=>void(J.current=i),[i]),S.useLayoutEffect(()=>void(U.current=s),[s]),S.useLayoutEffect(()=>void(F.current=n),[n]),S.useEffect(()=>{const N=tt=>{x(),z.current==null||z.current(tt)},K=tt=>J.current==null?void 0:J.current(tt),$=tt=>U.current==null?void 0:U.current(tt),R=tt=>F.current==null?void 0:F.current(tt);return H.addEventListener("change",N),H.addEventListener("mouseDown",K),H.addEventListener("mouseUp",$),H.addEventListener("objectChange",R),()=>{H.removeEventListener("change",N),H.removeEventListener("mouseDown",K),H.removeEventListener("mouseUp",$),H.removeEventListener("objectChange",R)}},[x,H]),S.useEffect(()=>{if(o){const N=M().controls;return k({controls:H}),()=>k({controls:N})}},[o,H]),S.createElement(S.Fragment,null,S.createElement("primitive",{ref:v,object:H,enabled:h,axis:u,mode:c,translationSnap:d,rotationSnap:A,scaleSnap:f,space:g,size:m,showX:p,showY:C,showZ:E}),S.createElement("group",wt({ref:Y},y),a))}),kI=S.forwardRef(({domElement:a,selector:t,onChange:e,onLock:i,onUnlock:s,enabled:n=!0,makeDefault:r,...o},l)=>{const{camera:h,...u}=o,c=q(v=>v.setEvents),d=q(v=>v.gl),A=q(v=>v.camera),f=q(v=>v.invalidate),g=q(v=>v.events),m=q(v=>v.get),p=q(v=>v.set),C=h||A,E=a||g.connected||d.domElement,y=S.useMemo(()=>new TE(C),[C]);return S.useEffect(()=>{if(n){y.connect(E);const v=m().events.compute;return c({compute(T,B){const _=B.size.width/2,D=B.size.height/2;B.pointer.set(_/B.size.width*2-1,-(D/B.size.height)*2+1),B.raycaster.setFromCamera(B.pointer,B.camera)}}),()=>{y.disconnect(),c({compute:v})}}},[n,y]),S.useEffect(()=>{const v=_=>{f(),e&&e(_)};y.addEventListener("change",v),i&&y.addEventListener("lock",i),s&&y.addEventListener("unlock",s);const T=()=>y.lock(),B=t?Array.from(document.querySelectorAll(t)):[document];return B.forEach(_=>_&&_.addEventListener("click",T)),()=>{y.removeEventListener("change",v),i&&y.removeEventListener("lock",i),s&&y.removeEventListener("unlock",s),B.forEach(_=>_?_.removeEventListener("click",T):void 0)}},[e,i,s,t,y,f]),S.useEffect(()=>{if(r){const v=m().controls;return p({controls:y}),()=>p({controls:v})}},[r,y]),S.createElement("primitive",wt({ref:l,object:y},u))}),OI=S.forwardRef(({domElement:a,makeDefault:t,...e},i)=>{const s=q(c=>c.camera),n=q(c=>c.gl),r=q(c=>c.events),o=q(c=>c.get),l=q(c=>c.set),h=a||r.connected||n.domElement,[u]=S.useState(()=>new fE(s,h));return S.useEffect(()=>{if(t){const c=o().controls;return l({controls:u}),()=>l({controls:c})}},[t,u]),Qt((c,d)=>{u.update(d)},-1),u?S.createElement("primitive",wt({ref:i,object:u},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},P=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Ti={NONE:0,IN:1,OUT:-1};function ui(a){return a.isPerspectiveCamera}function Ze(a){return a.isOrthographicCamera}const _i=Math.PI*2,fl=Math.PI/2,Kc=1e-5,os=Math.PI/180;function Ie(a,t,e){return Math.max(t,Math.min(e,a))}function Lt(a,t=Kc){return Math.abs(a)<t}function Bt(a,t,e=Kc){return Lt(a-t,e)}function gl(a,t){return Math.round(a/t)*t}function ls(a){return isFinite(a)?a:a<0?-Number.MAX_VALUE:Number.MAX_VALUE}function hs(a){return Math.abs(a)<Number.MAX_VALUE?a:a*(1/0)}function Hs(a,t,e,i,s=1/0,n){i=Math.max(1e-4,i);const r=2/i,o=r*n,l=1/(1+o+.48*o*o+.235*o*o*o);let h=a-t;const u=t,c=s*i;h=Ie(h,-c,c),t=a-h;const d=(e.value+r*h)*n;e.value=(e.value-r*d)*l;let A=t+(h+d)*l;return u-a>0==A>u&&(A=u,e.value=(A-u)/n),A}function ml(a,t,e,i,s=1/0,n,r){i=Math.max(1e-4,i);const o=2/i,l=o*n,h=1/(1+l+.48*l*l+.235*l*l*l);let u=t.x,c=t.y,d=t.z,A=a.x-u,f=a.y-c,g=a.z-d;const m=u,p=c,C=d,E=s*i,y=E*E,v=A*A+f*f+g*g;if(v>y){const H=Math.sqrt(v);A=A/H*E,f=f/H*E,g=g/H*E}u=a.x-A,c=a.y-f,d=a.z-g;const T=(e.x+o*A)*n,B=(e.y+o*f)*n,_=(e.z+o*g)*n;e.x=(e.x-o*T)*h,e.y=(e.y-o*B)*h,e.z=(e.z-o*_)*h,r.x=u+(A+T)*h,r.y=c+(f+B)*h,r.z=d+(g+_)*h;const D=m-a.x,x=p-a.y,M=C-a.z,k=r.x-m,X=r.y-p,W=r.z-C;return D*k+x*X+M*W>0&&(r.x=m,r.y=p,r.z=C,e.x=(r.x-m)/n,e.y=(r.y-p)/n,e.z=(r.z-C)/n),r}function hr(a,t){t.set(0,0),a.forEach(e=>{t.x+=e.clientX,t.y+=e.clientY}),t.x/=a.length,t.y/=a.length}function cr(a,t){return Ze(a)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}class QI{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 n=s.indexOf(e);n!==-1&&s.splice(n,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 n=0,r=s.length;n<r;n++)s[n].call(this,t)}}}var ur;const UI="2.10.1",Ks=1/8,GI=/Mac/.test((ur=globalThis==null?void 0:globalThis.navigator)===null||ur===void 0?void 0:ur.platform);let at,pl,$s,dr,te,dt,yt,xi,cs,Te,_e,di,El,Il,ce,us,Di,Cl,Ar,yl,fr,gr,Ys,mr=class ta extends QI{static install(t){at=t.THREE,pl=Object.freeze(new at.Vector3(0,0,0)),$s=Object.freeze(new at.Vector3(0,1,0)),dr=Object.freeze(new at.Vector3(0,0,1)),te=new at.Vector2,dt=new at.Vector3,yt=new at.Vector3,xi=new at.Vector3,cs=new at.Vector3,Te=new at.Vector3,_e=new at.Vector3,di=new at.Vector3,El=new at.Vector3,Il=new at.Vector3,ce=new at.Spherical,us=new at.Spherical,Di=new at.Box3,Cl=new at.Box3,Ar=new at.Sphere,yl=new at.Quaternion,fr=new at.Quaternion,gr=new at.Matrix4,Ys=new at.Raycaster}static get ACTION(){return P}set verticalDragToForward(t){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}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.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=P.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=Ti.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new at.Vector3,this._focalOffsetVelocity=new at.Vector3,this._zoomVelocity={value:0},this._truckInternal=(p,C,E,y)=>{let v,T;if(ui(this._camera)){const B=dt.copy(this._camera.position).sub(this._target),_=this._camera.getEffectiveFOV()*os,D=B.length()*Math.tan(_*.5);v=this.truckSpeed*p*D/this._elementRect.height,T=this.truckSpeed*C*D/this._elementRect.height}else if(Ze(this._camera)){const B=this._camera;v=this.truckSpeed*p*(B.right-B.left)/B.zoom/this._elementRect.width,T=this.truckSpeed*C*(B.top-B.bottom)/B.zoom/this._elementRect.height}else return;y?(E?this.setFocalOffset(this._focalOffsetEnd.x+v,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(v,0,!0),this.forward(-T,!0)):E?this.setFocalOffset(this._focalOffsetEnd.x+v,this._focalOffsetEnd.y+T,this._focalOffsetEnd.z,!0):this.truck(v,T,!0)},this._rotateInternal=(p,C)=>{const E=_i*this.azimuthRotateSpeed*p/this._elementRect.height,y=_i*this.polarRotateSpeed*C/this._elementRect.height;this.rotate(E,y,!0)},this._dollyInternal=(p,C,E)=>{const y=Math.pow(.95,-p*this.dollySpeed),v=this._sphericalEnd.radius,T=this._sphericalEnd.radius*y,B=Ie(T,this.minDistance,this.maxDistance),_=B-T;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(T,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(_,!0),this._dollyToNoClamp(B,!0)):this._dollyToNoClamp(B,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?T:B)-v,this._dollyControlCoord.set(C,E)),this._lastDollyDirection=Math.sign(-p)},this._zoomInternal=(p,C,E)=>{const y=Math.pow(.95,p*this.dollySpeed),v=this._zoom,T=this._zoom*y;this.zoomTo(T,!0),this.dollyToCursor&&(this._changedZoom+=T-v,this._dollyControlCoord.set(C,E))},typeof at>"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 at.Quaternion().setFromUnitVectors(this._camera.up,$s),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=P.NONE,this._target=new at.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new at.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new at.Spherical().setFromVector3(dt.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 at.Vector3,new at.Vector3,new at.Vector3,new at.Vector3],this._updateNearPlaneCorners(),this._boundary=new at.Box3(new at.Vector3(-1/0,-1/0,-1/0),new at.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 at.Vector2,this.mouseButtons={left:P.ROTATE,middle:P.DOLLY,right:P.TRUCK,wheel:ui(this._camera)?P.DOLLY:Ze(this._camera)?P.ZOOM:P.NONE},this.touches={one:P.TOUCH_ROTATE,two:ui(this._camera)?P.TOUCH_DOLLY_TRUCK:Ze(this._camera)?P.TOUCH_ZOOM_TRUCK:P.NONE,three:P.TOUCH_TRUCK};const i=new at.Vector2,s=new at.Vector2,n=new at.Vector2,r=p=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const y=this._domElement.getBoundingClientRect(),v=p.clientX/y.width,T=p.clientY/y.height;if(v<this._interactiveArea.left||v>this._interactiveArea.right||T<this._interactiveArea.top||T>this._interactiveArea.bottom)return}const C=p.pointerType!=="mouse"?null:(p.buttons&Ft.LEFT)===Ft.LEFT?Ft.LEFT:(p.buttons&Ft.MIDDLE)===Ft.MIDDLE?Ft.MIDDLE:(p.buttons&Ft.RIGHT)===Ft.RIGHT?Ft.RIGHT:null;if(C!==null){const y=this._findPointerByMouseButton(C);y&&this._disposePointer(y)}if((p.buttons&Ft.LEFT)===Ft.LEFT&&this._lockedPointer)return;const E={pointerId:p.pointerId,clientX:p.clientX,clientY:p.clientY,deltaX:0,deltaY:0,mouseButton:C};this._activePointers.push(E),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,d(p)},o=p=>{p.cancelable&&p.preventDefault();const C=p.pointerId,E=this._lockedPointer||this._findPointerById(C);if(E){if(E.clientX=p.clientX,E.clientY=p.clientY,E.deltaX=p.movementX,E.deltaY=p.movementY,this._state=0,p.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&&(p.buttons&Ft.LEFT)===Ft.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(p.buttons&Ft.MIDDLE)===Ft.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(p.buttons&Ft.RIGHT)===Ft.RIGHT&&(this._state=this._state|this.mouseButtons.right);A()}},l=p=>{const C=this._findPointerById(p.pointerId);if(!(C&&C===this._lockedPointer)){if(C&&this._disposePointer(C),p.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=P.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=P.NONE;f()}};let h=-1;const u=p=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===P.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const T=this._domElement.getBoundingClientRect(),B=p.clientX/T.width,_=p.clientY/T.height;if(B<this._interactiveArea.left||B>this._interactiveArea.right||_<this._interactiveArea.top||_>this._interactiveArea.bottom)return}if(p.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===P.ROTATE||this.mouseButtons.wheel===P.TRUCK){const T=performance.now();h-T<1e3&&this._getClientRect(this._elementRect),h=T}const C=GI?-1:-3,E=p.deltaMode===1||p.ctrlKey?p.deltaY/C:p.deltaY/(C*10),y=this.dollyToCursor?(p.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,v=this.dollyToCursor?(p.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case P.ROTATE:{this._rotateInternal(p.deltaX,p.deltaY),this._isUserControllingRotate=!0;break}case P.TRUCK:{this._truckInternal(p.deltaX,p.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case P.SCREEN_PAN:{this._truckInternal(p.deltaX,p.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case P.OFFSET:{this._truckInternal(p.deltaX,p.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case P.DOLLY:{this._dollyInternal(-E,y,v),this._isUserControllingDolly=!0;break}case P.ZOOM:{this._zoomInternal(-E,y,v),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},c=p=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===ta.ACTION.NONE){const C=p instanceof PointerEvent?p.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}p.preventDefault()}},d=p=>{if(!this._enabled)return;if(hr(this._activePointers,te),this._getClientRect(this._elementRect),i.copy(te),s.copy(te),this._activePointers.length>=2){const E=te.x-this._activePointers[1].clientX,y=te.y-this._activePointers[1].clientY,v=Math.sqrt(E*E+y*y);n.set(0,v);const T=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,B=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(T,B)}if(this._state=0,!p)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in p&&p.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&&(p.buttons&Ft.LEFT)===Ft.LEFT&&(this._state=this._state|this.mouseButtons.left),(p.buttons&Ft.MIDDLE)===Ft.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(p.buttons&Ft.RIGHT)===Ft.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&P.ROTATE)===P.ROTATE||(this._state&P.TOUCH_ROTATE)===P.TOUCH_ROTATE||(this._state&P.TOUCH_DOLLY_ROTATE)===P.TOUCH_DOLLY_ROTATE||(this._state&P.TOUCH_ZOOM_ROTATE)===P.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&P.TRUCK)===P.TRUCK||(this._state&P.SCREEN_PAN)===P.SCREEN_PAN||(this._state&P.TOUCH_TRUCK)===P.TOUCH_TRUCK||(this._state&P.TOUCH_SCREEN_PAN)===P.TOUCH_SCREEN_PAN||(this._state&P.TOUCH_DOLLY_TRUCK)===P.TOUCH_DOLLY_TRUCK||(this._state&P.TOUCH_DOLLY_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN||(this._state&P.TOUCH_ZOOM_TRUCK)===P.TOUCH_ZOOM_TRUCK||(this._state&P.TOUCH_ZOOM_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&P.DOLLY)===P.DOLLY||(this._state&P.TOUCH_DOLLY)===P.TOUCH_DOLLY||(this._state&P.TOUCH_DOLLY_TRUCK)===P.TOUCH_DOLLY_TRUCK||(this._state&P.TOUCH_DOLLY_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN||(this._state&P.TOUCH_DOLLY_OFFSET)===P.TOUCH_DOLLY_OFFSET||(this._state&P.TOUCH_DOLLY_ROTATE)===P.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&P.ZOOM)===P.ZOOM||(this._state&P.TOUCH_ZOOM)===P.TOUCH_ZOOM||(this._state&P.TOUCH_ZOOM_TRUCK)===P.TOUCH_ZOOM_TRUCK||(this._state&P.TOUCH_ZOOM_SCREEN_PAN)===P.TOUCH_ZOOM_SCREEN_PAN||(this._state&P.TOUCH_ZOOM_OFFSET)===P.TOUCH_ZOOM_OFFSET||(this._state&P.TOUCH_ZOOM_ROTATE)===P.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&P.OFFSET)===P.OFFSET||(this._state&P.TOUCH_OFFSET)===P.TOUCH_OFFSET||(this._state&P.TOUCH_DOLLY_OFFSET)===P.TOUCH_DOLLY_OFFSET||(this._state&P.TOUCH_ZOOM_OFFSET)===P.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},A=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,hr(this._activePointers,te);const C=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,E=C?-C.deltaX:s.x-te.x,y=C?-C.deltaY:s.y-te.y;if(s.copy(te),((this._state&P.ROTATE)===P.ROTATE||(this._state&P.TOUCH_ROTATE)===P.TOUCH_ROTATE||(this._state&P.TOUCH_DOLLY_ROTATE)===P.TOUCH_DOLLY_ROTATE||(this._state&P.TOUCH_ZOOM_ROTATE)===P.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(E,y),this._isUserControllingRotate=!0),(this._state&P.DOLLY)===P.DOLLY||(this._state&P.ZOOM)===P.ZOOM){const v=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,B=this.dollyDragInverted?-1:1;(this._state&P.DOLLY)===P.DOLLY?(this._dollyInternal(B*y*Ks,v,T),this._isUserControllingDolly=!0):(this._zoomInternal(B*y*Ks,v,T),this._isUserControllingZoom=!0)}if((this._state&P.TOUCH_DOLLY)===P.TOUCH_DOLLY||(this._state&P.TOUCH_ZOOM)===P.TOUCH_ZOOM||(this._state&P.TOUCH_DOLLY_TRUCK)===P.TOUCH_DOLLY_TRUCK||(this._state&P.TOUCH_ZOOM_TRUCK)===P.TOUCH_ZOOM_TRUCK||(this._state&P.TOUCH_DOLLY_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN||(this._state&P.TOUCH_ZOOM_SCREEN_PAN)===P.TOUCH_ZOOM_SCREEN_PAN||(this._state&P.TOUCH_DOLLY_OFFSET)===P.TOUCH_DOLLY_OFFSET||(this._state&P.TOUCH_ZOOM_OFFSET)===P.TOUCH_ZOOM_OFFSET||(this._state&P.TOUCH_DOLLY_ROTATE)===P.TOUCH_DOLLY_ROTATE||(this._state&P.TOUCH_ZOOM_ROTATE)===P.TOUCH_ZOOM_ROTATE){const v=te.x-this._activePointers[1].clientX,T=te.y-this._activePointers[1].clientY,B=Math.sqrt(v*v+T*T),_=n.y-B;n.set(0,B);const D=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&P.TOUCH_DOLLY)===P.TOUCH_DOLLY||(this._state&P.TOUCH_DOLLY_ROTATE)===P.TOUCH_DOLLY_ROTATE||(this._state&P.TOUCH_DOLLY_TRUCK)===P.TOUCH_DOLLY_TRUCK||(this._state&P.TOUCH_DOLLY_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN||(this._state&P.TOUCH_DOLLY_OFFSET)===P.TOUCH_DOLLY_OFFSET?(this._dollyInternal(_*Ks,D,x),this._isUserControllingDolly=!0):(this._zoomInternal(_*Ks,D,x),this._isUserControllingZoom=!0)}((this._state&P.TRUCK)===P.TRUCK||(this._state&P.TOUCH_TRUCK)===P.TOUCH_TRUCK||(this._state&P.TOUCH_DOLLY_TRUCK)===P.TOUCH_DOLLY_TRUCK||(this._state&P.TOUCH_ZOOM_TRUCK)===P.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(E,y,!1,!1),this._isUserControllingTruck=!0),((this._state&P.SCREEN_PAN)===P.SCREEN_PAN||(this._state&P.TOUCH_SCREEN_PAN)===P.TOUCH_SCREEN_PAN||(this._state&P.TOUCH_DOLLY_SCREEN_PAN)===P.TOUCH_DOLLY_SCREEN_PAN||(this._state&P.TOUCH_ZOOM_SCREEN_PAN)===P.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(E,y,!1,!0),this._isUserControllingTruck=!0),((this._state&P.OFFSET)===P.OFFSET||(this._state&P.TOUCH_OFFSET)===P.TOUCH_OFFSET||(this._state&P.TOUCH_DOLLY_OFFSET)===P.TOUCH_DOLLY_OFFSET||(this._state&P.TOUCH_ZOOM_OFFSET)===P.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(E,y,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{hr(this._activePointers,te),s.copy(te),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",m),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var p,C,E;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(p=this._domElement)===null||p===void 0||p.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",m),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},m=()=>{this.unlockPointer()};this._addAllEventListeners=p=>{this._domElement=p,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",c)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",c),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",m))},this.cancel=()=>{this._state!==P.NONE&&(this._state=P.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=Ie(t.width,0,1),this._interactiveArea.height=Ie(t.height,0,1),this._interactiveArea.x=Ie(t.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ie(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=Ie(t,this.minAzimuthAngle,this.maxAzimuthAngle),n=Ie(e,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(t,e=!1){return this.dollyTo(this._sphericalEnd.radius-t,e)}dollyTo(t,e=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Ti.NONE,this._changedDolly=0,this._dollyToNoClamp(Ie(t,this.minDistance,this.maxDistance),e)}_dollyToNoClamp(t,e=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Bt(r,this._spherical.radius);if(!(i>t)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(t,r)}else this._sphericalEnd.radius=t;this._needsUpdate=!0,e||(this._spherical.radius=this._sphericalEnd.radius);const n=!e||Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(cs).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(t,e=!1){return this.zoomTo(this._zoomEnd+t,e)}zoomTo(t,e=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ie(t,this.minZoom,this.maxZoom),this._needsUpdate=!0,e||(this._zoom=this._zoomEnd);const i=!e||Bt(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(t,e,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(t,e,i)}truck(t,e,i=!1){this._camera.updateMatrix(),Te.setFromMatrixColumn(this._camera.matrix,0),_e.setFromMatrixColumn(this._camera.matrix,1),Te.multiplyScalar(t),_e.multiplyScalar(-e);const s=dt.copy(Te).add(_e),n=yt.copy(this._targetEnd).add(s);return this.moveTo(n.x,n.y,n.z,i)}forward(t,e=!1){dt.setFromMatrixColumn(this._camera.matrix,0),dt.crossVectors(this._camera.up,dt),dt.multiplyScalar(t);const i=yt.copy(this._targetEnd).add(dt);return this.moveTo(i.x,i.y,i.z,e)}elevate(t,e=!1){return dt.copy(this._camera.up).multiplyScalar(t),this.moveTo(this._targetEnd.x+dt.x,this._targetEnd.y+dt.y,this._targetEnd.z+dt.z,e)}moveTo(t,e,i,s=!1){this._isUserControllingTruck=!1;const n=dt.set(t,e,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(t,e,i,s=!1){const o=dt.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:n=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],h=t.isBox3?Di.copy(t):Di.setFromObject(t);h.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=gl(this._sphericalEnd.theta,fl),c=gl(this._sphericalEnd.phi,fl);l.push(this.rotateTo(u,c,e));const d=dt.setFromSpherical(this._sphericalEnd).normalize(),A=yl.setFromUnitVectors(d,dr),f=Bt(Math.abs(d.y),1);f&&A.multiply(fr.setFromAxisAngle($s,u)),A.multiply(this._yAxisUpSpaceInverse);const g=Cl.makeEmpty();yt.copy(h.min).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.min).setX(h.max.x).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.min).setY(h.max.y).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.max).setZ(h.min.z).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.min).setZ(h.max.z).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.max).setY(h.min.y).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.max).setX(h.min.x).applyQuaternion(A),g.expandByPoint(yt),yt.copy(h.max).applyQuaternion(A),g.expandByPoint(yt),g.min.x-=s,g.min.y-=r,g.max.x+=n,g.max.y+=o,A.setFromUnitVectors(dr,d),f&&A.premultiply(fr.invert()),A.premultiply(this._yAxisUpSpace);const m=g.getSize(dt),p=g.getCenter(yt).applyQuaternion(A);if(ui(this._camera)){const C=this.getDistanceToFitBox(m.x,m.y,m.z,i);l.push(this.moveTo(p.x,p.y,p.z,e)),l.push(this.dollyTo(C,e)),l.push(this.setFocalOffset(0,0,0,e))}else if(Ze(this._camera)){const C=this._camera,E=C.right-C.left,y=C.top-C.bottom,v=i?Math.max(E/m.x,y/m.y):Math.min(E/m.x,y/m.y);l.push(this.moveTo(p.x,p.y,p.z,e)),l.push(this.zoomTo(v,e)),l.push(this.setFocalOffset(0,0,0,e))}return Promise.all(l)}fitToSphere(t,e){const i=[],n="isObject3D"in t?ta.createBoundingSphere(t,Ar):Ar.copy(t);if(i.push(this.moveTo(n.center.x,n.center.y,n.center.z,e)),ui(this._camera)){const r=this.getDistanceToFitSphere(n.radius);i.push(this.dollyTo(r,e))}else if(Ze(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*n.radius,h=Math.min(r/l,o/l);i.push(this.zoomTo(h,e))}return i.push(this.setFocalOffset(0,0,0,e)),Promise.all(i)}setLookAt(t,e,i,s,n,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ti.NONE,this._changedDolly=0;const l=yt.set(s,n,r),h=dt.set(t,e,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(h.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold)&&Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(t,e,i,s,n,r,o,l,h,u,c,d,A,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ti.NONE,this._changedDolly=0;const g=dt.set(s,n,r),m=yt.set(t,e,i);ce.setFromVector3(m.sub(g).applyQuaternion(this._yAxisUpSpace));const p=xi.set(u,c,d),C=yt.set(o,l,h);us.setFromVector3(C.sub(p).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(p,A));const E=us.theta-ce.theta,y=us.phi-ce.phi,v=us.radius-ce.radius;this._sphericalEnd.set(ce.radius+v*A,ce.phi+y*A,ce.theta+E*A),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const T=!f||Bt(this._target.x,this._targetEnd.x,this.restThreshold)&&Bt(this._target.y,this._targetEnd.y,this.restThreshold)&&Bt(this._target.z,this._targetEnd.z,this.restThreshold)&&Bt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Bt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Bt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(T)}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 n=this.getPosition(dt),r=this.setLookAt(n.x,n.y,n.z,t,e,i,s);return this._sphericalEnd.phi=Ie(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}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 n=!s||Bt(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Bt(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Bt(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(t,e,i){this._camera.updateMatrixWorld(),Te.setFromMatrixColumn(this._camera.matrixWorldInverse,0),_e.setFromMatrixColumn(this._camera.matrixWorldInverse,1),di.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=dt.set(t,e,i),n=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);Te.multiplyScalar(r.x),_e.multiplyScalar(r.y),di.multiplyScalar(r.z),dt.copy(Te).add(_e).add(di),dt.z=dt.z+n,this.dollyTo(n,!1),this.setFocalOffset(-dt.x,dt.y,-dt.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 at.Vector4,typeof t=="number"?this._viewport.set(t,e,i,s):this._viewport.copy(t)}getDistanceToFitBox(t,e,i,s=!1){if(cr(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=t/e,r=this._camera.getEffectiveFOV()*os,o=this._camera.aspect;return((s?n>o:n<o)?e:t/o)*.5/Math.tan(r*.5)+i*.5}getDistanceToFitSphere(t){if(cr(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*os,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 at.Vector3).copy(e?this._targetEnd:this._target)}getPosition(t,e=!0){return(t&&t.isVector3?t:new at.Vector3).setFromSpherical(e?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(e?this._targetEnd:this._target)}getSpherical(t,e=!0){return(t||new at.Spherical).copy(e?this._sphericalEnd:this._spherical)}getFocalOffset(t,e=!0){return(t&&t.isVector3?t:new at.Vector3).copy(e?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%_i,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=_i),this._spherical.theta+=_i*Math.round((this._sphericalEnd.theta-this._spherical.theta)/_i)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!Bt(this._camera.up.x,this._cameraUp0.x)||!Bt(this._camera.up.y,this._cameraUp0.y)||!Bt(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const i=this.getPosition(dt);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,$s),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const t=dt.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(dt);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,n=El.subVectors(this._targetEnd,this._target),r=Il.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Lt(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const c=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Hs(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,c,1/0,t),this._needsUpdate=!0}if(Lt(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const c=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Hs(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,c,1/0,t),this._needsUpdate=!0}if(Lt(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const c=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Hs(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,c,this.maxSpeed,t),this._needsUpdate=!0}if(Lt(n.x)&&Lt(n.y)&&Lt(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const c=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;ml(this._target,this._targetEnd,this._targetVelocity,c,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(Lt(r.x)&&Lt(r.y)&&Lt(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const c=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;ml(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,c,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(Lt(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const c=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Hs(this._zoom,this._zoomEnd,this._zoomVelocity,c,1/0,t)}if(this.dollyToCursor){if(ui(this._camera)&&this._changedDolly!==0){const c=this._spherical.radius-this._lastDistance,d=this._camera,A=this._getCameraDirection(cs),f=dt.copy(A).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const g=yt.crossVectors(f,A),m=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*os*.5),C=(this._sphericalEnd.radius-c-this._sphericalEnd.radius)/this._sphericalEnd.radius,E=xi.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*m*d.aspect)).add(g.multiplyScalar(this._dollyControlCoord.y*m)),y=dt.copy(this._targetEnd).lerp(E,C),v=this._lastDollyDirection===Ti.IN&&this._spherical.radius<=this.minDistance,T=this._lastDollyDirection===Ti.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(v||T)){this._sphericalEnd.radius-=c,this._spherical.radius-=c;const _=yt.copy(A).multiplyScalar(-c);y.add(_)}this._boundary.clampPoint(y,y);const B=yt.subVectors(y,this._targetEnd);this._targetEnd.copy(y),this._target.add(B),this._changedDolly-=c,Lt(this._changedDolly)&&(this._changedDolly=0)}else if(Ze(this._camera)&&this._changedZoom!==0){const c=this._zoom-this._lastZoom,d=this._camera,A=dt.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),f=yt.set(0,0,-1).applyQuaternion(d.quaternion),g=xi.copy(A).add(f.multiplyScalar(-A.dot(d.up))),p=-(this._zoom-c-this._zoom)/this._zoom,C=this._getCameraDirection(cs),E=this._targetEnd.dot(C),y=dt.copy(this._targetEnd).lerp(g,p),v=y.dot(C),T=C.multiplyScalar(v-E);y.sub(T),this._boundary.clampPoint(y,y);const B=yt.subVectors(y,this._targetEnd);this._targetEnd.copy(y),this._target.add(B),this._changedZoom-=c,Lt(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),(!Lt(this._focalOffset.x)||!Lt(this._focalOffset.y)||!Lt(this._focalOffset.z))&&(Te.setFromMatrixColumn(this._camera.matrix,0),_e.setFromMatrixColumn(this._camera.matrix,1),di.setFromMatrixColumn(this._camera.matrix,2),Te.multiplyScalar(this._focalOffset.x),_e.multiplyScalar(-this._focalOffset.y),di.multiplyScalar(this._focalOffset.z),dt.copy(Te).add(_e).add(di),this._camera.position.add(dt),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),dt.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const u=this._needsUpdate;return u&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):u?(this.dispatchEvent({type:"update"}),Lt(e,this.restThreshold)&&Lt(i,this.restThreshold)&&Lt(s,this.restThreshold)&&Lt(n.x,this.restThreshold)&&Lt(n.y,this.restThreshold)&&Lt(n.z,this.restThreshold)&&Lt(r.x,this.restThreshold)&&Lt(r.y,this.restThreshold)&&Lt(r.z,this.restThreshold)&&Lt(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!u&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=u,this._needsUpdate=!1,u}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:ls(this.maxDistance),minZoom:this.minZoom,maxZoom:ls(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:ls(this.maxPolarAngle),minAzimuthAngle:ls(this.minAzimuthAngle),maxAzimuthAngle:ls(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:dt.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=hs(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=hs(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=hs(i.maxPolarAngle),this.minAzimuthAngle=hs(i.minAzimuthAngle),this.maxAzimuthAngle=hs(i.maxAzimuthAngle),this.smoothTime=i.smoothTime,this.draggingSmoothTime=i.draggingSmoothTime,this.dollySpeed=i.dollySpeed,this.truckSpeed=i.truckSpeed,this.dollyToCursor=i.dollyToCursor,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),ce.setFromVector3(dt.fromArray(i.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ce.theta,ce.phi,e),this.dollyTo(ce.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",UI),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 n=yt.copy(e).add(t),o=this._boundary.clampPoint(n,xi).sub(n),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 h=1+i*l/e.dot(o);return t.add(yt.copy(e).multiplyScalar(h)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(ui(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*os,s=Math.tan(i*.5)*e,n=s*t.aspect;this._nearPlaneCorners[0].set(-n,-s,0),this._nearPlaneCorners[1].set(n,-s,0),this._nearPlaneCorners[2].set(n,s,0),this._nearPlaneCorners[3].set(-n,s,0)}else if(Ze(this._camera)){const t=this._camera,e=1/t.zoom,i=t.left*e,s=t.right*e,n=t.top*e,r=t.bottom*e;this._nearPlaneCorners[0].set(i,n,0),this._nearPlaneCorners[1].set(s,n,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let t=1/0;if(!(this.colliderMeshes.length>=1)||cr(this._camera,"_collisionTest"))return t;const i=this._getTargetDirection(cs);gr.lookAt(pl,i,this._camera.up);for(let s=0;s<4;s++){const n=yt.copy(this._nearPlaneCorners[s]);n.applyMatrix4(gr);const r=xi.addVectors(this._target,n);Ys.set(r,i),Ys.far=this._spherical.radius+1;const o=Ys.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 at.Sphere){const i=e,s=i.center;Di.makeEmpty(),t.traverseVisible(r=>{r.isMesh&&Di.expandByObject(r)}),Di.getCenter(s);let n=0;return t.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let c=0,d=u.count;c<d;c++)dt.fromBufferAttribute(u,c),n=Math.max(n,s.distanceToSquared(dt))}),i.radius=Math.sqrt(n),i}};const NI=S.forwardRef((a,t)=>{S.useMemo(()=>{const v={Box3:Yh,MathUtils:{clamp:ot.clamp},Matrix4:At,Quaternion:It,Raycaster:Pn,Sphere:Ba,Spherical:ya,Vector2:Kt,Vector3:Q,Vector4:ze};mr.install({THREE:v}),zh({CameraControlsImpl:mr})},[]);const{camera:e,domElement:i,makeDefault:s,onStart:n,onEnd:r,onChange:o,regress:l,...h}=a,u=q(v=>v.camera),c=q(v=>v.gl),d=q(v=>v.invalidate),A=q(v=>v.events),f=q(v=>v.setEvents),g=q(v=>v.set),m=q(v=>v.get),p=q(v=>v.performance),C=e||u,E=i||A.connected||c.domElement,y=S.useMemo(()=>new mr(C),[C]);return Qt((v,T)=>{y.enabled&&y.update(T)},-1),S.useEffect(()=>(y.connect(E),()=>void y.disconnect()),[E,y]),S.useEffect(()=>{const v=_=>{d(),l&&p.regress(),o&&o(_)},T=_=>{n&&n(_)},B=_=>{r&&r(_)};return y.addEventListener("update",v),y.addEventListener("controlstart",T),y.addEventListener("controlend",B),y.addEventListener("control",v),y.addEventListener("transitionstart",v),y.addEventListener("wake",v),()=>{y.removeEventListener("update",v),y.removeEventListener("controlstart",T),y.removeEventListener("controlend",B),y.removeEventListener("control",v),y.removeEventListener("transitionstart",v),y.removeEventListener("wake",v)}},[y,n,r,d,f,l,o]),S.useEffect(()=>{if(s){const v=m().controls;return g({controls:y}),()=>g({controls:v})}},[s,y]),S.createElement("primitive",wt({ref:t,object:y},h))}),HI=a=>(a==null?void 0:a.current)instanceof Zt,$c=S.createContext(null);function Yc(){const a=S.useContext($c);if(!a)throw new Error("useMotion hook must be used in a MotionPathControls component.");return a}function KI({points:a=50,color:t="black"}){const{path:e}=Yc(),[i,s]=S.useState([]),n=S.useMemo(()=>new va({color:t}),[t]),r=S.useMemo(()=>new $h(.025,16,16),[]),o=S.useRef([]);return S.useEffect(()=>{e.curves!==o.current&&(s(e.getPoints(a)),o.current=e.curves)}),i.map((l,h)=>S.createElement("mesh",{key:h,material:n,geometry:r,position:[l.x,l.y,l.z]}))}const $I=S.forwardRef(({children:a,curves:t=[],debug:e=!1,debugColor:i="black",object:s,focus:n,loop:r=!0,offset:o=void 0,smooth:l=!1,eps:h=1e-5,damping:u=.1,focusDamping:c=.1,maxSpeed:d=1/0,...A},f)=>{const{camera:g}=q(),m=S.useRef(null),p=S.useRef(o??0),C=S.useMemo(()=>new EA,[]),E=S.useMemo(()=>({focus:n,object:(s==null?void 0:s.current)instanceof Zt?s:{current:g},path:C,current:p.current,offset:p.current,point:new Q,tangent:new Q,next:new Q}),[n,s]),y=IA(m);S.useLayoutEffect(()=>{const T=y.current;C.curves=[];const B=t.length>0?t:T.children.map(_=>_.object);for(let _=0;_<B.length;_++)C.add(B[_]);if(l){const _=C.getPoints(typeof l=="number"?l:1),D=new CA(_);C.curves=[D]}C.updateArcLengths()}),S.useImperativeHandle(f,()=>Object.assign(m.current,{motion:E}),[E]),S.useLayoutEffect(()=>{p.current=ks.repeat(p.current,1)},[o]);const v=S.useMemo(()=>new Q,[]);return Qt((T,B)=>{const _=E.offset;if(si.damp(p,"current",o!==void 0?o:E.current,u,B,d,void 0,h),E.offset=r?ks.repeat(p.current,1):ks.clamp(p.current,0,1),C.getCurveLengths().length>0){C.getPointAt(E.offset,E.point),C.getTangentAt(E.offset,E.tangent).normalize(),C.getPointAt(ks.repeat(p.current-(_-E.offset),1),E.next);const D=(s==null?void 0:s.current)instanceof Zt?s.current:g;D.position.copy(E.point),n&&si.dampLookAt(D,HI(n)?n.current.getWorldPosition(v):n,c,B,d,void 0,h)}}),S.createElement("group",wt({ref:m},A),S.createElement($c.Provider,{value:E},a,e&&S.createElement(KI,{color:i})))});function Oa(a,{path:t}){const[e]=Se(qh,[a],i=>i.setPath(t));return e}Oa.preload=(a,{path:t})=>Se.preload(qh,[a],e=>e.setPath(t));function YI({children:a,files:t,...e}){const i=Oa(t,{...e});return S.createElement(S.Fragment,null,a==null?void 0:a(i))}function kn(a){return Se(Ma,a)}kn.preload=a=>Se.preload(Ma,a);kn.clear=a=>Se.clear(Ma,a);function VI({path:a,...t}){const i=kn(a).children[0];return S.createElement(Ta,wt({},t,{object:i}))}const Vc="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master";function On(a,t=`${Vc}/basis/`){const e=q(s=>s.gl),i=Se(ka,zr(a)?Object.values(a):a,s=>{s.detectSupport(e),s.setTranscoderPath(t)});if(S.useEffect(()=>{(Array.isArray(i)?i:[i]).forEach(e.initTexture)},[e,i]),zr(a)){const s=Object.keys(a),n={};return s.forEach(r=>Object.assign(n,{[r]:i[s.indexOf(r)]})),n}else return i}On.preload=(a,t=`${Vc}/basis/`)=>Se.preload(ka,a,e=>{e.setTranscoderPath(t)});On.clear=a=>Se.clear(ka,a);const JI=({children:a,input:t,basisPath:e})=>{const i=On(t,e);return S.createElement(S.Fragment,null,a==null?void 0:a(i))},j=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},zI=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=qI},qI=Number.MAX_SAFE_INTEGER||9007199254740991;let et=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),b=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a}({}),I=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a}({});var gt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ri{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 XI{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 Ri(t),this.fast_=new Ri(e),this.defaultTTFB_=s,this.ttfb_=new Ri(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new Ri(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Ri(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new Ri(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){t=Math.max(t,this.minDelayMs_);const i=8*e,s=t/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function WI(a,t,e){return(t=ZI(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function xt(){return xt=Object.assign?Object.assign.bind():function(a){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)({}).hasOwnProperty.call(e,i)&&(a[i]=e[i])}return a},xt.apply(null,arguments)}function vl(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(a);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),e.push.apply(e,i)}return e}function St(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?vl(Object(e),!0).forEach(function(i){WI(a,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):vl(Object(e)).forEach(function(i){Object.defineProperty(a,i,Object.getOwnPropertyDescriptor(e,i))})}return a}function jI(a,t){if(typeof a!="object"||!a)return a;var e=a[Symbol.toPrimitive];if(e!==void 0){var i=e.call(a,t);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(a)}function ZI(a){var t=jI(a,"string");return typeof t=="symbol"?t:t+""}class qe{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=ti,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const ti=function(){},tC={trace:ti,debug:ti,log:ti,warn:ti,info:ti,error:ti};function ea(){return xt({},tC)}function eC(a,t){const e=self.console[a];return e?e.bind(self.console,`${t?"["+t+"] ":""}[${a}] >`):ti}function Bl(a,t,e){return t[a]?t[a].bind(t):eC(a,e)}const ia=ea();function iC(a,t,e){const i=ea();if(typeof console=="object"&&a===!0||typeof a=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Bl(n,a,e)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.2`)}catch{return ea()}s.forEach(n=>{ia[n]=Bl(n,a)})}else xt(ia,i);return i}const Et=ia;function Je(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function sC(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Jc(a,t){const e=Object.keys(a),i=Object.keys(t),s=e.length,n=i.length;return!s||!n||s===n&&!e.some(r=>i.indexOf(r)===-1)}function ae(a,t=!1){if(typeof TextDecoder<"u"){const h=new TextDecoder("utf-8").decode(a);if(t){const u=h.indexOf("\0");return u!==-1?h.substring(0,u):h}return h.replace(/\0/g,"")}const e=a.length;let i,s,n,r="",o=0;for(;o<e;){if(i=a[o++],i===0&&t)return r;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:r+=String.fromCharCode(i);break;case 12:case 13:s=a[o++],r+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=a[o++],n=a[o++],r+=String.fromCharCode((i&15)<<12|(s&63)<<6|(n&63)<<0);break}}return r}const Le={hexDump:function(a){let t="";for(let e=0;e<a.length;e++){let i=a[e].toString(16);i.length<2&&(i="0"+i),t+=i}return t}};function nC(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var pr={exports:{}},Sl;function rC(){return Sl||(Sl=1,function(a,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,u){if(u=u||{},l=l.trim(),h=h.trim(),!h){if(!u.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var d=o.parseURL(h);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return u.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):h;var A=o.parseURL(l);if(!A)throw new Error("Error trying to parse base URL.");if(!A.netLoc&&A.path&&A.path[0]!=="/"){var f=s.exec(A.path);A.netLoc=f[1],A.path=f[2]}A.netLoc&&!A.path&&(A.path="/");var g={scheme:A.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(g.netLoc=A.netLoc,d.path[0]!=="/"))if(!d.path)g.path=A.path,d.params||(g.params=A.params,d.query||(g.query=A.query));else{var m=A.path,p=m.substring(0,m.lastIndexOf("/")+1)+d.path;g.path=o.normalizePath(p)}return g.path===null&&(g.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(g)},parseURL:function(l){var h=i.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(r,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()}(pr)),pr.exports}var Qa=rC();class Qn{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 _t={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Ua{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t=="string"&&(t={url:t}),this.base=t,aC(this,"stats")}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 baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[_t.AUDIO]:null,[_t.VIDEO]:null,[_t.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Qn),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Qa.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[_t.AUDIO]=null,t[_t.VIDEO]=null,t[_t.AUDIOVIDEO]=null}}function zt(a){return a.sn!=="initSegment"}class cn extends Ua{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=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.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,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 byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange){const t=this.byteRange[0],e=this.byteRange[1];if(j(t)&&j(e))return e-t}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=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)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}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!j(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return zt(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}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,n,r=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:r};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,n)}}class zc extends Ua{constructor(t,e,i,s,n){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.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 r=t.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.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)}}function qc(a,t){const e=Object.getPrototypeOf(a);if(e){const i=Object.getOwnPropertyDescriptor(e,t);return i||qc(e,t)}}function aC(a,t){const e=qc(a,t);e&&(e.enumerable=!0,Object.defineProperty(a,t,e))}const vn=Math.pow(2,32)-1,oC=[].push,Xc={video:1,audio:2,id3:3,text:4};function Ht(a){return String.fromCharCode.apply(null,a)}function Wc(a,t){const e=a[t]<<8|a[t+1];return e<0?65536+e:e}function nt(a,t){const e=jc(a,t);return e<0?4294967296+e:e}function Tl(a,t){let e=nt(a,t);return e*=Math.pow(2,32),e+=nt(a,t+4),e}function jc(a,t){return a[t]<<24|a[t+1]<<16|a[t+2]<<8|a[t+3]}function Er(a,t,e){a[t]=e>>24,a[t+1]=e>>16&255,a[t+2]=e>>8&255,a[t+3]=e&255}function lC(a){const t=a.byteLength;for(let e=0;e<t;){const i=nt(a,e);if(i>8&&a[e+4]===109&&a[e+5]===111&&a[e+6]===111&&a[e+7]===102)return!0;e=i>1?e+i:t}return!1}function ct(a,t){const e=[];if(!t.length)return e;const i=a.byteLength;for(let s=0;s<i;){const n=nt(a,s),r=Ht(a.subarray(s+4,s+8)),o=n>1?s+n:i;if(r===t[0])if(t.length===1)e.push(a.subarray(s+8,o));else{const l=ct(a.subarray(s+8,o),t.slice(1));l.length&&oC.apply(e,l)}s=o}return e}function hC(a){const t=[],e=a[0];let i=8;const s=nt(a,i);i+=4;let n=0,r=0;e===0?(n=nt(a,i),r=nt(a,i+4),i+=8):(n=Tl(a,i),r=Tl(a,i+8),i+=16),i+=2;let o=a.length+r;const l=Wc(a,i);i+=2;for(let h=0;h<l;h++){let u=i;const c=nt(a,u);u+=4;const d=c&2147483647;if((c&2147483648)>>>31===1)return Et.warn("SIDX has hierarchical references (not supported)"),null;const f=nt(a,u);u+=4,t.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:n,timescale:s,version:e,referencesCount:l,references:t}}function Zc(a){const t=[],e=ct(a,["moov","trak"]);for(let s=0;s<e.length;s++){const n=e[s],r=ct(n,["tkhd"])[0];if(r){let o=r[0];const l=nt(r,o===0?12:20),h=ct(n,["mdia","mdhd"])[0];if(h){o=h[0];const u=nt(h,o===0?12:20),c=ct(n,["mdia","hdlr"])[0];if(c){const d=Ht(c.subarray(8,12)),A={soun:_t.AUDIO,vide:_t.VIDEO}[d],f=ct(n,["mdia","minf","stbl","stsd"])[0],g=cC(f);A?(t[l]={timescale:u,type:A,stsd:g},t[A]=St({timescale:u,id:l},g)):t[l]={timescale:u,type:d,stsd:g}}}}}return ct(a,["moov","mvex","trex"]).forEach(s=>{const n=nt(s,4),r=t[n];r&&(r.default={duration:nt(s,12),flags:nt(s,20)})}),t}function cC(a){const t=a.subarray(8),e=t.subarray(86),i=Ht(t.subarray(4,8));let s=i,n;const r=i==="enca"||i==="encv";if(r){const h=ct(t,[i])[0].subarray(i==="enca"?28:78);ct(h,["sinf"]).forEach(c=>{const d=ct(c,["schm"])[0];if(d){const A=Ht(d.subarray(4,8));if(A==="cbcs"||A==="cenc"){const f=ct(c,["frma"])[0];f&&(s=Ht(f))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const l=ct(e,["avcC"])[0];l&&l.length>3&&(s+="."+Js(l[1])+Js(l[2])+Js(l[3]),n=Vs(o==="avc1"?"dva1":"dvav",e));break}case"mp4a":{const l=ct(t,[i])[0],h=ct(l.subarray(28),["esds"])[0];if(h&&h.length>7){let u=4;if(h[u++]!==3)break;u=Ir(h,u),u+=2;const c=h[u++];if(c&128&&(u+=2),c&64&&(u+=h[u++]),h[u++]!==4)break;u=Ir(h,u);const d=h[u++];if(d===64)s+="."+Js(d);else break;if(u+=12,h[u++]!==5)break;u=Ir(h,u);const A=h[u++];let f=(A&248)>>3;f===31&&(f+=1+((A&7)<<3)+((h[u]&224)>>5)),s+="."+f}break}case"hvc1":case"hev1":{const l=ct(e,["hvcC"])[0];if(l&&l.length>12){const h=l[1],u=["","A","B","C"][h>>6],c=h&31,d=nt(l,2),A=(h&32)>>5?"H":"L",f=l[12],g=l.subarray(6,12);s+="."+u+c,s+="."+d.toString(16).toUpperCase(),s+="."+A+f;let m="";for(let p=g.length;p--;){const C=g[p];(C||m)&&(m="."+C.toString(16).toUpperCase()+m)}s+=m}n=Vs(o=="hev1"?"dvhe":"dvh1",e);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Vs(s,e)||s;break}case"vp09":{const l=ct(e,["vpcC"])[0];if(l&&l.length>6){const h=l[4],u=l[5],c=l[6]>>4&15;s+="."+De(h)+"."+De(u)+"."+De(c)}break}case"av01":{const l=ct(e,["av1C"])[0];if(l&&l.length>2){const h=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,A=(l[2]&32)>>5,f=h===2&&d?A?12:10:d?10:8,g=(l[2]&16)>>4,m=(l[2]&8)>>3,p=(l[2]&4)>>2,C=l[2]&3;s+="."+h+"."+De(u)+c+"."+De(f)+"."+g+"."+m+p+C+"."+De(1)+"."+De(1)+"."+De(1)+"."+0,n=Vs("dav1",e)}break}}return{codec:s,encrypted:r,supplemental:n}}function Vs(a,t){const e=ct(t,["dvvC"]),i=e.length?e[0]:ct(t,["dvcC"])[0];if(i){const s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return a+"."+De(s)+"."+De(n)}}function Ir(a,t){const e=t+5;for(;a[t++]&128&&t<e;);return t}function Js(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function De(a){return(a<10?"0":"")+a}function uC(a,t){if(!a||!t)return a;const e=t.keyId;return e&&t.isCommonEncryption&&ct(a,["moov","trak"]).forEach(s=>{const r=ct(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=ct(r,["enca"]);const l=o.length>0;l||(o=ct(r,["encv"])),o.forEach(h=>{const u=l?h.subarray(28):h.subarray(78);ct(u,["sinf"]).forEach(d=>{const A=tu(d);if(A){const f=A.subarray(8,24);f.some(g=>g!==0)||(Et.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Le.hexDump(f)} -> ${Le.hexDump(e)}`),A.set(e,8))}})})}),a}function tu(a){const t=ct(a,["schm"])[0];if(t){const e=Ht(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return ct(a,["schi","tenc"])[0]}return null}function dC(a,t){return ct(t,["moof","traf"]).reduce((e,i)=>{const s=ct(i,["tfdt"])[0],n=s[0],r=ct(i,["tfhd"]).reduce((o,l)=>{const h=nt(l,4),u=a[h];if(u){let c=nt(s,4);if(n===1){if(c===vn)return Et.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;c*=vn+1,c+=nt(s,8)}const d=u.timescale||9e4,A=c/d;if(j(A)&&(o===null||A<o))return A}return o},null);return r!==null&&j(r)&&(e===null||r<e)?r:e},null)}function AC(a,t){let e=0,i=0,s=0;const n=ct(a,["moof","traf"]);for(let r=0;r<n.length;r++){const o=n[r],l=ct(o,["tfhd"])[0],h=nt(l,4),u=t[h];if(!u)continue;const c=u.default,d=nt(l,0)|(c==null?void 0:c.flags);let A=c==null?void 0:c.duration;d&8&&(d&2?A=nt(l,12):A=nt(l,8));const f=u.timescale||9e4,g=ct(o,["trun"]);for(let m=0;m<g.length;m++){if(e=fC(g[m]),!e&&A){const p=nt(g[m],4);e=A*p}u.type===_t.VIDEO?i+=e/f:u.type===_t.AUDIO&&(s+=e/f)}}if(i===0&&s===0){let r=1/0,o=0,l=0;const h=ct(a,["sidx"]);for(let u=0;u<h.length;u++){const c=hC(h[u]);if(c!=null&&c.references){r=Math.min(r,c.earliestPresentationTime/c.timescale);const d=c.references.reduce((A,f)=>A+f.info.duration||0,0);o=Math.max(o,d+c.earliestPresentationTime/c.timescale),l=o-r}}if(l&&j(l))return l}return i||s}function fC(a){const t=nt(a,0);let e=8;t&1&&(e+=4),t&4&&(e+=4);let i=0;const s=nt(a,4);for(let n=0;n<s;n++){if(t&256){const r=nt(a,e);i+=r,e+=4}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4)}return i}function gC(a,t,e){ct(t,["moof","traf"]).forEach(i=>{ct(i,["tfhd"]).forEach(s=>{const n=nt(s,4),r=a[n];if(!r)return;const o=r.timescale||9e4;ct(i,["tfdt"]).forEach(l=>{const h=l[0],u=e*o;if(u){let c=nt(l,4);if(h===0)c-=u,c=Math.max(c,0),Er(l,4,c);else{c*=Math.pow(2,32),c+=nt(l,8),c-=u,c=Math.max(c,0);const d=Math.floor(c/(vn+1)),A=Math.floor(c%(vn+1));Er(l,4,d),Er(l,8,A)}}})})})}function mC(a){const t={valid:null,remainder:null},e=ct(a,["moof"]);if(e.length<2)return t.remainder=a,t;const i=e[e.length-1];return t.valid=a.slice(0,i.byteOffset-8),t.remainder=a.slice(i.byteOffset-8),t}function fe(a,t){const e=new Uint8Array(a.length+t.length);return e.set(a),e.set(t,a.length),e}function _l(a,t){const e=[],i=t.samples,s=t.timescale,n=t.id;let r=!1;return ct(i,["moof"]).map(l=>{const h=l.byteOffset-8;ct(l,["traf"]).map(c=>{const d=ct(c,["tfdt"]).map(A=>{const f=A[0];let g=nt(A,4);return f===1&&(g*=Math.pow(2,32),g+=nt(A,8)),g/s})[0];return d!==void 0&&(a=d),ct(c,["tfhd"]).map(A=>{const f=nt(A,4),g=nt(A,0)&16777215,m=(g&1)!==0,p=(g&2)!==0,C=(g&8)!==0;let E=0;const y=(g&16)!==0;let v=0;const T=(g&32)!==0;let B=8;f===n&&(m&&(B+=8),p&&(B+=4),C&&(E=nt(A,B),B+=4),y&&(v=nt(A,B),B+=4),T&&(B+=4),t.type==="video"&&(r=Un(t.codec)),ct(c,["trun"]).map(_=>{const D=_[0],x=nt(_,0)&16777215,M=(x&1)!==0;let k=0;const X=(x&4)!==0,W=(x&256)!==0;let H=0;const Y=(x&512)!==0;let z=0;const J=(x&1024)!==0,U=(x&2048)!==0;let F=0;const N=nt(_,4);let K=8;M&&(k=nt(_,K),K+=4),X&&(K+=4);let $=k+h;for(let R=0;R<N;R++){if(W?(H=nt(_,K),K+=4):H=E,Y?(z=nt(_,K),K+=4):z=v,J&&(K+=4),U&&(D===0?F=nt(_,K):F=jc(_,K),K+=4),t.type===_t.VIDEO){let tt=0;for(;tt<z;){const it=nt(i,$);if($+=4,pC(r,i[$])){const lt=i.subarray($,$+it);Ga(lt,r?2:1,a+F/s,e)}$+=it,tt+=it+4}}a+=H/s}}))})})}),e}function Un(a){if(!a)return!1;const t=a.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function pC(a,t){if(a){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function Ga(a,t,e,i){const s=eu(a);let n=0;n+=t;let r=0,o=0,l=0;for(;n<s.length;){r=0;do{if(n>=s.length)break;l=s[n++],r+=l}while(l===255);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(l===255);const h=s.length-n;let u=n;if(o<h)n+=o;else if(o>h){Et.error(`Malformed SEI payload. ${o} is too small, only ${h} bytes left to parse.`);break}if(r===4){if(s[u++]===181){const d=Wc(s,u);if(u+=2,d===49){const A=nt(s,u);if(u+=4,A===1195456820){const f=s[u++];if(f===3){const g=s[u++],m=31&g,p=64&g,C=p?2+m*3:0,E=new Uint8Array(C);if(p){E[0]=g;for(let y=1;y<C;y++)E[y]=s[u++]}i.push({type:f,payloadType:r,pts:e,bytes:E})}}}}}else if(r===5&&o>16){const c=[];for(let f=0;f<16;f++){const g=s[u++].toString(16);c.push(g.length==1?"0"+g:g),(f===3||f===5||f===7||f===9)&&c.push("-")}const d=o-16,A=new Uint8Array(d);for(let f=0;f<d;f++)A[f]=s[u++];i.push({payloadType:r,pts:e,uuid:c.join(""),userData:ae(A),userDataBytes:A})}}}function eu(a){const t=a.byteLength,e=[];let i=1;for(;i<t-2;)a[i]===0&&a[i+1]===0&&a[i+2]===3?(e.push(i+2),i+=2):i++;if(e.length===0)return a;const s=t-e.length,n=new Uint8Array(s);let r=0;for(i=0;i<s;r++,i++)r===e[0]&&(r++,e.shift()),n[i]=a[r];return n}function EC(a){const t=a[0];let e="",i="",s=0,n=0,r=0,o=0,l=0,h=0;if(t===0){for(;Ht(a.subarray(h,h+1))!=="\0";)e+=Ht(a.subarray(h,h+1)),h+=1;for(e+=Ht(a.subarray(h,h+1)),h+=1;Ht(a.subarray(h,h+1))!=="\0";)i+=Ht(a.subarray(h,h+1)),h+=1;i+=Ht(a.subarray(h,h+1)),h+=1,s=nt(a,12),n=nt(a,16),o=nt(a,20),l=nt(a,24),h=28}else if(t===1){h+=4,s=nt(a,h),h+=4;const c=nt(a,h);h+=4;const d=nt(a,h);for(h+=4,r=2**32*c+d,zI(r)||(r=Number.MAX_SAFE_INTEGER,Et.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=nt(a,h),h+=4,l=nt(a,h),h+=4;Ht(a.subarray(h,h+1))!=="\0";)e+=Ht(a.subarray(h,h+1)),h+=1;for(e+=Ht(a.subarray(h,h+1)),h+=1;Ht(a.subarray(h,h+1))!=="\0";)i+=Ht(a.subarray(h,h+1)),h+=1;i+=Ht(a.subarray(h,h+1)),h+=1}const u=a.subarray(h,a.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:r,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function IC(a,...t){const e=t.length;let i=8,s=e;for(;s--;)i+=t[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(a,4),s=0,i=8;s<e;s++)n.set(t[s],i),i+=t[s].byteLength;return n}function CC(a,t,e){if(a.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const r=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(r.buffer).setUint32(0,e.byteLength,!1),IC([112,115,115,104],new Uint8Array([i,0,0,0]),a,n,s,r,e||new Uint8Array)}function yC(a){const t=[];if(a instanceof ArrayBuffer){const e=a.byteLength;let i=0;for(;i+32<e;){const s=new DataView(a,i),n=vC(s);t.push(n),i+=n.size}}return t}function vC(a){const t=a.getUint32(0),e=a.byteOffset,i=a.byteLength;if(i<t)return{offset:e,size:i};if(a.getUint32(4)!==1886614376)return{offset:e,size:t};const n=a.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:e,size:t};const r=a.buffer,o=Le.hexDump(new Uint8Array(r,e+12,16)),l=a.getUint32(28);let h=null,u=null;if(n===0){if(t-32<l||l<22)return{offset:e,size:t};u=new Uint8Array(r,e+32,l)}else if(n===1){if(!l||i<e+32+l*16+16)return{offset:e,size:t};h=[];for(let c=0;c<l;c++)h.push(new Uint8Array(r,e+32+c*16,16))}return{version:n,systemId:o,kids:h,data:u,offset:e,size:t}}const iu=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ni={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,dav1:.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 su(a,t){const e=Ni[t];return!!e&&!!e[a.slice(0,4)]}function sa(a,t,e=!0){return!a.split(",").some(i=>!nu(i,t,e))}function nu(a,t,e=!0){var i;const s=Je(e);return(i=s==null?void 0:s.isTypeSupported(Bs(a,t)))!=null?i:!1}function Bs(a,t){return`${t}/mp4;codecs=${a}`}function xl(a){if(a){const t=a.substring(0,4);return Ni.video[t]}return 2}function Bn(a){const t=iu();return a.split(",").reduce((e,i)=>{const n=t&&Un(i)?9:Ni.video[i];return n?(n*2+e)/(e?3:2):(Ni.audio[i]+e)/(e?2:1)},0)}const Cr={};function BC(a,t=!0){if(Cr[a])return Cr[a];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let s=0;s<e.length;s++){var i;if(nu(e[s],"audio",t))return Cr[a]=e[s],e[s];if(e[s]==="mp3"&&(i=Je(t))!=null&&i.isTypeSupported("audio/mpeg"))return""}return a}const SC=/flac|opus|mp4a\.40\.34/i;function Sn(a,t=!0){return a.replace(SC,e=>BC(e.toLowerCase(),t))}function TC(a,t){const e=[];if(a){const i=a.split(",");for(let s=0;s<i.length;s++)su(i[s],"video")||e.push(i[s])}return t&&e.push(t),e.join(",")}function un(a,t){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1))return a;if(t){const e=t.split(",");if(e.length>1){if(a){for(let i=e.length;i--;)if(e[i].substring(0,4)===a.substring(0,4))return e[i]}return e[0]}}return t||a}function _C(a){const t=a.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(",")}function xC(a){if(a.startsWith("av01.")){const t=a.split("."),e=["0","111","01","01","01","0"];for(let i=t.length;i>4&&i<10;i++)t[i]=e[i-4];return t.join(".")}return a}function Dl(a){const t=Je(a)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ru(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const au={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ou(a,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:a}}const Rl={};function DC(a,t,e,i,s,n){const r=a.audioCodec?a.audioGroups:null,o=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let u=null;if(r!=null&&r.length)try{r.length===1&&r[0]?u=t.groups[r[0]].channels:u=r.reduce((c,d)=>{if(d){const A=t.groups[d];if(!A)throw new Error(`Audio track group ${d} not found`);Object.keys(A.channels).forEach(f=>{c[f]=(c[f]||0)+A.channels[f]})}return c},{2:0})}catch{return!0}return a.videoCodec!==void 0&&(a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(i,30)||a.videoRange!=="SDR"&&a.videoRange!==e||a.bitrate>Math.max(s,8e6))||!!u&&j(h)&&Object.keys(u).some(c=>parseInt(c)>h)}function lu(a,t,e){const i=a.videoCodec,s=a.audioCodec;if(!i&&!s||!e)return Promise.resolve(au);const n=[];if(i){const r={width:a.width,height:a.height,bitrate:Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)),framerate:a.frameRate||30},o=a.videoRange;o!=="SDR"&&(r.transferFunction=o.toLowerCase());const l=i.split(","),h=navigator.userAgent;if(l.some(u=>Un(u))&&iu())return Promise.resolve(ou(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${h})`),n));n.push.apply(n,l.map(u=>({type:"media-source",video:St(St({},r),{},{contentType:Bs(xC(u),"video")})})))}return s&&a.audioGroups&&a.audioGroups.forEach(r=>{var o;r&&((o=t.groups[r])==null||o.tracks.forEach(l=>{if(l.groupId===r){const h=l.channels||"",u=parseFloat(h);j(u)&&u>2&&n.push.apply(n,s.split(",").map(c=>({type:"media-source",audio:{contentType:Bs(c,"audio"),channels:""+u}})))}}))}),Promise.all(n.map(r=>{const o=RC(r);return Rl[o]||(Rl[o]=e.decodingInfo(r))})).then(r=>({supported:!r.some(o=>!o.supported),configurations:n,decodingInfoResults:r})).catch(r=>({supported:!1,configurations:n,decodingInfoResults:[],error:r}))}function RC(a){const{audio:t,video:e}=a,i=e||t;if(i){const s=ru(i.contentType);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""}const na=["NONE","TYPE-0","TYPE-1",null];function LC(a){return na.indexOf(a)>-1}const Tn=["SDR","PQ","HLG"];function bC(a){return!!a&&Tn.indexOf(a)>-1}var Is={No:"",Yes:"YES",v2:"v2"};function Ll(a){const{canSkipUntil:t,canSkipDateRanges:e,age:i}=a,s=i<t/2;return t&&s?e?Is.v2:Is.Yes:Is.No}class ra{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 Hi{constructor(t){if(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.supplemental=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(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=(e=t.supplemental)==null?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}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 bl(this._audioGroups,t)}hasSubtitleGroup(t){return bl(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 bl(a,t){return!t||!a?!1:a.indexOf(t)!==-1}function wC(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(a.media!==t.media)return a.matches===!0}return!1}function PC(a,t){let e=!1,i=[];if(a&&(e=a!=="SDR",i=[a]),t){i=t.allowedVideoRanges||Tn.slice(0);const s=i.join("")!=="SDR"&&!t.videoCodec;e=t.preferHDR!==void 0?t.preferHDR:s&&wC(),e||(i=["SDR"])}return{preferHDR:e,allowedVideoRanges:i}}const MC=a=>{const t=new WeakSet;return(e,i)=>{if(a&&(i=a(e,i)),typeof i=="object"&&i!==null){if(t.has(i))return;t.add(i)}return i}},Mt=(a,t)=>JSON.stringify(a,MC(t));function FC(a,t,e,i,s){const n=Object.keys(a),r=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=s==null?void 0:s.videoCodec,h=r&&parseInt(r)===2;let u=!1,c=!1,d=1/0,A=1/0,f=1/0,g=1/0,m=0,p=[];const{preferHDR:C,allowedVideoRanges:E}=PC(t,s);for(let _=n.length;_--;){const D=a[n[_]];u||(u=D.channels[2]>0),d=Math.min(d,D.minHeight),A=Math.min(A,D.minFramerate),f=Math.min(f,D.minBitrate),E.filter(M=>D.videoRanges[M]>0).length>0&&(c=!0)}d=j(d)?d:0,A=j(A)?A:0;const y=Math.max(1080,d),v=Math.max(30,A);f=j(f)?f:e,e=Math.max(f,e),c||(t=void 0);const T=n.length>1;return{codecSet:n.reduce((_,D)=>{const x=a[D];if(D===_)return _;if(p=c?E.filter(M=>x.videoRanges[M]>0):[],T){if(x.minBitrate>e)return xe(D,`min bitrate of ${x.minBitrate} > current estimate of ${e}`),_;if(!x.hasDefaultAudio)return xe(D,"no renditions with default or auto-select sound found"),_;if(o&&D.indexOf(o.substring(0,4))%5!==0)return xe(D,`audio codec preference "${o}" not found`),_;if(r&&!h){if(!x.channels[r])return xe(D,`no renditions with ${r} channel sound found (channels options: ${Object.keys(x.channels)})`),_}else if((!o||h)&&u&&x.channels[2]===0)return xe(D,"no renditions with stereo sound found"),_;if(x.minHeight>y)return xe(D,`min resolution of ${x.minHeight} > maximum of ${y}`),_;if(x.minFramerate>v)return xe(D,`min framerate of ${x.minFramerate} > maximum of ${v}`),_;if(!p.some(M=>x.videoRanges[M]>0))return xe(D,`no variants with VIDEO-RANGE of ${Mt(p)} found`),_;if(l&&D.indexOf(l.substring(0,4))%5!==0)return xe(D,`video codec preference "${l}" not found`),_;if(x.maxScore<m)return xe(D,`max score of ${x.maxScore} < selected max of ${m}`),_}return _&&(Bn(D)>=Bn(_)||x.fragmentError>a[_].fragmentError)?_:(g=x.minIndex,m=x.maxScore,D)},void 0),videoRanges:p,preferHDR:C,minFramerate:A,minBitrate:f,minIndex:g}}function xe(a,t){Et.log(`[abr] start candidates with "${a}" ignored because ${t}`)}function hu(a){return a.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 kC(a,t,e,i){return a.slice(e,i+1).reduce((s,n,r)=>{if(!n.codecSet)return s;const o=n.audioGroups;let l=s[n.codecSet];l||(s[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const h=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,h),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,r),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const c=t.groups[u];c&&(l.hasDefaultAudio=l.hasDefaultAudio||t.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(c.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+c.channels[d]}))}),s},{})}function wl(a){if(!a)return a;const{lang:t,assocLang:e,characteristics:i,channels:s,audioCodec:n}=a;return{lang:t,assocLang:e,characteristics:i,channels:s,audioCodec:n}}function we(a,t,e){if("attrs"in a){const i=t.indexOf(a);if(i!==-1)return i}for(let i=0;i<t.length;i++){const s=t[i];if(mi(a,s,e))return i}return-1}function mi(a,t,e){const{groupId:i,name:s,lang:n,assocLang:r,default:o}=a,l=a.forced;return(i===void 0||t.groupId===i)&&(s===void 0||t.name===s)&&(n===void 0||OC(n,t.lang))&&(n===void 0||t.assocLang===r)&&(o===void 0||t.default===o)&&(l===void 0||t.forced===l)&&(!("characteristics"in a)||QC(a.characteristics||"",t.characteristics))&&(e===void 0||e(a,t))}function OC(a,t="--"){return a.length===t.length?a===t:a.startsWith(t)||t.startsWith(a)}function QC(a,t=""){const e=a.split(","),i=t.split(",");return e.length===i.length&&!e.some(s=>i.indexOf(s)===-1)}function gi(a,t){const{audioCodec:e,channels:i}=a;return(e===void 0||(t.audioCodec||"").substring(0,4)===e.substring(0,4))&&(i===void 0||i===(t.channels||"2"))}function UC(a,t,e,i,s){const n=t[i],o=t.reduce((d,A,f)=>{const g=A.uri;return(d[g]||(d[g]=[])).push(f),d},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,h=n.frameRate,u=n.codecSet.substring(0,4),c=Pl(t,i,d=>{if(d.videoRange!==l||d.frameRate!==h||d.codecSet.substring(0,4)!==u)return!1;const A=d.audioGroups,f=e.filter(g=>!A||A.indexOf(g.groupId)!==-1);return we(a,f,s)>-1});return c>-1?c:Pl(t,i,d=>{const A=d.audioGroups,f=e.filter(g=>!A||A.indexOf(g.groupId)!==-1);return we(a,f,s)>-1})}function Pl(a,t,e){for(let i=t;i>-1;i--)if(e(a[i]))return i;for(let i=t+1;i<a.length;i++)if(e(a[i]))return i;return-1}function _n(a,t){var e;return!!a&&a!==((e=t.loadLevelObj)==null?void 0:e.uri)}class cu extends qe{constructor(t){super("abr",t.logger),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.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var i;const{fragCurrent:s,partCurrent:n,hls:r}=this,{autoLevelEnabled:o,media:l}=r;if(!s||!l)return;const h=performance.now(),u=n?n.stats:s.stats,c=n?n.duration:s.duration,d=h-u.loading.start,A=r.minAutoLevel,f=s.level,g=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=A){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=g>-1&&g!==f,p=!!e||m;if(!p&&(l.paused||!l.playbackRate||!l.readyState))return;const C=r.mainForwardBufferInfo;if(!p&&C===null)return;const E=this.bwEstimator.getEstimateTTFB(),y=Math.abs(l.playbackRate);if(d<=Math.max(E,1e3*(c/(y*2))))return;const v=C?C.len/y:0,T=u.loading.first?u.loading.first-u.loading.start:-1,B=u.loaded&&T>-1,_=this.getBwEstimate(),D=r.levels,x=D[f],M=Math.max(u.loaded,Math.round(c*(s.bitrate||x.averageBitrate)/8));let k=B?d-T:d;k<1&&B&&(k=Math.min(d,u.loaded*8/_));const X=B?u.loaded*1e3/k:0,W=E/1e3,H=X?(M-u.loaded)/X:M*8/_+W;if(H<=v)return;const Y=X?X*8:_,z=((i=(e==null?void 0:e.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,J=this.hls.config.abrBandWidthUpFactor;let U=Number.POSITIVE_INFINITY,F;for(F=f-1;F>A;F--){const R=D[F].maxBitrate,tt=!D[F].details||z;if(U=this.getTimeToLoadFrag(W,Y,c*R,tt),U<Math.min(v,c+W))break}if(U>=H||U>c*10)return;B?this.bwEstimator.sample(d-Math.min(E,T),u.loaded):this.bwEstimator.sampleTTFB(d);const N=D[F].maxBitrate;this.getBwEstimate()*J>N&&this.resetEstimator(N);const K=this.findBestLevel(N,A,F,0,v,1,1);K>-1&&(F=K),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${f} is loading too slowly;
|
|
11
|
+
Fragment duration: ${s.duration.toFixed(3)}
|
|
12
|
+
Time to underbuffer: ${v.toFixed(3)} s
|
|
13
|
+
Estimated load time for current fragment: ${H.toFixed(3)} s
|
|
14
|
+
Estimated load time for down switch fragment: ${U.toFixed(3)} s
|
|
15
|
+
TTFB estimate: ${T|0} ms
|
|
16
|
+
Current BW estimate: ${j(_)?_|0:"Unknown"} bps
|
|
17
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
18
|
+
Switching to level ${F} @ ${N|0} bps`),r.nextLoadLevel=r.nextAutoLevel=F,this.clearTimer();const $=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===F&&F>0){const R=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${F>0?"and switching down":""}
|
|
19
|
+
Fragment duration: ${s.duration.toFixed(3)} s
|
|
20
|
+
Time to underbuffer: ${R.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,F>A){let tt=this.findBestLevel(this.hls.levels[A].bitrate,A,F,0,R,1,1);tt===-1&&(tt=A),this.hls.nextLoadLevel=this.hls.nextAutoLevel=tt,this.resetEstimator(this.hls.levels[tt].bitrate)}}};m||H>U*2?$():this.timer=self.setInterval($,U*1e3),r.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.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 XI(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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case b.FRAG_LOAD_TIMEOUT:{const i=e.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const r=performance.now(),o=n?n.stats:i.stats,l=r-o.loading.start,h=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&h>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,h),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,i,s){const n=t+i/e,r=s?t+this.lastLevelLoadSec:0;return n+r}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,n=s.end-s.first;j(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===Z.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 n=i?i.duration:e.duration,r=this.hls.levels[e.level],o=(r.loaded?r.loaded.bytes:0)+s.loaded,l=(r.loaded?r.loaded.duration:0)+n;r.loaded={bytes:o,duration:l},r.realBitrate=Math.round(8*o/l)}if(e.bitrateTest){const n={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(I.FRAG_BUFFERED,n),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const r=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=r/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Z.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,n=this.findBestLevel(i,e,t,0,s,1,1);if(n>-1)return n;const r=this.hls.firstLevel,o=Math.min(Math.max(r,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${r} 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 n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const r=this.hls.levels;if(r.length>Math.max(t,n)&&r[t].loadError<=r[n].loadError)return t}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:r}=i,o=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),h=this.getStarvationDelay();let u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(h){const m=this.findBestLevel(l,r,s,h,0,u,c);if(m>=0)return this.rebufferNotice=-1,m}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!h){const m=this.bitrateTestDelay;m&&(d=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=c=1)}const A=this.findBestLevel(l,r,s,h,d,u,c);if(this.rebufferNotice!==A&&(this.rebufferNotice=A,this.info(`${h?"rebuffering expected":"buffer is empty"}, optimal quality level ${A}`)),A>-1)return A;const f=i.levels[r],g=i.loadLevelObj;return g&&(f==null?void 0:f.bitrate)<g.bitrate?r: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,n,r,o){var l;const h=s+n,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:A}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(f.length===1)return 0;const C=f[c],E=!!((l=this.hls.latestLevelDetails)!=null&&l.live),y=m===-1||u===-1;let v,T="SDR",B=(C==null?void 0:C.frameRate)||0;const{audioPreference:_,videoPreference:D}=p,x=this.audioTracksByGroup||(this.audioTracksByGroup=hu(g));let M=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;const Y=this.codecTiers||(this.codecTiers=kC(f,x,e,i)),z=FC(Y,T,t,_,D),{codecSet:J,videoRanges:U,minFramerate:F,minBitrate:N,minIndex:K,preferHDR:$}=z;M=K,v=J,T=$?U[U.length-1]:U[0],B=F,t=Math.max(t,N),this.log(`picked start tier ${Mt(z)}`)}else v=C==null?void 0:C.codecSet,T=C==null?void 0:C.videoRange;const k=A?A.duration:d?d.duration:0,X=this.bwEstimator.getEstimateTTFB()/1e3,W=[];for(let Y=i;Y>=e;Y--){var H;const z=f[Y],J=Y>c;if(!z)continue;if(p.useMediaCapabilities&&!z.supportedResult&&!z.supportedPromise){const tt=navigator.mediaCapabilities;typeof(tt==null?void 0:tt.decodingInfo)=="function"&&(DC(z,x,T,B,t,_)||Un(z.videoCodec))?(z.supportedPromise=lu(z,x,tt),z.supportedPromise.then(it=>{if(!this.hls)return;z.supportedResult=it;const lt=this.hls.levels,Dt=lt.indexOf(z);it.error?this.warn(`MediaCapabilities decodingInfo error: "${it.error}" for level ${Dt} ${Mt(it)}`):it.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Dt} ${Mt(it)}`),Dt>-1&<.length>1&&(this.log(`Removing unsupported level ${Dt}`),this.hls.removeLevel(Dt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):z.supportedResult=au}if((v&&z.codecSet!==v||T&&z.videoRange!==T||J&&B>z.frameRate||!J&&B>0&&B<z.frameRate||z.supportedResult&&!((H=z.supportedResult.decodingInfoResults)!=null&&H[0].smooth))&&(!y||Y!==M)){W.push(Y);continue}const U=z.details,F=(A?U==null?void 0:U.partTarget:U==null?void 0:U.averagetargetduration)||k;let N;J?N=o*t:N=r*t;const K=k&&s>=k*2&&n===0?z.averageBitrate:z.maxBitrate,$=this.getTimeToLoadFrag(X,N,K*F,U===void 0);if(N>=K&&(Y===u||z.loadError===0&&z.fragmentError===0)&&($<=X||!j($)||E&&!this.bitrateTestDelay||$<h)){const tt=this.forcedAutoLevel;return Y!==m&&(tt===-1||tt!==m)&&(W.length&&this.trace(`Skipped level(s) ${W.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[W[0]].codecs}" ${f[W[0]].videoRange}; not compatible with "${v}" ${T}`),this.info(`switch candidate:${c}->${Y} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-K)} ttfb:${X.toFixed(1)} avgDuration:${F.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${$.toFixed(1)} firstSelection:${y} codecSet:${z.codecSet} videoRange:${z.videoRange} hls.loadLevel:${m}`)),y&&(this.firstSelection=Y),Y}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}}const Na={search:function(a,t){let e=0,i=a.length-1,s=null,n=null;for(;e<=i;){s=(e+i)/2|0,n=a[s];const r=t(n);if(r>0)e=s+1;else if(r<0)i=s-1;else return n}return null}};function GC(a,t,e){if(t===null||!Array.isArray(a)||!a.length||!j(t))return null;const i=a[0].programDateTime;if(t<(i||0))return null;const s=a[a.length-1].endProgramDateTime;if(t>=(s||0))return null;e=e||0;for(let n=0;n<a.length;++n){const r=a[n];if(HC(t,e,r))return r}return null}function Ei(a,t,e=0,i=0,s=.005){let n=null;if(a){n=t[1+a.sn-t[0].sn]||null;const o=a.endDTS-e;o>0&&o<15e-7&&(e+=15e-7),n&&a.level!==n.level&&n.end<=a.end&&(n=t[2+a.sn-t[0].sn]||null)}else e===0&&t[0].start===0&&(n=t[0]);if(n&&((!a||a.level===n.level)&&Ml(e,i,n)===0||NC(n,a,Math.min(s,i))))return n;const r=Na.search(t,Ml.bind(null,e,i));return r&&(r!==a||!n)?r:n}function NC(a,t,e){if(t&&t.start===0&&t.level<a.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),e);return a.start<=i}return!1}function Ml(a=0,t=0,e){if(e.start<=a&&e.start+e.duration>a)return 0;const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-i<=a?1:e.start-i>a&&e.start?-1:0}function HC(a,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>a}function uu(a,t){return Na.search(a,e=>e.cc<t?1:e.cc>t?-1:0)}function KC(a,t,e){if(a&&a.startCC<=t&&a.endCC>=t){const i=e.start,s=e.end;let n=a.fragments;if(!e.relurl){const{fragmentHint:r}=a;r&&(n=n.concat(r))}return Na.search(n,r=>r.cc<t||r.end<=i?1:r.cc>t||r.start>=s?-1:0)}return null}function xn(a){switch(a.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Fl(a,t){const e=xn(t);return a.default[`${e?"timeout":"error"}Retry`]}function Ha(a,t){const e=a.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*a.retryDelayMs,a.maxRetryDelayMs)}function kl(a){return St(St({},a),{errorRetry:null,timeoutRetry:null})}function Dn(a,t,e,i){if(!a)return!1;const s=i==null?void 0:i.code,n=t<a.maxNumRetry&&($C(s)||!!e);return a.shouldRetry?a.shouldRetry(a,t,e,i,n):n}function $C(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}var Jt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},de={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class du extends qe{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,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)===Z.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,n=e.context;switch(e.details){case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case b.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction=Ss();return}case b.FRAG_GAP:case b.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Jt.SendAlternateToPenaltyBox;return}case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:{var r,o;const h=e.parent===Z.MAIN?e.level:s.loadLevel;e.details===b.LEVEL_EMPTY_ERROR&&((r=e.context)!=null&&(o=r.levelDetails)!=null&&o.live)?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,h):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,h))}return;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level));return;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const h=s.loadLevelObj;if(h&&(n.type===gt.AUDIO_TRACK&&h.hasAudioGroup(n.groupId)||n.type===gt.SUBTITLE_TRACK&&h.hasSubtitleGroup(n.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Jt.SendAlternateToPenaltyBox,e.errorAction.flags=de.MoveAllAlternatesMatchingHost;return}}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const h=s.loadLevelObj,u=h==null?void 0:h.attrs["HDCP-LEVEL"];u?e.errorAction={action:Jt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(e)}return;case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:case b.BUFFER_APPEND_ERROR:if(!e.errorAction){var l;e.errorAction=this.getLevelSwitchAction(e,(l=e.level)!=null?l:s.loadLevel)}return;case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:e.errorAction=Ss();return}e.type===et.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=Fl(i.config.playlistLoadPolicy,t),n=this.playlistError++;if(Dn(s,n,xn(t),t.response))return{action:Jt.RetryRequest,flags:de.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(t,e);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:r}=e.config,o=Fl(t.details.startsWith("key")?r:n,t),l=e.levels.reduce((u,c)=>u+c.fragmentError,0);if(s&&(t.details!==b.FRAG_GAP&&s.fragmentError++,Dn(o,l,xn(t),t.response)))return{action:Jt.RetryRequest,flags:de.None,retryConfig:o,retryCount:l};const h=this.getLevelSwitchAction(t,i);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var n,r;const h=t.details;s.loadError++,h===b.BUFFER_APPEND_ERROR&&s.fragmentError++;let u=-1;const{levels:c,loadLevel:d,minAutoLevel:A,maxAutoLevel:f}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(n=t.frag)==null?void 0:n.type,p=(g===Z.AUDIO&&h===b.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(h===b.BUFFER_ADD_CODEC_ERROR||h===b.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:T})=>s.audioCodec!==T),E=t.sourceBufferName==="video"&&(h===b.BUFFER_ADD_CODEC_ERROR||h===b.BUFFER_APPEND_ERROR)&&c.some(({codecSet:T,audioCodec:B})=>s.codecSet!==T&&s.audioCodec===B),{type:y,groupId:v}=(r=t.context)!=null?r:{};for(let T=c.length;T--;){const B=(T+d)%c.length;if(B!==d&&B>=A&&B<=f&&c[B].loadError===0){var o,l;const _=c[B];if(h===b.FRAG_GAP&&g===Z.MAIN&&t.frag){const D=c[B].details;if(D){const x=Ei(t.frag,D.fragments,t.frag.start);if(x!=null&&x.gap)continue}}else{if(y===gt.AUDIO_TRACK&&_.hasAudioGroup(v)||y===gt.SUBTITLE_TRACK&&_.hasSubtitleGroup(v))continue;if(g===Z.AUDIO&&(o=s.audioGroups)!=null&&o.some(D=>_.hasAudioGroup(D))||g===Z.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(D=>_.hasSubtitleGroup(D))||p&&s.audioCodec===_.audioCodec||!p&&s.audioCodec!==_.audioCodec||E&&s.codecSet===_.codecSet)continue}u=B;break}}if(u>-1&&i.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:Jt.SendAlternateToPenaltyBox,flags:de.None,nextAutoLevel:u}}return{action:Jt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case Jt.DoNothing:break;case Jt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==b.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 Jt.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:n,nextAutoLevel:r}=i;switch(s){case de.None:this.switchLevel(t,r);break;case de.MoveAllAlternatesMatchingHDCP:n&&(e.maxHdcpLevel=na[na.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(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,t.details===b.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo")){const i=ru(t.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${t.sourceBufferName}Codec`]===i&&this.hls.removeLevel(n)}}}function Ss(a){const t={action:Jt.DoNothing,flags:de.None};return a&&(t.resolved=!0),t}var $t={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class YC{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.MANIFEST_LOADING,this.onManifestLoading,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.MANIFEST_LOADING,this.onManifestLoading,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 n=i[s];if(!n)break;const r=n.end;if(n.start<=t&&r!==null&&t<=r)return n}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:s}=this,n=Object.keys(s);for(let r=n.length;r--;){const o=s[n[r]];if((o==null?void 0:o.body.type)===e&&(!i||o.buffered)){const l=o.body;if(l.start<=t&&t<=l.end)return l}}return null}detectEvictedFragments(t,e,i,s,n){this.timeRanges&&(this.timeRanges[t]=e);const r=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||r>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===i&&this.removeFragment(l.body);return}const h=l.range[t];if(h){if(h.time.length===0){this.removeFragment(l.body);return}h.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,e);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(t){const e=this.timeRanges;if(!e||t.frag.sn==="initSegment")return;const i=t.frag,s=Li(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const r=!i.relurl;Object.keys(e).forEach(o=>{const l=i.elementaryStreams[o];if(!l)return;const h=e[o],u=r||l.partial===!0;n.range[o]=this.getBufferedTimes(i,t.part,u,h)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),zs(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ol(i,s=>s.fragment.sn>=t))}fragBuffered(t,e){const i=Li(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 n={time:[],partial:i},r=t.start,o=t.end,l=t.minEndPTS||o,h=t.maxStartPTS||r;for(let u=0;u<s.length;u++){const c=s.start(u)-this.bufferPadding,d=s.end(u)+this.bufferPadding;if(h>=c&&l<=d){n.time.push({startPTS:Math.max(r,s.start(u)),endPTS:Math.min(o,s.end(u))});break}else if(r<d&&o>c){const A=Math.max(r,s.start(u)),f=Math.min(o,s.end(u));f>A&&(n.partial=!0,n.time.push({startPTS:A,endPTS:f}))}else if(o<=c)break}return n}getPartialFragment(t){let e=null,i,s,n,r=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const u=l[h];u&&zs(u)&&(s=u.body.start-o,n=u.body.end+o,t>=s&&t<=n&&(i=Math.min(t-s,n-t),r<=i&&(e=u.body,r=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||zs(e))}getState(t){const e=Li(t),i=this.fragments[e];return i?i.buffered?zs(i)?$t.PARTIAL:$t.OK:$t.APPENDING:$t.NOT_LOADED}isTimeBuffered(t,e,i){let s,n;for(let r=0;r<i.length;r++){if(s=i.start(r)-this.bufferPadding,n=i.end(r)+this.bufferPadding,t>=s&&e<=n)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(e.frag.sn==="initSegment"||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,n=Li(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:n,type:r}=e;if(i.sn==="initSegment")return;const o=i.type;if(s){let h=this.activePartLists[o];h||(this.activePartLists[o]=h=[]),h.push(s)}this.timeRanges=n;const l=n[r];this.detectEvictedFragments(r,l,o,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Li(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const n=e[i[s]];if((n==null?void 0:n.body.type)===t)return!0}return!1}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}removeFragmentsInRange(t,e,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<e&&l.end>t&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(t){const e=Li(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const s=t.sn;this.activePartLists[t.type]=Ol(i,n=>n.fragment.sn!==s)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t,e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(t=this.hls)==null||(e=t.latestLevelDetails)==null?void 0:e.partList;i&&i.forEach(s=>s.clearElementaryStreamInfo())}}function zs(a){var t,e,i;return a.buffered&&(a.body.gap||((t=a.range.video)==null?void 0:t.partial)||((e=a.range.audio)==null?void 0:e.partial)||((i=a.range.audiovideo)==null?void 0:i.partial))}function Li(a){return`${a.type}_${a.level}_${a.sn}`}function Ol(a,t){return a.filter(e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i})}var ni={cbc:0,ctr:1};class VC{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case ni.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case ni.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function JC(a){const t=a.byteLength,e=t&&new DataView(a.buffer).getUint8(t-1);return e?a.slice(0,t-e):a}class zC{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],n=i[1],r=i[2],o=i[3],l=this.invSubMix,h=l[0],u=l[1],c=l[2],d=l[3],A=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)m<128?A[m]=m<<1:A[m]=m<<1^283;for(m=0;m<256;m++){let p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^p&255^99,t[f]=p,e[p]=f;const C=A[f],E=A[C],y=A[E];let v=A[p]*257^p*16843008;s[f]=v<<24|v>>>8,n[f]=v<<16|v>>>16,r[f]=v<<8|v>>>24,o[f]=v,v=y*16843009^E*65537^C*257^f*16843008,h[p]=v<<24|v>>>8,u[p]=v<<16|v>>>16,c[p]=v<<8|v>>>24,d[p]=v,f?(f=C^A[A[A[y^C]]],g^=A[A[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 n=this.keySize=e.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const r=this.ksRows=(n+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(r),u=this.invKeySchedule=new Uint32Array(r),c=this.sBox,d=this.rcon,A=this.invSubMix,f=A[0],g=A[1],m=A[2],p=A[3];let C,E;for(o=0;o<r;o++){if(o<n){C=h[o]=e[o];continue}E=C,o%n===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=d[o/n|0]<<24):n>6&&o%n===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),h[o]=C=(h[o-n]^E)>>>0}for(l=0;l<r;l++)o=r-l,l&3?E=h[o]:E=h[o-4],l<4||o<=4?u[l]=E:u[l]=f[c[E>>>24]]^g[c[E>>>16&255]]^m[c[E>>>8&255]]^p[c[E&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],u=o[2],c=o[3],d=this.uint8ArrayToUint32Array_(i);let A=d[0],f=d[1],g=d[2],m=d[3];const p=new Int32Array(t),C=new Int32Array(p.length);let E,y,v,T,B,_,D,x,M,k,X,W,H,Y;const z=this.networkToHostOrderSwap;for(;e<p.length;){for(M=z(p[e]),k=z(p[e+1]),X=z(p[e+2]),W=z(p[e+3]),B=M^n[0],_=W^n[1],D=X^n[2],x=k^n[3],H=4,Y=1;Y<s;Y++)E=l[B>>>24]^h[_>>16&255]^u[D>>8&255]^c[x&255]^n[H],y=l[_>>>24]^h[D>>16&255]^u[x>>8&255]^c[B&255]^n[H+1],v=l[D>>>24]^h[x>>16&255]^u[B>>8&255]^c[_&255]^n[H+2],T=l[x>>>24]^h[B>>16&255]^u[_>>8&255]^c[D&255]^n[H+3],B=E,_=y,D=v,x=T,H=H+4;E=r[B>>>24]<<24^r[_>>16&255]<<16^r[D>>8&255]<<8^r[x&255]^n[H],y=r[_>>>24]<<24^r[D>>16&255]<<16^r[x>>8&255]<<8^r[B&255]^n[H+1],v=r[D>>>24]<<24^r[x>>16&255]<<16^r[B>>8&255]<<8^r[_&255]^n[H+2],T=r[x>>>24]<<24^r[B>>16&255]<<16^r[_>>8&255]<<8^r[D&255]^n[H+3],C[e]=z(E^A),C[e+1]=z(T^f),C[e+2]=z(v^g),C[e+3]=z(y^m),A=M,f=k,g=X,m=W,e=e+4}return C.buffer}}class qC{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=XC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function XC(a){switch(a){case ni.cbc:return"AES-CBC";case ni.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const WC=16;class Ka{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.enableSoftwareAES=void 0,this.enableSoftwareAES=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?JC(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s){return this.useSoftware?new Promise((n,r)=>{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,e,i,s);const l=this.flush();l?n(l.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:n,currentResult:r,remainderData:o}=this;if(s!==ni.cbc||e.byteLength!==16)return Et.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=fe(o,t),this.remainderData=null);const l=this.getValidChunk(t);if(!l.length)return null;n&&(i=n);let h=this.softwareDecrypter;h||(h=this.softwareDecrypter=new zC),h.expandKey(e);const u=r;return this.currentResult=h.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new qC(this.subtle,e,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new VC(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Et.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%WC;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(Et.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ql=Math.pow(2,17);class jC{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 Ge({type:et.NETWORK_ERROR,details:b.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,n=s.fLoader,r=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){l(Gl(t));return}else t.gap=!1;const h=this.loader=n?new n(s):new r(s),u=Ul(t);t.loader=h;const c=kl(s.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Ql};t.stats=h.stats;const A={onSuccess:(f,g,m,p)=>{this.resetLoader(t,h);let C=f.data;m.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(C.slice(0,16)),C=C.slice(16)),o({frag:t,part:null,payload:C,networkDetails:p})},onError:(f,g,m,p)=>{this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:St({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))}};e&&(A.onProgress=(f,g,m,p)=>e({frag:t,part:null,payload:m,networkDetails:p})),h.load(u,d,A)})}loadPart(t,e,i){this.abort();const s=this.config,n=s.fLoader,r=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(Gl(t,e));return}const h=this.loader=n?new n(s):new r(s),u=Ul(t,e);t.loader=h;const c=kl(s.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ql};e.stats=h.stats,h.load(u,d,{onSuccess:(A,f,g,m)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const p={frag:t,part:e,payload:A.data,networkDetails:m};i(p),o(p)},onError:(A,f,g,m)=>{this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:St({url:u.url,data:void 0},A),error:new Error(`HTTP Error ${A.code} ${A.text}`),networkDetails:g,stats:m}))},onAbort:(A,f,g)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:g,stats:A}))},onTimeout:(A,f,g)=>{this.resetLoader(t,h),l(new Ge({type:et.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:A}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(t.duration/e.duration),h=Math.min(Math.round(i.loaded/n),l),c=(l-h)*Math.round(i.loaded/h);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const r=i.loading,o=s.loading;r.start?r.first+=o.first-o.start:(r.start=o.start,r.first=o.first),r.end=o.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Ul(a,t=null){const e=t||a,i={frag:a,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},s=e.byteRangeStartOffset,n=e.byteRangeEndOffset;if(j(s)&&j(n)){var r;let o=s,l=n;if(a.sn==="initSegment"&&ZC((r=a.decryptdata)==null?void 0:r.method)){const h=n-s;h%16&&(l=n+(16-h%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Gl(a,t){const e=new Error(`GAP ${a.gap?"tag":"attribute"} found`),i={type:et.MEDIA_ERROR,details:b.FRAG_GAP,fatal:!1,frag:a,error:e,networkDetails:null};return t&&(i.part=t),(t||a).stats.aborted=!0,new Ge(i)}function ZC(a){return a==="AES-128"||a==="AES-256"}class Ge extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Au extends qe{constructor(t,e){super(t,e),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(){}}class Gn{constructor(t,e,i,s=0,n=-1,r=!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=qs(),this.buffering={audio:qs(),video:qs(),audiovideo:qs()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=n,this.partial=r}}function qs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Nl={length:0,start:()=>0,end:()=>0};class ft{static isBuffered(t,e){if(t){const i=ft.getBuffered(t);for(let s=i.length;s--;)if(e>=i.start(s)&&e<=i.end(s))return!0}return!1}static bufferedRanges(t){if(t){const e=ft.getBuffered(t);return ft.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=ft.bufferedRanges(t);if(s.length)return ft.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((u,c)=>u.start-c.start||c.end-u.end);let s=-1,n=[];if(i)for(let u=0;u<t.length;u++){e>=t[u].start&&e<=t[u].end&&(s=u);const c=n.length;if(c){const d=n[c-1].end;t[u].start-d<i?t[u].end>d&&(n[c-1].end=t[u].end):n.push(t[u])}else n.push(t[u])}else n=t;let r=0,o,l=e,h=e;for(let u=0;u<n.length;u++){const c=n[u].start,d=n[u].end;if(s===-1&&e>=c&&e<=d&&(s=u),e+i>=c&&e<d)l=c,h=d,r=h-e;else if(e+i<c){o=c;break}}return{len:r,start:l||0,end:h||0,nextStart:o,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||Nl}catch(e){return Et.log("failed to get media.buffered",e),Nl}}}const fu=/\{\$([a-zA-Z0-9-_]+)\}/g;function Hl(a){return fu.test(a)}function aa(a,t){if(a.variableList!==null||a.hasVariableRefs){const e=a.variableList;return t.replace(fu,i=>{const s=i.substring(2,i.length-1),n=e==null?void 0:e[s];return n===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return t}function Kl(a,t,e){let i=a.variableList;i||(a.variableList=i={});let s,n;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const r=new self.URL(e).searchParams;if(r.has(s))n=r.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${e}"`)}catch(r){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${r.message}`))}}else s=t.NAME,n=t.VALUE;s in i?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function ty(a,t,e){const i=t.IMPORT;if(e&&i in e){let s=a.variableList;s||(a.variableList=s={}),s[i]=e[i]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const ey=/^(\d+)x(\d+)$/,$l=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Pt{constructor(t,e){typeof t=="string"&&(t=Pt.parseAttrList(t,e)),xt(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}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]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),e)}bool(t){return this[t]==="YES"}decimalResolution(t){const e=ey.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={},n='"';for($l.lastIndex=0;(i=$l.exec(t))!==null;){const r=i[1].trim();let o=i[2];const l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1;let h=!1;if(l)o=o.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":h=!0}if(e&&(l||h))o=aa(e,o);else if(!h&&!l)switch(r){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Et.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=o}return s}}const iy="com.apple.hls.interstitial";function sy(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function ny(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class $a{constructor(t,e,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(e==null?void 0:e.tagAnchor)||null,this.tagOrder=(s=e==null?void 0:e.tagOrder)!=null?s:i,e){const n=e.attr;for(const r in n)if(Object.prototype.hasOwnProperty.call(t,r)&&t[r]!==n[r]){Et.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=r;break}t=xt(new Pt({}),n,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const n=(e==null?void 0:e.endDate)||new Date(this.attr["END-DATE"]);j(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return t===null||t.programDateTime===null?(Et.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return e!==null?this._dateAtEnd=new Date(this._startDate.getTime()+e*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 isInterstitial(){return this.class===iy}get isValid(){return!!this.id&&!this._badValueForSameId&&j(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const ry=10;class gu{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,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}get hasProgramDateTime(){return this.fragments.length?j(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ry}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 fragmentStart(){var t;return(t=this.fragments)!=null&&t.length?this.fragments[0].start: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 maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(e!==-1){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Ui(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function Ya(a){switch(a){case"AES-128":case"AES-256":return ni.cbc;case"AES-256-CTR":return ni.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function Va(a){return Uint8Array.from(atob(a),t=>t.charCodeAt(0))}function oa(a){return Uint8Array.from(unescape(encodeURIComponent(a)),t=>t.charCodeAt(0))}function ay(a){const t=oa(a).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function oy(a){const t=function(i,s,n){const r=i[s];i[s]=i[n],i[n]=r};t(a,0,3),t(a,1,2),t(a,4,5),t(a,6,7)}function ly(a){const t=a.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 n=s[0]==="base64",r=s[1];n?(i.splice(-1,1),e=Va(r)):e=ay(r)}}return e}const Rn=typeof self<"u"?self:void 0;var vt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},jt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function yr(a){switch(a){case jt.FAIRPLAY:return vt.FAIRPLAY;case jt.PLAYREADY:return vt.PLAYREADY;case jt.WIDEVINE:return vt.WIDEVINE;case jt.CLEARKEY:return vt.CLEARKEY}}var Xs={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function vr(a){if(a===Xs.WIDEVINE)return vt.WIDEVINE;if(a===Xs.PLAYREADY)return vt.PLAYREADY;if(a===Xs.CENC||a===Xs.CLEARKEY)return vt.CLEARKEY}function Br(a){switch(a){case vt.FAIRPLAY:return jt.FAIRPLAY;case vt.PLAYREADY:return jt.PLAYREADY;case vt.WIDEVINE:return jt.WIDEVINE;case vt.CLEARKEY:return jt.CLEARKEY}}function Ws(a){const{drmSystems:t,widevineLicenseUrl:e}=a,i=t?[vt.FAIRPLAY,vt.WIDEVINE,vt.PLAYREADY,vt.CLEARKEY].filter(s=>!!t[s]):[];return!i[vt.WIDEVINE]&&e&&i.push(vt.WIDEVINE),i}const Ja=function(a){return Rn!=null&&(a=Rn.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function hy(a,t,e,i){let s;switch(a){case vt.FAIRPLAY:s=["cenc","sinf"];break;case vt.WIDEVINE:case vt.PLAYREADY:s=["cenc"];break;case vt.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return cy(s,t,e,i)}function cy(a,t,e,i){return[{initDataTypes:a,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:e.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function uy(a){var t;return a.sessionType==="persistent-license"||!!((t=a.sessionTypes)!=null&&t.some(e=>e==="persistent-license"))}function mu(a){const t=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),e=String.fromCharCode.apply(null,Array.from(t)),i=e.substring(e.indexOf("<"),e.length),r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const o=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(o){const l=Va(o).subarray(0,16);return oy(l),l}}return null}let js={};class Ki{static clearKeyUriToKeyIdMap(){js={}}constructor(t,e,i,s=[1],n=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=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ui(t)}isSupported(){if(this.method){if(Ui(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case jt.FAIRPLAY:case jt.WIDEVINE:case jt.PLAYREADY:case jt.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(Ui(this.method)&&this.uri&&!this.iv){typeof t!="number"&&(Et.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=dy(t);return new Ki(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=ly(this.uri);if(e)switch(this.keyFormat){case jt.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case jt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=CC(i,null,e),this.keyId=mu(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=js[this.uri];if(!i){const s=Object.keys(js).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),js[this.uri]=i}this.keyId=i}return this}}function dy(a){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=a>>8*(15-e)&255;return t}const Yl=/#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,Vl=/#EXT-X-MEDIA:(.*)/g,Ay=/^#EXT(?:INF|-X-TARGETDURATION):/m,Sr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),fy=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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 Be{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 Qa.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ay.test(t)}static parseMasterPlaylist(t,e){const i=Hl(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];Yl.lastIndex=0;let r;for(;(r=Yl.exec(t))!=null;)if(r[1]){var o;const h=new Pt(r[1],s),u=aa(s,r[2]),c={attrs:h,bitrate:h.decimalInteger("BANDWIDTH")||h.decimalInteger("AVERAGE-BANDWIDTH"),name:h.NAME,url:Be.resolve(u,e)},d=h.decimalResolution("RESOLUTION");d&&(c.width=d.width,c.height=d.height),ql(h.CODECS,c);const A=h["SUPPLEMENTAL-CODECS"];A&&(c.supplemental={},ql(A,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),s.levels.push(c)}else if(r[3]){const h=r[3],u=r[4];switch(h){case"SESSION-DATA":{const c=new Pt(u,s),d=c["DATA-ID"];d&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[d]=c);break}case"SESSION-KEY":{const c=Jl(u,e,s);c.encrypted&&c.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(c)):Et.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new Pt(u,s);Kl(s,c,e)}break}case"CONTENT-STEERING":{const c=new Pt(u,s);s.contentSteering={uri:Be.resolve(c["SERVER-URI"],e),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=zl(u);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let s;const n={},r=i.levels,o={AUDIO:r.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:r.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Vl.lastIndex=0;(s=Vl.exec(t))!==null;){const h=new Pt(s[1],i),u=h.TYPE;if(u){const c=o[u],d=n[u]||[];n[u]=d;const A=h.LANGUAGE,f=h["ASSOC-LANGUAGE"],g=h.CHANNELS,m=h.CHARACTERISTICS,p=h["INSTREAM-ID"],C={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||A||"",type:u,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:A,url:h.URI?Be.resolve(h.URI,e):""};if(f&&(C.assocLang=f),g&&(C.channels=g),m&&(C.characteristics=m),p&&(C.instreamId=p),c!=null&&c.length){const E=Be.findGroup(c,C.groupId)||c[0];Xl(C,E,"audioCodec"),Xl(C,E,"textCodec")}d.push(C)}}return n}static parseLevelPlaylist(t,e,i,s,n,r){var o;const l={url:e},h=new gu(e),u=h.fragments,c=[];let d=null,A=0,f=0,g=0,m=0,p=0,C=null,E=new cn(s,l),y,v,T,B=-1,_=!1,D=null,x;if(Sr.lastIndex=0,h.m3u8=t,h.hasVariableRefs=Hl(t),((o=Sr.exec(t))==null?void 0:o[0])!=="#EXTM3U")return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;(y=Sr.exec(t))!==null;){_&&(_=!1,E=new cn(s,l),E.playlistOffset=g,E.start=g,E.sn=A,E.cc=m,p&&(E.bitrate=p),E.level=i,d&&(E.initSegment=d,d.rawProgramDateTime&&(E.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),D&&(E.setByteRange(D),D=null)));const W=y[1];if(W){E.duration=parseFloat(W);const H=(" "+y[2]).slice(1);E.title=H||null,E.tagList.push(H?["INF",W,H]:["INF",W])}else if(y[3]){if(j(E.duration)){E.playlistOffset=g,E.start=g,T&&jl(E,T,h),E.sn=A,E.level=i,E.cc=m,u.push(E);const H=(" "+y[3]).slice(1);E.relurl=aa(h,H),la(E,C,c),C=E,g+=E.duration,A++,f=0,_=!0}}else{if(y=y[0].match(fy),!y){Et.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<y.length&&y[v]===void 0;v++);const H=(" "+y[v]).slice(1),Y=(" "+y[v+1]).slice(1),z=y[v+2]?(" "+y[v+2]).slice(1):null;switch(H){case"BYTERANGE":C?E.setByteRange(Y,C):E.setByteRange(Y);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=Y,E.tagList.push(["PROGRAM-DATE-TIME",Y]),B===-1&&(B=u.length);break;case"PLAYLIST-TYPE":h.type&&Oe(h,H,y),h.type=Y.toUpperCase();break;case"MEDIA-SEQUENCE":h.startSN!==0?Oe(h,H,y):u.length>0&&Zl(h,H,y),A=h.startSN=parseInt(Y);break;case"SKIP":{h.skippedSegments&&Oe(h,H,y);const J=new Pt(Y,h),U=J.decimalInteger("SKIPPED-SEGMENTS");if(j(U)){h.skippedSegments+=U;for(let N=U;N--;)u.push(null);A+=U}const F=J.enumeratedString("RECENTLY-REMOVED-DATERANGES");F&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(F.split(" ")));break}case"TARGETDURATION":h.targetduration!==0&&Oe(h,H,y),h.targetduration=Math.max(parseInt(Y),1);break;case"VERSION":h.version!==null&&Oe(h,H,y),h.version=parseInt(Y);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Oe(h,H,y),h.live=!1;break;case"#":(Y||z)&&E.tagList.push(z?[Y,z]:[Y]);break;case"DISCONTINUITY":m++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([H]);break;case"BITRATE":E.tagList.push([H,Y]),p=parseInt(Y)*1e3,j(p)?E.bitrate=p:p=0;break;case"DATERANGE":{const J=new Pt(Y,h),U=new $a(J,h.dateRanges[J.ID],h.dateRangeTagCount);h.dateRangeTagCount++,U.isValid||h.skippedSegments?h.dateRanges[U.id]=U:Et.warn(`Ignoring invalid DATERANGE tag: "${Y}"`),E.tagList.push(["EXT-X-DATERANGE",Y]);break}case"DEFINE":{{const J=new Pt(Y,h);"IMPORT"in J?ty(h,J,r):Kl(h,J,e)}break}case"DISCONTINUITY-SEQUENCE":h.startCC!==0?Oe(h,H,y):u.length>0&&Zl(h,H,y),h.startCC=m=parseInt(Y);break;case"KEY":{const J=Jl(Y,e,h);if(J.isSupported()){if(J.method==="NONE"){T=void 0;break}T||(T={}),T[J.keyFormat]&&(T=xt({},T)),T[J.keyFormat]=J}else Et.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${Y}"`);break}case"START":h.startTimeOffset=zl(Y);break;case"MAP":{const J=new Pt(Y,h);if(E.duration){const U=new cn(s,l);Wl(U,J,i,T),d=U,E.initSegment=d,d.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=d.rawProgramDateTime)}else{const U=E.byteRangeEndOffset;if(U){const F=E.byteRangeStartOffset;D=`${U-F}@${F}`}else D=null;Wl(E,J,i,T),d=E,_=!0}d.cc=m;break}case"SERVER-CONTROL":{x&&Oe(h,H,y),x=new Pt(Y),h.canBlockReload=x.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=x.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&x.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=x.optionalFloat("PART-HOLD-BACK",0),h.holdBack=x.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{h.partTarget&&Oe(h,H,y);const J=new Pt(Y);h.partTarget=J.decimalFloatingPoint("PART-TARGET");break}case"PART":{let J=h.partList;J||(J=h.partList=[]);const U=f>0?J[J.length-1]:void 0,F=f++,N=new Pt(Y,h),K=new zc(N,E,l,F,U);J.push(K),E.duration+=K.duration;break}case"PRELOAD-HINT":{const J=new Pt(Y,h);h.preloadHint=J;break}case"RENDITION-REPORT":{const J=new Pt(Y,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(J);break}default:Et.warn(`line parsed but not handled: ${y}`);break}}}C&&!C.relurl?(u.pop(),g-=C.duration,h.partList&&(h.fragmentHint=C)):h.partList&&(la(E,C,c),E.cc=m,h.fragmentHint=E,T&&jl(E,T,h)),h.targetduration||(h.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const M=u.length,k=u[0],X=u[M-1];if(g+=h.skippedSegments*h.targetduration,g>0&&M&&X){h.averagetargetduration=g/M;const W=X.sn;h.endSN=W!=="initSegment"?W:0,h.live||(X.endList=!0),k&&h.startCC===void 0&&(h.startCC=k.cc),B>0&&(my(u,B),k&&c.unshift(k))}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(g+=h.fragmentHint.duration),h.totalduration=g,c.length&&h.dateRangeTagCount&&k&&pu(c,h),h.endCC=m,h}}function pu(a,t){const e=a.length,i=a[e-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let r=n.length;r--;){const o=t.dateRanges[n[r]],l=o.startDate.getTime();o.tagAnchor=i.ref;for(let h=e;h--;){const u=gy(t,l,a,h,s);if(u!==-1){o.tagAnchor=t.fragments[u].ref;break}}}}function gy(a,t,e,i,s){const n=e[i];if(n){const o=n.programDateTime;if(t>=o||i===0){var r;const l=(((r=e[i+1])==null?void 0:r.start)||s)-n.start;if(t<=o+l*1e3){const h=e[i].sn-a.startSN,u=a.fragments;if(u.length>e.length){const d=(e[i+1]||u[u.length-1]).sn-a.startSN;for(let A=d;A>h;A--){const f=u[A].programDateTime;if(t>=f&&t<f+u[A].duration*1e3)return A}}return h}}}return-1}function Jl(a,t,e){var i,s;const n=new Pt(a,e),r=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&Et.error(`Invalid IV: ${n.IV}`);const c=o?Be.resolve(o,t):"",d=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ki(r,c,u,d,l)}function zl(a){const e=new Pt(a).decimalFloatingPoint("TIME-OFFSET");return j(e)?e:null}function ql(a,t){let e=(a||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=e.filter(n=>su(n,i));s.length&&(t[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),e=e.filter(n=>s.indexOf(n)===-1))}),t.unknownCodecs=e}function Xl(a,t,e){const i=t[e];i&&(a[e]=i)}function my(a,t){let e=a[t];for(let i=t;i--;){const s=a[i];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function la(a,t,e){a.rawProgramDateTime?e.push(a):t!=null&&t.programDateTime&&(a.programDateTime=t.endProgramDateTime)}function Wl(a,t,e,i){a.relurl=t.URI,t.BYTERANGE&&a.setByteRange(t.BYTERANGE),a.level=e,a.sn="initSegment",i&&(a.levelkeys=i),a.initSegment=null}function jl(a,t,e){a.levelkeys=t;const{encryptedFragments:i}=e;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&i.push(a)}function Oe(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`)}function Zl(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`)}function Tr(a,t){const e=t.startPTS;if(j(e)){let i=0,s;t.sn>a.sn?(i=e-a.start,s=a):(i=a.start-e,s=t),s.duration!==i&&s.setDuration(i)}else t.sn>a.sn?a.cc===t.cc&&a.minEndPTS?t.setStart(a.start+(a.minEndPTS-a.start)):t.setStart(a.start+a.duration):t.setStart(Math.max(a.start-t.duration,0))}function Eu(a,t,e,i,s,n){i-e<=0&&(Et.warn("Fragment should have a positive duration",t),i=e+t.duration,n=s+t.duration);let o=e,l=i;const h=t.startPTS,u=t.endPTS;if(j(h)){const m=Math.abs(h-e);j(t.deltaPTS)?t.deltaPTS=Math.max(m,t.deltaPTS):t.deltaPTS=m,o=Math.max(e,h),e=Math.min(e,h),s=Math.min(s,t.startDTS),l=Math.min(i,u),i=Math.max(i,u),n=Math.max(n,t.endDTS)}const c=e-t.start;t.start!==0&&t.setStart(e),t.setDuration(i-t.start),t.startPTS=e,t.maxStartPTS=o,t.startDTS=s,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const d=t.sn;if(!a||d<a.startSN||d>a.endSN)return 0;let A;const f=d-a.startSN,g=a.fragments;for(g[f]=t,A=f;A>0;A--)Tr(g[A],g[A-1]);for(A=f;A<g.length-1;A++)Tr(g[A],g[A+1]);return a.fragmentHint&&Tr(g[g.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,c}function py(a,t){if(a===t)return;let e=null;const i=a.fragments;for(let l=i.length-1;l>=0;l--){const h=i[l].initSegment;if(h){e=h;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let s;Cy(a,t,(l,h,u,c)=>{if(!t.startCC&&h.cc!==l.cc){var d,A;const f=l.cc-h.cc;for(let g=u;g<c.length;g++)c[g].cc+=f;t.startCC=(d=(A=yu(a,t.startSN-1))==null?void 0:A.cc)!=null?d:c[0].cc,t.endCC=c[c.length-1].cc}j(l.startPTS)&&j(l.endPTS)&&(h.setStart(h.startPTS=l.startPTS),h.startDTS=l.startDTS,h.maxStartPTS=l.maxStartPTS,h.endPTS=l.endPTS,h.endDTS=l.endDTS,h.minEndPTS=l.minEndPTS,h.setDuration(l.endPTS-l.startPTS),h.duration&&(s=h),t.PTSKnown=t.alignedSliding=!0),l.hasStreams&&(h.elementaryStreams=l.elementaryStreams),h.loader=l.loader,l.hasStats&&(h.stats=l.stats),l.initSegment&&(h.initSegment=l.initSegment,e=l.initSegment)});const n=t.fragments,r=t.fragmentHint?n.concat(t.fragmentHint):n;if(e&&r.forEach(l=>{var h;l&&(!l.initSegment||l.initSegment.relurl===((h=e)==null?void 0:h.relurl))&&(l.initSegment=e)}),t.skippedSegments)if(t.deltaUpdateFailed=n.some(l=>!l),t.deltaUpdateFailed){Et.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=t.skippedSegments;l--;)n.shift();t.startSN=n[0].sn}else{t.endCC=n[n.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=Ey(a.dateRanges,t));const l=a.fragments.filter(h=>h.rawProgramDateTime);if(a.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h<r.length;h++)r[h].programDateTime===null&&la(r[h],r[h-1],l);pu(l,t)}Iy(a.partList,t.partList,(l,h)=>{h.elementaryStreams=l.elementaryStreams,h.stats=l.stats}),s?Eu(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Iu(a,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=a.driftStartTime,t.driftStart=a.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const l=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=l),t.driftEndTime=o,t.driftEnd=l}else t.driftEndTime=a.driftEndTime,t.driftEnd=a.driftEnd,t.advancedDateTime=a.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=a.requestScheduled)}function Ey(a,t){const{dateRanges:e,recentlyRemovedDateranges:i}=t,s=xt({},a);i&&i.forEach(o=>{delete s[o]});const r=Object.keys(s).length;return r&&Object.keys(e).forEach(o=>{const l=s[o],h=new $a(e[o].attr,l);h.isValid?(s[o]=h,l||(h.tagOrder+=r)):Et.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Mt(e[o].attr)}"`)}),s}function Iy(a,t,e){if(a&&t){let i=0;for(let s=0,n=a.length;s<=n;s++){const r=a[s],o=t[s+i];r&&o&&r.index===o.index&&r.fragment.sn===o.fragment.sn?e(r,o):i--}}}function Cy(a,t,e){const i=t.skippedSegments,s=Math.max(a.startSN,t.startSN)-t.startSN,n=(a.fragmentHint?1:0)+(i?t.endSN:Math.min(a.endSN,t.endSN))-t.startSN,r=t.startSN-a.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let h=s;h<=n;h++){const u=l[r+h];let c=o[h];if(i&&!c&&u&&(c=t.fragments[h]=u),u&&c){if(e(u,c,h,o),u.url&&u.url!==c.url){t.playlistParsingError=th(`media sequence mismatch ${c.sn}:`,a,t,u,c);return}else if(u.cc!==c.cc){t.playlistParsingError=th(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,a,t,u,c);return}}}}function th(a,t,e,i,s){return new Error(`${a} ${s.url}
|
|
21
|
+
Playlist starting @${t.startSN}
|
|
22
|
+
${t.m3u8}
|
|
23
|
+
|
|
24
|
+
Playlist starting @${e.startSN}
|
|
25
|
+
${e.m3u8}`)}function Iu(a,t,e=!0){const i=t.startSN+t.skippedSegments-a.startSN,s=a.fragments,n=i>=0;let r=0;if(n&&i<s.length)r=s[i].start;else if(n&&t.startSN===a.endSN+1)r=a.fragmentEnd;else if(n&&e)r=a.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)r=a.fragmentStart;else return;ha(t,r)}function ha(a,t){if(t){const e=a.fragments;for(let i=a.skippedSegments;i<e.length;i++)e[i].addStart(t);a.fragmentHint&&a.fragmentHint.addStart(t)}}function Cu(a,t=1/0){let e=1e3*a.targetduration;if(a.updated){const i=a.fragments;if(i.length&&e*4>t){const n=i[i.length-1].duration*1e3;n<e&&(e=n)}}else e/=2;return Math.round(e)}function yu(a,t,e){if(!a)return null;let i=a.fragments[t-a.startSN];return i||(i=a.fragmentHint,i&&i.sn===t)?i:t<a.startSN&&e&&e.sn===t?e:null}function eh(a,t,e){return a?vu(a.partList,t,e):null}function vu(a,t,e){if(a)for(let i=a.length;i--;){const s=a[i];if(s.index===e&&s.fragment.sn===t)return s}return null}function Bu(a){a.forEach((t,e)=>{var i;(i=t.details)==null||i.fragments.forEach(s=>{s.level=e,s.initSegment&&(s.initSegment.level=e)})})}function Cs(a,t){for(let i=0,s=a.length;i<s;i++){var e;if(((e=a[i])==null?void 0:e.cc)===t)return a[i]}return null}function yy(a,t){return!!(a&&t.startCC<a.endCC&&t.endCC>a.startCC)}function ih(a,t){if(a){const e=a.start+t;a.start=a.startPTS=e,a.endPTS=e+a.duration}}function Su(a,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)ih(e[i],a);t.fragmentHint&&ih(t.fragmentHint,a),t.alignedSliding=!0}function vy(a,t){a&&(Tu(t,a),!t.alignedSliding&&a&&Ln(t,a),!t.alignedSliding&&a&&!t.skippedSegments&&Iu(a,t,!1))}function Tu(a,t){if(!yy(t,a))return;const e=Math.min(t.endCC,a.endCC),i=Cs(t.fragments,e),s=Cs(a.fragments,e);if(!i||!s)return;Et.log(`Aligning playlist at start of dicontinuity sequence ${e}`);const n=i.start-s.start;Su(n,a)}function Ln(a,t){if(!a.hasProgramDateTime||!t.hasProgramDateTime)return;const e=a.fragments,i=t.fragments;if(!e.length||!i.length)return;let s,n;const r=Math.min(t.endCC,a.endCC);t.startCC<r&&a.startCC<r&&(s=Cs(i,r),n=Cs(e,r)),(!s||!n)&&(s=i[Math.floor(i.length/2)],n=Cs(e,s.cc)||e[Math.floor(e.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;const h=(l-o)/1e3-(n.start-s.start);Su(h,a)}const By={toString:function(a){let t="";const e=a.length;for(let i=0;i<e;i++)t+=`[${a.start(i).toFixed(3)}-${a.end(i).toFixed(3)}]`;return t}},G={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 Nn extends Au{constructor(t,e,i,s,n){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=G.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.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.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:r,fragCurrent:o,media:l,mediaBuffer:h,state:u}=this,c=l?l.currentTime:0,d=ft.bufferInfo(h||l,c,r.maxBufferHole);if(this.log(`media seeking to ${j(c)?c.toFixed(3):c}, state: ${u}`),this.state===G.ENDED)this.resetLoadingState();else if(o){const A=r.maxFragLookUpTolerance,f=o.start-A,g=o.start+o.duration+A;if(!d.len||g<d.start||f>d.end){const m=c>g;(c<f||m)&&(m&&o.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const A=this.lastCurrentTime;if(c>A&&(this.lastCurrentTime=c),!this.loadingParts){const f=Math.max(d.end,c),g=this.shouldLoadParts(this.getLevelDetails(),f);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=g)}}!this.hls.hasEnoughToStart&&!d.len&&(this.log(`setting startPosition to ${c} because of seek before start`),this.nextLoadPosition=this.startPosition=c),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new jC(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ka(t.config)}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_LOADED,this.onManifestLoaded,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_LOADED,this.onManifestLoaded,this),t.off(I.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===G.STOPPED)return;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=G.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return e===-1&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const n=t.nextStart;if(n&&n>s&&n<e.edge||this.media.currentTime<t.start)return!1;const o=e.partList;if(o!=null&&o.length){const h=o[o.length-1];return ft.isBuffered(this.media,h.start+h.duration/2)}const l=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var t;return(t=this.levelLastLoaded)==null?void 0:t.details}}get timelineOffset(){const t=this.config.timelineOffset;if(t){var e;return((e=this.getLevelDetails())==null?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===G.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=G.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.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){const s=n=>{const r=n.frag;if(this.fragContextChanged(r)){this.warn(`${r.type} sn: ${r.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(r,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(r);return}r.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(t,e,i,s).then(n=>{if(!n)return;const r=this.state,o=n.frag;if(this.fragContextChanged(o)){(r===G.FRAG_LOADING||!this.fragCurrent&&r===G.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=G.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(I.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===G.STOPPED||this.state===G.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===$t.APPENDING){const n=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(t.duration,r?r.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)===$t.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)}waitForLive(t){const e=t.details;return(e==null?void 0:e.live)&&e.type!=="EVENT"&&(this.levelLastLoaded!==t||e.expired)}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=>{const s=i==null?void 0:i.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{frag:n,payload:r}=i,o=n.decryptdata;if(r&&r.byteLength>0&&o!=null&&o.key&&o.iv&&Ui(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer,Ya(o.method)).catch(h=>{throw s.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:h,reason:h.message,frag:n}),h}).then(h=>{const u=self.performance.now();return s.trigger(I.FRAG_DECRYPTED,{frag:n,payload:h,stats:{tstart:l,tdecrypt:u}}),i.payload=h,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===G.STOPPED||this.state===G.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!==G.STOPPED&&(this.state=G.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){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?By.toString(ft.getBuffered(i)):"(detached)"})`),zt(t)){var s;if(t.type!==Z.SUBTITLE){const r=t.elementaryStreams;if(!Object.keys(r).some(o=>!!r[o])){this.state=G.IDLE;return}}const n=(s=this.levels)==null?void 0:s[t.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=G.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:n}=t,r=!n||n.length===0||n.some(l=>!l),o=new Gn(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!r);e.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var n;this.fragCurrent=t;const r=e==null?void 0:e.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let o=null;t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${t.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=G.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(I.KEY_LOADED,c),this.state===G.KEY_LOADING&&(this.state=G.IDLE),c}),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&&r.encryptedFragments.length&&this.keyLoader.loadClear(t,r.encryptedFragments);const l=this.fragPrevious;if(zt(t)&&(!l||t.sn!==l.sn)){const c=this.shouldLoadParts(e.details,t.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${t.sn}`),this.loadingParts=c)}if(i=Math.max(t.start,i||0),this.loadingParts&&zt(t)){const c=r.partList;if(c&&s){i>t.end&&r.fragmentHint&&(t=r.fragmentHint);const d=this.getNextPart(c,t,i);if(d>-1){const A=c[d];t=this.fragCurrent=A.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${A.index} (${d}/${c.length-1}) of ${this.fragInfo(t,!1,A)}) cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=A.start+A.duration,this.state=G.FRAG_LOADING;let f;return o?f=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(t,A,e,s)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(t,A,e,s).catch(g=>this.handleFragLoadError(g)),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")):f}else if(!t.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}if(zt(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${r?"["+r.startSN+"-"+r.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),j(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=G.FRAG_LOADING;const h=this.config.progressive;let u;return h&&o?u=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(t,s)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(t,h?s:void 0),o]).then(([c])=>(!h&&c&&s&&s(c),c)).catch(c=>this.handleFragLoadError(c)),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")):u}doFragPartsLoad(t,e,i,s){return new Promise((n,r)=>{var o;const l=[],h=(o=i.details)==null?void 0:o.partList,u=c=>{this.fragmentLoader.loadPart(t,c,s).then(d=>{l[c.index]=d;const A=d.part;this.hls.trigger(I.FRAG_LOADED,d);const f=eh(i.details,t.sn,c.index+1)||vu(h,t.sn,c.index+1);if(f)u(f);else return n({frag:t,part:A,partsLoaded:l})}).catch(r)};u(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===b.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(I.ERROR,e)}else this.hls.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==G.PARSING){!this.fragCurrent&&this.state!==G.STOPPED&&this.state!==G.ERROR&&(this.state=G.IDLE);return}const{frag:i,part:s,level:n}=e,r=self.performance.now();i.stats.parsing.end=r,s&&(s.stats.parsing.end=r);const o=this.getLevelDetails(),h=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=h),this.updateLevelTiming(i,s,n,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t!=null&&t.partList){var i;const n=t.partList[0],r=n.end+(((i=t.fragmentHint)==null?void 0:i.duration)||0);if(e>=r){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:n,part:r}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=e[s],l=o.details,h=r>-1?eh(l,n,r):null,u=h?h.fragment:yu(l,n,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:h,level:o}):null}bufferFragmentData(t,e,i,s,n){var r;if(!t||this.state!==G.PARSING)return;const{data1:o,data2:l}=t;let h=o;if(o&&l&&(h=fe(o,l)),!((r=h)!=null&&r.length))return;const u={type:t.type,frag:e,part:i,chunkMeta:s,parent:e.type,data:h};if(this.hls.trigger(I.BUFFER_APPENDING,u),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ft.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=ft.bufferInfo(e,i,0),n=t.duration,r=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(t.start-r,s.end-r),i+r);t.start-o>r&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){var i;const s=this.getLoadPosition();if(!j(s))return null;const r=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,r)}getFwdBufferInfoAtPos(t,e,i,s){const n=ft.bufferInfo(t,e,s);if(n.len===0&&n.nextStart!==void 0){const r=this.fragmentTracker.getBufferedFrag(e,i);if(r&&(n.nextStart<=r.end||r.gap)){const o=Math.max(Math.min(n.nextStart,r.end)-e,s);return ft.bufferInfo(t,e,o)}}return n}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),n=Math.max(t-e*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(t,e=Z.MAIN){var i;const s=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(t,e);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:n}=this,r=i[0].start,o=n.lowLatencyMode&&!!e.partList;let l=null;if(e.live){const c=n.initialLiveManifestSize;if(s<c)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${c})`),null;if(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<r){var h;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(e,i);const d=this.hls.startPosition,A=this.hls.liveSyncPosition,f=l?(d!==-1&&d>=r?d:A)||l.start:t;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${A} frag.start: ${(h=l)==null?void 0:h.start}`),this.startPosition=this.nextLoadPosition=f}}else t<=r&&(l=i[0]);if(!l){const c=this.loadingParts?e.partEnd:e.fragmentEnd;l=this.getFragmentAtPosition(t,c,e)}let u=this.filterReplacedPrimary(l,e);if(!u&&l){const c=l.sn-e.startSN;u=this.filterReplacedPrimary(i[c+1]||null,e)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===$t.OK||i===$t.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,n){let r=null;if(t.gap&&(r=this.getNextFragment(this.nextLoadPosition,e),r&&!r.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){const l=r.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,r}get primaryPrefetch(){if(sh(this.hls.config)){var t,e;if((t=this.hls.interstitialsManager)==null||(e=t.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(sh(this.hls.config)&&t.type!==Z.SUBTITLE){const i=this.hls.interstitialsManager,s=i==null?void 0:i.bufferingItem;if(s){const r=s.event;if(r){if(r.appendInPlace||Math.abs(t.start-s.start)>1||s.start===0)return null}else if(t.end<=s.start&&(e==null?void 0:e.live)===!1||t.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||t.start-s.end>1))return null}const n=i==null?void 0:i.playerQueue;if(n)for(let r=n.length;r--;){const o=n[r].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return 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,n=!1,r=!0;for(let o=0,l=t.length;o<l;o++){const h=t[o];if(r=r&&!h.independent,s>-1&&i<h.start)break;const u=h.loaded;u?s=-1:(n||h.independent||r)&&h.fragment===e&&(s=o),n=u}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=GC(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=t.startSN&&n<=t.endSN){const r=e[n-t.startSN];i.cc===r.cc&&(s=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=uu(e,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:r,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:h}=s,u=i.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&l&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(r=r.concat(l),o=l.sn);let d;if(t<e){var A;const g=t<this.lastCurrentTime||t>e-h||(A=this.media)!=null&&A.paused||!this.startFragRequested?0:h;d=Ei(n,r,t,g)}else d=r[r.length-1];if(d){const f=d.sn-i.startSN,g=this.fragmentTracker.getState(d);if((g===$t.OK||g===$t.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!c||u[0].fragment.sn>d.sn||!i.live&&!c)&&n&&d.level===n.level){const p=r[f+1];d.sn<o&&this.fragmentTracker.getState(p)!==$t.OK?d=p:d=null}}return d}alignPlaylists(t,e,i){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,r=!e,o=t.alignedSliding&&j(n);if(r||!o&&!n){vy(i,t);const l=t.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),l}return n}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;i<e&&(i=-1);const s=this.timelineOffset;if(i===-1){const n=this.startTimeOffset!==null,r=n?this.startTimeOffset:t.startTimeOffset;r!==null&&j(r)?(i=e+r,r<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${r} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;const{media:e}=this;let i=0;return(t=this.hls)!=null&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&zt(t)&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==G.FRAG_LOADING_WAITING_RETRY)&&(this.state=G.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const f=this.getCurrentContext(e.chunkMeta);f&&(e.frag=f.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 n=e.details===b.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const r=e.errorAction,{action:o,flags:l,retryCount:h=0,retryConfig:u}=r||{},c=!!r&&!!u,d=c&&o===Jt.RetryRequest,A=c&&!r.resolved&&l===de.MoveAllAlternatesMatchingHost;if(!d&&A&&zt(i)&&!i.endList)this.resetFragmentErrors(t),this.treatAsGap(i),r.resolved=!0;else if((d||A)&&h<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const f=Ha(u,h);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${f}ms`),r.resolved=!0,this.retryDate=self.performance.now()+f,this.state=G.FRAG_LOADING_WAITING_RETRY}else if(u&&r)if(this.resetFragmentErrors(t),h<u.maxNumRetry)!n&&o!==Jt.RemoveAlternatePermanently&&(r.resolved=!0);else{this.warn(`${e.details} reached or exceeded max retry (${h})`);return}else o===Jt.SendAlternateToPenaltyBox?this.state=G.WAITING_LEVEL:this.state=G.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===G.PARSING||this.state===G.PARSED){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(e==null?void 0:e.duration)||10);const r=!n;return r&&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(),r}return!1}resetFragmentErrors(t){t===Z.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==G.STOPPED&&(this.state=G.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=ft.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===G.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==G.STOPPED&&(this.state=G.IDLE)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=t?t.details:null;e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${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){const n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((l,h)=>{const u=t.elementaryStreams[h];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${t.sn} ${h} duration reliably (${c})`),l||!1;const d=s?0:Eu(n,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(I.LEVEL_PTS_UPDATED,{details:n,level:i,drift:d,type:h,frag:t,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;if(i.fragmentError===0&&this.treatAsGap(t,i),((o=this.transmuxer)==null?void 0:o.error)===null){const l=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=G.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(I.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===Z.MAIN?"level":"track"}fragInfo(t,e=!0,i){var s,n;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${((s=e&&!i?t.startPTS:(i||t).start)!=null?s:NaN).toFixed(3)}-${((n=e&&!i?t.endPTS:(i||t).end)!=null?n:NaN).toFixed(3)}]${i&&t.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),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}}function sh(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class _u{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=Sy(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Sy(a,t){const e=new Uint8Array(t);let i=0;for(let s=0;s<a.length;s++){const n=a[s];e.set(n,i),i+=n.length}return e}var _r={exports:{}},nh;function Ty(){return nh||(nh=1,function(a){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(l,h,u){this.fn=l,this.context=h,this.once=u||!1}function n(l,h,u,c,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var A=new s(u,c||l,d),f=e?e+h:h;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],A]:l._events[f].push(A):(l._events[f]=A,l._eventsCount++),l}function r(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var h=[],u,c;if(this._eventsCount===0)return h;for(c in u=this._events)t.call(u,c)&&h.push(e?c.slice(1):c);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(u)):h},o.prototype.listeners=function(h){var u=e?e+h:h,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var d=0,A=c.length,f=new Array(A);d<A;d++)f[d]=c[d].fn;return f},o.prototype.listenerCount=function(h){var u=e?e+h:h,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(h,u,c,d,A,f){var g=e?e+h:h;if(!this._events[g])return!1;var m=this._events[g],p=arguments.length,C,E;if(m.fn){switch(m.once&&this.removeListener(h,m.fn,void 0,!0),p){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,c),!0;case 4:return m.fn.call(m.context,u,c,d),!0;case 5:return m.fn.call(m.context,u,c,d,A),!0;case 6:return m.fn.call(m.context,u,c,d,A,f),!0}for(E=1,C=new Array(p-1);E<p;E++)C[E-1]=arguments[E];m.fn.apply(m.context,C)}else{var y=m.length,v;for(E=0;E<y;E++)switch(m[E].once&&this.removeListener(h,m[E].fn,void 0,!0),p){case 1:m[E].fn.call(m[E].context);break;case 2:m[E].fn.call(m[E].context,u);break;case 3:m[E].fn.call(m[E].context,u,c);break;case 4:m[E].fn.call(m[E].context,u,c,d);break;default:if(!C)for(v=1,C=new Array(p-1);v<p;v++)C[v-1]=arguments[v];m[E].fn.apply(m[E].context,C)}}return!0},o.prototype.on=function(h,u,c){return n(this,h,u,c,!1)},o.prototype.once=function(h,u,c){return n(this,h,u,c,!0)},o.prototype.removeListener=function(h,u,c,d){var A=e?e+h:h;if(!this._events[A])return this;if(!u)return r(this,A),this;var f=this._events[A];if(f.fn)f.fn===u&&(!d||f.once)&&(!c||f.context===c)&&r(this,A);else{for(var g=0,m=[],p=f.length;g<p;g++)(f[g].fn!==u||d&&!f[g].once||c&&f[g].context!==c)&&m.push(f[g]);m.length?this._events[A]=m.length===1?m[0]:m:r(this,A)}return this},o.prototype.removeAllListeners=function(h){var u;return h?(u=e?e+h:h,this._events[u]&&r(this,u)):(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,a.exports=o}(_r)),_r.exports}var _y=Ty(),za=nC(_y);const Ts="1.6.2",$i={};function xy(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Dy(){const a=$i[Ts];if(a)return a.clientCount++,a;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t),s={worker:new self.Worker(e),objectURL:e,clientCount:1};return $i[Ts]=s,s}function Ry(a){const t=$i[a];if(t)return t.clientCount++,t;const e=new self.URL(a,self.location.href).href,s={worker:new self.Worker(e),scriptURL:e,clientCount:1};return $i[a]=s,s}function Ly(a){const t=$i[a||Ts];if(t&&t.clientCount--===1){const{worker:i,objectURL:s}=t;delete $i[a||Ts],s&&self.URL.revokeObjectURL(s),i.terminate()}}function xu(a,t){return t+10<=a.length&&a[t]===51&&a[t+1]===68&&a[t+2]===73&&a[t+3]<255&&a[t+4]<255&&a[t+6]<128&&a[t+7]<128&&a[t+8]<128&&a[t+9]<128}function qa(a,t){return t+10<=a.length&&a[t]===73&&a[t+1]===68&&a[t+2]===51&&a[t+3]<255&&a[t+4]<255&&a[t+6]<128&&a[t+7]<128&&a[t+8]<128&&a[t+9]<128}function Hn(a,t){let e=0;return e=(a[t]&127)<<21,e|=(a[t+1]&127)<<14,e|=(a[t+2]&127)<<7,e|=a[t+3]&127,e}function _s(a,t){const e=t;let i=0;for(;qa(a,t);){i+=10;const s=Hn(a,t+6);i+=s,xu(a,t+10)&&(i+=10),t+=i}if(i>0)return a.subarray(e,e+i)}function by(a,t,e,i){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=t[e+2],r=n>>2&15;if(r>12){const A=new Error(`invalid ADTS sampling index:${r}`);a.emit(I.ERROR,I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!0,error:A,reason:A.message});return}const o=(n>>6&3)+1,l=t[e+3]>>6&3|(n&1)<<2,h="mp4a.40."+o,u=s[r];let c=r;(o===5||o===29)&&(c-=3);const d=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return Et.log(`manifest codec:${i}, parsed codec:${h}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${r})`),{config:d,samplerate:u,channelCount:l,codec:h,parsedCodec:h,manifestCodec:i}}function Du(a,t){return a[t]===255&&(a[t+1]&246)===240}function Ru(a,t){return a[t+1]&1?7:9}function Xa(a,t){return(a[t+3]&3)<<11|a[t+4]<<3|(a[t+5]&224)>>>5}function wy(a,t){return t+5<a.length}function bn(a,t){return t+1<a.length&&Du(a,t)}function Py(a,t){return wy(a,t)&&Du(a,t)&&Xa(a,t)<=a.length-t}function My(a,t){if(bn(a,t)){const e=Ru(a,t);if(t+e>=a.length)return!1;const i=Xa(a,t);if(i<=e)return!1;const s=t+i;return s===a.length||bn(a,s)}return!1}function Lu(a,t,e,i,s){if(!a.samplerate){const n=by(t,e,i,s);if(!n)return;xt(a,n)}}function bu(a){return 1024*9e4/a}function Fy(a,t){const e=Ru(a,t);if(t+e<=a.length){const i=Xa(a,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function wu(a,t,e,i,s){const n=bu(a.samplerate),r=i+s*n,o=Fy(t,e);let l;if(o){const{frameLength:c,headerLength:d}=o,A=d+c,f=Math.max(0,e+A-t.length);f?(l=new Uint8Array(A-d),l.set(t.subarray(e+d,t.length),0)):l=t.subarray(e+d,e+A);const g={unit:l,pts:r};return f||a.samples.push(g),{sample:g,length:A,missing:f}}const h=t.length-e;return l=new Uint8Array(h),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:r},length:h,missing:-1}}function ky(a,t){return qa(a,t)&&Hn(a,t+6)+10<=a.length-t}function Oy(a){if(a.size<2)return;const t=ae(a.data,!0),e=new Uint8Array(a.data.subarray(t.length+1));return{key:a.type,info:t,data:e.buffer}}function Qy(a){if(a.size<2)return;if(a.type==="TXXX"){let e=1;const i=ae(a.data.subarray(e),!0);e+=i.length+1;const s=ae(a.data.subarray(e));return{key:a.type,info:i,data:s}}const t=ae(a.data.subarray(1));return{key:a.type,info:"",data:t}}function Uy(a){if(a.type==="WXXX"){if(a.size<2)return;let e=1;const i=ae(a.data.subarray(e),!0);e+=i.length+1;const s=ae(a.data.subarray(e));return{key:a.type,info:i,data:s}}const t=ae(a.data);return{key:a.type,info:"",data:t}}function Gy(a){return btoa(String.fromCharCode(...a))}function Pu(a,t){if(a<0)return-Pu(-a,t);const e=Math.pow(10,t);if(Math.abs(a*e%1-.5)<Number.EPSILON){const s=Math.floor(a*e);return(s%2===0?s:s+1)/e}else return Math.round(a*e)/e}function Ny(a,t){const e=new URL(a),i=new URL(t);if(e.origin!==i.origin)return a;const s=e.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function Hy(){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 n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(s=="x"?n:n&3|8).toString(16)})}}}function Ky(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function xr(a,t=0,e=1/0){return $y(a,t,e,Uint8Array)}function $y(a,t,e,i){const s=Yy(a);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const r=Vy(a)?a.byteOffset:0,o=(r+a.byteLength)/n,l=(r+t)/n,h=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(h+Math.max(e,0),o));return new i(s,h,u-h)}function Yy(a){return a instanceof ArrayBuffer?a:a.buffer}function Vy(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Jy(a){const t={key:a.type,description:"",data:"",mimeType:null,pictureType:null},e=3;if(a.size<2)return;if(a.data[0]!==e){console.log("Ignore frame with unrecognized character encoding");return}const i=a.data.subarray(1).indexOf(0);if(i===-1)return;const s=ae(xr(a.data,1,i)),n=a.data[2+i],r=a.data.subarray(3+i).indexOf(0);if(r===-1)return;const o=ae(xr(a.data,3+i,r));let l;return s==="-->"?l=ae(xr(a.data,4+i+r)):l=Ky(a.data.subarray(4+i+r)),t.mimeType=s,t.pictureType=n,t.description=o,t.data=l,t}function zy(a){return a.type==="PRIV"?Oy(a):a.type[0]==="W"?Uy(a):a.type==="APIC"?Jy(a):Qy(a)}function qy(a){const t=String.fromCharCode(a[0],a[1],a[2],a[3]),e=Hn(a,4),i=10;return{type:t,size:e,data:a.subarray(i,i+e)}}const Zs=10,Xy=10;function Mu(a){let t=0;const e=[];for(;qa(a,t);){const i=Hn(a,t+6);a[t+5]>>6&1&&(t+=Zs),t+=Zs;const s=t+i;for(;t+Xy<s;){const n=qy(a.subarray(t)),r=zy(n);r&&e.push(r),t+=n.size+Zs}xu(a,t)&&(t+=Zs)}return e}function Fu(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Wy(a){if(a.data.byteLength===8){const t=new Uint8Array(a.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)}}function Wa(a){const t=Mu(a);for(let e=0;e<t.length;e++){const i=t[e];if(Fu(i))return Wy(i)}}let se=function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a}({});function be(a="",t=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ja{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=fe(this.cachedData,t),this.cachedData=null);let i=_s(t,0),s=i?i.length:0,n;const r=this._audioTrack,o=this._id3Track,l=i?Wa(i):void 0,h=t.length;for((this.basePTS===null||this.frameIndex===0&&j(l))&&(this.basePTS=jy(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:se.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(t,s)){const u=this.appendFrame(r,t,s);u?(this.frameIndex++,this.lastPTS=u.sample.pts,s+=u.length,n=s):s=h}else ky(t,s)?(i=_s(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:se.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===h&&n!==h){const u=t.slice(n);this.cachedData?this.cachedData=fe(this.cachedData,u):this.cachedData=u}}return{audioTrack:r,videoTrack:be(),id3Track:o,textTrack:be()}}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:be(),id3Track:this._id3Track,textTrack:be()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const jy=(a,t,e)=>{if(j(a))return a*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};let tn=null;const Zy=[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],tv=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ev=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],iv=[0,1,1,4];function ku(a,t,e,i,s){if(e+24>t.length)return;const n=Ou(t,e);if(n&&e+n.frameLength<=t.length){const r=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*r,l={unit:t.subarray(e,e+n.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=n.channelCount,a.samplerate=n.sampleRate,a.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Ou(a,t){const e=a[t+1]>>3&3,i=a[t+1]>>1&3,s=a[t+2]>>4&15,n=a[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&n!==3){const r=a[t+2]>>1&1,o=a[t+3]>>6,l=e===3?3-i:i===3?3:4,h=Zy[l*14+s-1]*1e3,c=tv[(e===3?0:e===2?1:2)*3+n],d=o===3?1:2,A=ev[e][i],f=iv[i],g=A*8*f,m=Math.floor(A*h/c+r)*f;if(tn===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);tn=E?parseInt(E[1]):0}return!!tn&&tn<=87&&i===2&&h>=224e3&&o===0&&(a[t+3]=a[t+3]|128),{sampleRate:c,channelCount:d,frameLength:m,samplesPerFrame:g}}}function Za(a,t){return a[t]===255&&(a[t+1]&224)===224&&(a[t+1]&6)!==0}function Qu(a,t){return t+1<a.length&&Za(a,t)}function sv(a,t){return Za(a,t)&&4<=a.length-t}function Uu(a,t){if(t+1<a.length&&Za(a,t)){const i=Ou(a,t);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=t+s;return n===a.length||Qu(a,n)}return!1}class nv extends ja{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,e){if(!t)return!1;const i=_s(t,0);let s=(i==null?void 0:i.length)||0;if(Uu(t,s))return!1;for(let n=t.length;s<n;s++)if(My(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return Py(t,e)}appendFrame(t,e,i){Lu(t,this.observer,e,i,t.manifestCodec);const s=wu(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const Gu=(a,t)=>{let e=0,i=5;t+=i;const s=new Uint32Array(1),n=new Uint32Array(1),r=new Uint8Array(1);for(;i>0;){r[0]=a[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(r[0]&n[0])>>l,e=e?e<<o|s[0]:s[0],t+=1,i-=o}return e};class rv extends ja{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=Nu(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=_s(t,0);if(!e)return!1;const i=e.length;return t[i]===11&&t[i+1]===119&&Wa(e)!==void 0&&Gu(t,i)<16}}function Nu(a,t,e,i,s){if(e+8>t.length||t[e]!==11||t[e+1]!==119)return-1;const n=t[e+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],l=t[e+4]&63,u=[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+n]*2;if(e+u>t.length)return-1;const c=t[e+6]>>5;let d=0;c===2?d+=2:(c&1&&c!==1&&(d+=2),c&4&&(d+=2));const A=(t[e+6]<<8|t[e+7])>>12-d&1,g=[2,1,2,3,3,4,4,5][c]+A,m=t[e+5]>>3,p=t[e+5]&7,C=new Uint8Array([n<<6|m<<1|p>>2,(p&3)<<6|c<<3|A<<2|l>>4,l<<4&224]),E=1536/o*9e4,y=i+s*E,v=t.subarray(e,e+u);return a.config=C,a.channelCount=g,a.samplerate=o,a.samples.push({unit:v,pts:y}),u}class av extends ja{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=_s(t,0);let i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&Wa(e)!==void 0&&Gu(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(Uu(t,i))return Et.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return sv(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return ku(t,e,i,this.basePTS,this.frameIndex)}}const ov=/\/emsg[-/]ID3/i;class lv{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 n=this.videoTrack=be("video",1),r=this.audioTrack=be("audio",1),o=this.txtTrack=be("text",1);if(this.id3Track=be("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=Zc(t);if(l.video){const{id:h,timescale:u,codec:c,supplemental:d}=l.video;n.id=h,n.timescale=o.timescale=u,n.codec=c,n.supplemental=d}if(l.audio){const{id:h,timescale:u,codec:c}=l.audio;r.id=h,r.timescale=u,r.codec=c}o.id=Xc.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return lC(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=fe(this.remainderData,t));const o=mC(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const r=this.extractID3Track(s,e);return n.samples=_l(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:r,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=_l(t,e),{videoTrack:e,audioTrack:be(),id3Track:s,textTrack:be()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=ct(t.samples,["emsg"]);s&&s.forEach(n=>{const r=EC(n);if(ov.test(r.schemeIdUri)){const o=rh(r,e);let l=r.eventDuration===4294967295?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=r.payload;i.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:se.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=rh(r,e);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:o,pts:o,type:se.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function rh(a,t){return j(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale}class hv{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ka(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,ni.cbc)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).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 n=32;n<t.length-16;n+=160,s+=16)i.set(t.subarray(n,n+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let n=32;n<t.length-16;n+=160,s+=16)t.set(i.subarray(s,s+16),n);return t}decryptAvcSample(t,e,i,s,n){const r=eu(n.data),o=this.getAvcEncryptedData(r);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(r,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 n=t[e].units;for(;!(i>=n.length);i++){const r=n[i];if(!(r.data.length<=48||r.type!==1&&r.type!==5)&&(this.decryptAvcSample(t,e,i,s,r),!this.decrypter.isSync()))return}}}}class Hu{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],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 n=i.units;s=n[n.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 n=i[s-1];t.pts=n.pts,t.dts=n.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;let n=t.naluState||0;const r=n,o=[];let l=0,h,u,c,d=-1,A=0;for(n===-1&&(d=0,A=this.getNALuType(e,0),n=0,l=1);l<s;){if(h=e[l++],!n){n=h?0:1;continue}if(n===1){n=h?0:2;continue}if(!h)n=3;else if(h===1){if(u=l-n-1,d>=0){const f={data:e.subarray(d,u),type:A};o.push(f)}else{const f=this.getLastNalUnit(t.samples);f&&(r&&l<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),u>0&&(f.data=fe(f.data,e.subarray(0,u)),f.state=0))}l<s?(c=this.getNALuType(e,l),d=l,A=c,n=0):n=-1}else n=0}if(d>=0&&n>=0){const f={data:e.subarray(d,s),type:A,state:n};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(t.samples);f&&(f.data=fe(f.data,e))}return t.naluState=n,o}}class ys{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),n=Math.min(4,e);if(n===0)throw new Error("no bytes available");s.set(t.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}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&&Et.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)}}class ah extends Hu{parsePES(t,e,i,s){const n=this.parseNALu(t,i.data,s);let r=this.VideoSample,o,l=!1;i.data=null,r&&n.length&&!t.audFound&&(this.pushAccessUnit(r,t),r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(h=>{var u,c;switch(h.type){case 1:{let g=!1;o=!0;const m=h.data;if(l&&m.length>4){const p=this.readSliceType(m);(p===2||p===4||p===7||p===9)&&(g=!0)}if(g){var d;(d=r)!=null&&d.frame&&!r.key&&(this.pushAccessUnit(r,t),r=this.VideoSample=null)}r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.frame=!0,r.key=g;break}case 5:o=!0,(u=r)!=null&&u.frame&&!r.key&&(this.pushAccessUnit(r,t),r=this.VideoSample=null),r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.key=!0,r.frame=!0;break;case 6:{o=!0,Ga(h.data,1,i.pts,e.samples);break}case 7:{var A,f;o=!0,l=!0;const g=h.data,m=this.readSPS(g);if(!t.sps||t.width!==m.width||t.height!==m.height||((A=t.pixelRatio)==null?void 0:A[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];const p=g.subarray(1,4);let C="avc1.";for(let E=0;E<3;E++){let y=p[E].toString(16);y.length<2&&(y="0"+y),C+=y}t.codec=C}break}case 8:o=!0,t.pps=[h.data];break;case 9:o=!0,t.audFound=!0,(c=r)!=null&&c.frame&&(this.pushAccessUnit(r,t),r=null),r||(r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}r&&o&&r.units.push(h)}),s&&r&&(this.pushAccessUnit(r,t),this.VideoSample=null)}getNALuType(t,e){return t[e]&31}readSliceType(t){const e=new ys(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i=8,s=8,n;for(let r=0;r<t;r++)s!==0&&(n=e.readEG(),s=(i+n+256)%256),i=s===0?i:s}readSPS(t){const e=new ys(t);let i=0,s=0,n=0,r=0,o,l,h;const u=e.readUByte.bind(e),c=e.readBits.bind(e),d=e.readUEG.bind(e),A=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);u();const C=u();if(c(5),f(3),u(),m(),C===100||C===110||C===122||C===244||C===44||C===83||C===86||C===118||C===128){const _=d();if(_===3&&f(1),m(),m(),f(1),A())for(l=_!==3?8:12,h=0;h<l;h++)A()&&(h<6?p(16,e):p(64,e))}m();const E=d();if(E===0)d();else if(E===1)for(f(1),g(),g(),o=d(),h=0;h<o;h++)g();m(),f(1);const y=d(),v=d(),T=c(1);T===0&&f(1),f(1),A()&&(i=d(),s=d(),n=d(),r=d());let B=[1,1];if(A()&&A())switch(u()){case 1:B=[1,1];break;case 2:B=[12,11];break;case 3:B=[10,11];break;case 4:B=[16,11];break;case 5:B=[40,33];break;case 6:B=[24,11];break;case 7:B=[20,11];break;case 8:B=[32,11];break;case 9:B=[80,33];break;case 10:B=[18,11];break;case 11:B=[15,11];break;case 12:B=[64,33];break;case 13:B=[160,99];break;case 14:B=[4,3];break;case 15:B=[3,2];break;case 16:B=[2,1];break;case 255:{B=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((y+1)*16-i*2-s*2),height:(2-T)*(v+1)*16-(T?2:4)*(n+r),pixelRatio:B}}}class oh extends Hu{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const n=this.parseNALu(t,i.data,s);let r=this.VideoSample,o,l=!1;i.data=null,r&&n.length&&!t.audFound&&(this.pushAccessUnit(r,t),r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(h=>{var u,c;switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:r||(r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var d;(d=r)!=null&&d.frame&&!r.key&&(this.pushAccessUnit(r,t),r=this.VideoSample=null)}r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.key=!0,r.frame=!0;break;case 19:case 20:o=!0,(u=r)!=null&&u.frame&&!r.key&&(this.pushAccessUnit(r,t),r=this.VideoSample=null),r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.key=!0,r.frame=!0;break;case 39:o=!0,Ga(h.data,2,i.pts,e.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=xt(t.params,this.readVPS(h.data)),this.initVPS=h.data),t.vps=[h.data];break;case 33:if(o=!0,l=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],h.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const A=this.readSPS(h.data);t.width=A.width,t.height=A.height,t.pixelRatio=A.pixelRatio,t.codec=A.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const f in A.params)t.params[f]=A.params[f]}this.pushParameterSet(t.sps,h.data,t.vps),r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const A=this.readPPS(h.data);for(const f in A)t.params[f]=A[f]}this.pushParameterSet(t.pps,h.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(c=r)!=null&&c.frame&&(this.pushAccessUnit(r,t),r=null),r||(r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}r&&o&&r.units.push(h)}),s&&r&&(this.pushAccessUnit(r,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(t[e]&126)>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&t[s]===3&&t[s-1]===0&&t[s-2]===0||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ys(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);const i=e.readBits(3),s=e.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(t){const e=new ys(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),n=e.readBoolean(),r=e.readBits(5),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),u=e.readUByte(),c=e.readUByte(),d=e.readUByte(),A=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),C=[],E=[];for(let Ct=0;Ct<i;Ct++)C.push(e.readBoolean()),E.push(e.readBoolean());if(i>0)for(let Ct=i;Ct<8;Ct++)e.readBits(2);for(let Ct=0;Ct<i;Ct++)C[Ct]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),E[Ct]&&e.readUByte();e.readUEG();const y=e.readUEG();y==3&&e.skipBits(1);const v=e.readUEG(),T=e.readUEG(),B=e.readBoolean();let _=0,D=0,x=0,M=0;B&&(_+=e.readUEG(),D+=e.readUEG(),x+=e.readUEG(),M+=e.readUEG());const k=e.readUEG(),X=e.readUEG(),W=e.readUEG(),H=e.readBoolean();for(let Ct=H?0:i;Ct<=i;Ct++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(let Xt=0;Xt<4;Xt++)for(let oe=0;oe<(Xt===3?2:6);oe++)if(!e.readBoolean())e.readUEG();else{const ge=Math.min(64,1<<4+(Xt<<1));Xt>1&&e.readEG();for(let Ii=0;Ii<ge;Ii++)e.readEG()}e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const J=e.readUEG();let U=0;for(let Ct=0;Ct<J;Ct++){let Xt=!1;if(Ct!==0&&(Xt=e.readBoolean()),Xt){Ct===J&&e.readUEG(),e.readBoolean(),e.readUEG();let oe=0;for(let ri=0;ri<=U;ri++){const ge=e.readBoolean();let Ii=!1;ge||(Ii=e.readBoolean()),(ge||Ii)&&oe++}U=oe}else{const oe=e.readUEG(),ri=e.readUEG();U=oe+ri;for(let ge=0;ge<oe;ge++)e.readUEG(),e.readBoolean();for(let ge=0;ge<ri;ge++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const Ct=e.readUEG();for(let Xt=0;Xt<Ct;Xt++){for(let oe=0;oe<W+4;oe++)e.readBits(1);e.readBits(1)}}let N=0,K=1,$=1,R=!0,tt=1,it=0;e.readBoolean(),e.readBoolean();let lt=!1;if(e.readBoolean()){if(e.readBoolean()){const ai=e.readUByte(),ao=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],bs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ai>0&&ai<16?(K=ao[ai-1],$=bs[ai-1]):ai===255&&(K=e.readBits(16),$=e.readBits(16))}if(e.readBoolean()&&e.readBoolean(),e.readBoolean()&&(e.readBits(3),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())),e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),lt=e.readBoolean(),lt&&(_+=e.readUEG(),D+=e.readUEG(),x+=e.readUEG(),M+=e.readUEG()),e.readBoolean()&&(tt=e.readBits(32),it=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){const bs=e.readBoolean(),oo=e.readBoolean();let qi=!1;(bs||oo)&&(qi=e.readBoolean(),qi&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),qi&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let lo=0;lo<=i;lo++){R=e.readBoolean();const Ud=R||e.readBoolean();let ho=!1;Ud?e.readEG():ho=e.readBoolean();const co=ho?1:e.readUEG()+1;if(bs)for(let Xi=0;Xi<co;Xi++)e.readUEG(),e.readUEG(),qi&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(oo)for(let Xi=0;Xi<co;Xi++)e.readUEG(),e.readUEG(),qi&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),N=e.readUEG())}let qt=v,Xe=T;if(B||lt){let Ct=1,Xt=1;y===1?Ct=Xt=2:y==2&&(Ct=2),qt=v-Ct*D-Ct*_,Xe=T-Xt*M-Xt*x}const zi=s?["A","B","C"][s]:"",Qd=o<<24|l<<16|h<<8|u;let Vn=0;for(let Ct=0;Ct<32;Ct++)Vn=(Vn|(Qd>>Ct&1)<<31-Ct)>>>0;let Jn=Vn.toString(16);return r===1&&Jn==="2"&&(Jn="6"),{codecString:`hvc1.${zi}${r}.${Jn}.${n?"H":"L"}${p}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[o,l,h,u],general_constraint_indicator_flags:[c,d,A,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:X,min_spatial_segmentation_idc:N,chroma_format_idc:y,frame_rate:{fixed:R,fps:it/tt}},width:qt,height:Xe,pixelRatio:[K,$]}}readPPS(t){const e=new ys(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2),e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),n=e.readBoolean();let r=1;return n&&s?r=0:n?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Vt=188;class ei{constructor(t,e,i,s){this.logger=void 0,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._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.logger=s,this.videoParser=null}static probe(t,e){const i=ei.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(t){const e=t.length;let i=Math.min(Vt*5,e-Vt)+1,s=0;for(;s<i;){let n=!1,r=-1,o=0;for(let l=s;l<e;l+=Vt)if(t[l]===71&&(e-l===Vt||t[l+Vt]===71)){if(o++,r===-1&&(r=l,r!==0&&(i=Math.min(r+Vt*99,t.length-Vt)+1)),n||(n=ca(t,l)===0),n&&o>1&&(r===0&&o>2||l+Vt>i))return r}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:Xc[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._videoTrack.duration=s,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}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 n;const r=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack;let u=r.pid,c=r.pesData,d=o.pid,A=l.pid,f=o.pesData,g=l.pesData,m=null,p=this.pmtParsed,C=this._pmtId,E=t.length;if(this.remainderData&&(t=fe(this.remainderData,t),E=t.length,this.remainderData=null),E<Vt&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:r,id3Track:l,textTrack:h};const y=Math.max(0,ei.syncOffset(t));E-=(E-y)%Vt,E<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));let v=0;for(let B=y;B<E;B+=Vt)if(t[B]===71){const _=!!(t[B+1]&64),D=ca(t,B),x=(t[B+3]&48)>>4;let M;if(x>1){if(M=B+5+t[B+4],M===B+Vt)continue}else M=B+4;switch(D){case u:if(_){if(c&&(n=bi(c,this.logger))){if(this.videoParser===null)switch(r.segmentCodec){case"avc":this.videoParser=new ah;break;case"hevc":this.videoParser=new oh;break}this.videoParser!==null&&this.videoParser.parsePES(r,h,n,!1)}c={data:[],size:0}}c&&(c.data.push(t.subarray(M,B+Vt)),c.size+=B+Vt-M);break;case d:if(_){if(f&&(n=bi(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}f={data:[],size:0}}f&&(f.data.push(t.subarray(M,B+Vt)),f.size+=B+Vt-M);break;case A:_&&(g&&(n=bi(g,this.logger))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(M,B+Vt)),g.size+=B+Vt-M);break;case 0:_&&(M+=t[M]+1),C=this._pmtId=cv(t,M);break;case C:{_&&(M+=t[M]+1);const k=uv(t,M,this.typeSupported,i,this.observer,this.logger);u=k.videoPid,u>0&&(r.pid=u,r.segmentCodec=k.segmentVideoCodec),d=k.audioPid,d>0&&(o.pid=d,o.segmentCodec=k.segmentAudioCodec),A=k.id3Pid,A>0&&(l.pid=A),m!==null&&!p&&(this.logger.warn(`MPEG-TS PMT found at ${B} after unknown PID '${m}'. Backtracking to sync byte @${y} to parse all TS packets.`),m=null,B=y-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=D;break}}else v++;v>0&&ua(this.observer,new Error(`Found ${v} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=c,o.pesData=f,l.pesData=g;const T={audioTrack:o,videoTrack:r,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(T),T}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:n}=t,r=i.pesData,o=e.pesData,l=s.pesData;let h;if(r&&(h=bi(r,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new ah;break;case"hevc":this.videoParser=new oh;break}this.videoParser!==null&&(this.videoParser.parsePES(i,n,h,!0),i.pesData=null)}else i.pesData=r;if(o&&(h=bi(o,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,h);break;case"mp3":this.parseMPEGPES(e,h);break;case"ac3":this.parseAC3PES(e,h);break}e.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;l&&(h=bi(l,this.logger))?(this.parseID3PES(s,h),s.pesData=null):s.pesData=l}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new hv(this.observer,this.config,e);return this.decrypt(s,n)}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&e.decryptAvcSamples(n.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let n=e.data;if(s){this.aacOverFlow=null;const c=s.missing,d=s.sample.unit.byteLength;if(c===-1)n=fe(s.sample.unit,n);else{const A=d-c;s.sample.unit.set(n.subarray(0,c),A),t.samples.push(s.sample),i=s.missing}}let r,o;for(r=i,o=n.length;r<o-1&&!bn(n,r);r++);if(r!==i){let c;const d=r<o-1;if(d?c=`AAC PES did not start with ADTS header,offset:${r}`:c="No ADTS header found in AAC PES",ua(this.observer,new Error(c),d,this.logger),!d)return}Lu(t,this.observer,n,r,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(s){const c=bu(t.samplerate);l=s.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,u;for(;r<o;)if(u=wu(t,n,r,l,h),r+=u.length,u.missing){this.aacOverFlow=u;break}else for(h++;r<o-1&&!bn(n,r);r++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let n=0,r=0;const o=e.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;r<s;)if(Qu(i,r)){const l=ku(t,i,r,o,n);if(l)r+=l.length,n++;else break}else r++}parseAC3PES(t,e){{const i=e.data,s=e.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let r=0,o=0,l;for(;o<n&&(l=Nu(t,i,o,s,r++))>0;)o+=l}}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=xt({},e,{type:this._videoTrack?se.emsg:se.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function ca(a,t){return((a[t+1]&31)<<8)+a[t+2]}function cv(a,t){return(a[t+10]&31)<<8|a[t+11]}function uv(a,t,e,i,s,n){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[t+1]&15)<<8|a[t+2],l=t+3+o-4,h=(a[t+10]&15)<<8|a[t+11];for(t+=12+h;t<l;){const u=ca(a,t),c=(a[t+3]&15)<<8|a[t+4];switch(a[t]){case 207:if(!i){Dr("ADTS AAC",n);break}case 15:r.audioPid===-1&&(r.audioPid=u);break;case 21:r.id3Pid===-1&&(r.id3Pid=u);break;case 219:if(!i){Dr("H.264",n);break}case 27:r.videoPid===-1&&(r.videoPid=u);break;case 3:case 4:!e.mpeg&&!e.mp3?n.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=u,r.segmentAudioCodec="mp3");break;case 193:if(!i){Dr("AC-3",n);break}case 129:e.ac3?r.audioPid===-1&&(r.audioPid=u,r.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&c>0){let d=t+5,A=c;for(;A>2;){switch(a[d]){case 106:e.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=u,r.segmentAudioCodec="ac3");break}const g=a[d+1]+2;d+=g,A-=g}}break;case 194:case 135:return ua(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),r;case 36:r.videoPid===-1&&(r.videoPid=u,r.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}t+=c+5}return r}function ua(a,t,e,i){i.warn(`parsing error: ${t.message}`),a.emit(I.ERROR,I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:t,reason:t.message})}function Dr(a,t){t.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function bi(a,t){let e=0,i,s,n,r,o;const l=a.data;if(!a||a.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=fe(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>a.size-6)return null;const u=i[7];u&192&&(r=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,r-o>60*9e4&&(t.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),n=i[8];let c=n+9;if(a.size<=c)return null;a.size-=c;const d=new Uint8Array(a.size);for(let A=0,f=l.length;A<f;A++){i=l[A];let g=i.byteLength;if(c)if(c>g){c-=g;continue}else i=i.subarray(c),g-=c,c=0;d.set(i,e),e+=g}return s&&(s-=n+3),{data:d,pts:r,dts:o,len:s}}return null}class dv{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 We=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],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]),n=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=n,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 r=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,r,l,r,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 n=s;for(;s--;)i+=e[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(t,4),s=0,i=8;s<n;s++)r.set(e[s],i),i+=e[s].byteLength;return r}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/(We+1)),s=Math.floor(e%(We+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||0,t.duration||0),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||0,t[0].duration||0)].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/(We+1)),s=Math.floor(e%(We+1)),n=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,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,n;for(s=0;s<e.length;s++)n=e[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.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,n,r;for(s=0;s<t.sps.length;s++)n=t.sps[s],r=n.byteLength,e.push(r>>>8&255),e.push(r&255),e=e.concat(Array.prototype.slice.call(n));for(s=0;s<t.pps.length;s++)n=t.pps[s],r=n.byteLength,i.push(r>>>8&255),i.push(r&255),i=i.concat(Array.prototype.slice.call(n));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,h=t.height,u=t.pixelRatio[0],c=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,h>>8&255,h&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([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,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){const{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(t));if(e==="ac3"&&t.config)return L.box(L.types.stsd,L.STSD,L.ac3(t));if(e==="mp3"&&t.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(t));if(e==="hevc"&&t.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,r=Math.floor(i/(We+1)),o=Math.floor(i%(We+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,r>>24,r>>16&255,r>>8&255,r&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,n>>8&255,n&255,0,0]))}static traf(t,e){const i=L.sdtp(t),s=t.id,n=Math.floor(e/(We+1)),r=Math.floor(e%(We+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,n>>24,n>>16&255,n>>8&255,n&255,r>>24,r>>16&255,r>>8&255,r&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,n=12+16*s,r=new Uint8Array(n);let o,l,h,u,c,d;for(e+=8+n,r.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],h=l.duration,u=l.size,c=l.flags,d=l.cts,r.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,r)}static initSegment(t){L.types||L.init();const e=L.moov(t);return fe(L.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=4,n=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),s-1|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=n.length;for(let f=0;f<i.length;f+=1){r+=3;for(let g=0;g<i[f].length;g+=1)r+=2+i[f][g].length}const o=new Uint8Array(r);o.set(n,0),r=n.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){o.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),r),r+=3;for(let g=0;g<i[f].length;g+=1)o.set(new Uint8Array([i[f][g].length>>8,i[f][g].length&255]),r),r+=2,o.set(i[f][g],r),r+=i[f][g].length}const h=L.box(L.types.hvcC,o),u=t.width,c=t.height,d=t.pixelRatio[0],A=t.pixelRatio[1];return L.box(L.types.hvc1,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,u>>8&255,u&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]),h,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([d>>24,d>>16&255,d>>8&255,d&255,A>>24,A>>16&255,A>>8&255,A&255])))}}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 Ku=9e4;function to(a,t,e=1,i=!1){const s=a*t*e;return i?Math.round(s):s}function Av(a,t,e=1,i=!1){return to(a,t,1/e,i)}function ds(a,t=!1){return to(a,1e3,1/Ku,t)}function fv(a,t=1){return to(a,Ku,1/t)}const gv=10*1e3,mv=1024,pv=1152,Ev=1536;let wi=null,Rr=null;function lh(a,t,e,i){return{duration:t,size:e,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class dn{constructor(t,e,i,s){if(this.logger=void 0,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.logger=s,this.ISGenerated=!1,wi===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);wi=r?parseInt(r[1]):0}if(Rr===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);Rr=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.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((n,r)=>{let o=r.pts,l=o-n;return l<-4294967296&&(e=!0,o=Ae(o,i),l=o-n),l>0?n:o},i);return e&&this.logger.debug("PTS rollover detected"),s}remux(t,e,i,s,n,r,o,l){let h,u,c,d,A,f,g=n,m=n;const p=t.pid>-1,C=e.pid>-1,E=e.samples.length,y=t.samples.length>0,v=o&&E>0||E>1;if((!p||y)&&(!C||v)||this.ISGenerated||o){if(this.ISGenerated){var B,_,D,x;const W=this.videoTrackConfig;(W&&(e.width!==W.width||e.height!==W.height||((B=e.pixelRatio)==null?void 0:B[0])!==((_=W.pixelRatio)==null?void 0:_[0])||((D=e.pixelRatio)==null?void 0:D[1])!==((x=W.pixelRatio)==null?void 0:x[1]))||!W&&v||this.nextAudioPts===null&&y)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,n,r));const M=this.isVideoContiguous;let k=-1,X;if(v&&(k=Iv(e.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,k>0){this.logger.warn(`[mp4-remuxer]: Dropped ${k} out of ${E} video samples due to a missing keyframe`);const W=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(k),e.dropped+=k,m+=(e.samples[0].pts-W)/e.inputTimeScale,X=m}else k===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(y&&v){const W=this.getVideoStartPts(e.samples),Y=(Ae(t.samples[0].pts,W)-W)/e.inputTimeScale;g+=Math.max(0,Y),m+=Math.max(0,-Y)}if(y){if(t.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,e,n,r)),u=this.remuxAudio(t,g,this.isAudioContiguous,r,C||v||l===Z.AUDIO?m:void 0),v){const W=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,e,n,r)),h=this.remuxVideo(e,m,M,W)}}else v&&(h=this.remuxVideo(e,m,M,0));h&&(h.firstKeyFrame=k,h.independent=k!==-1,h.firstKeyFramePTS=X)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(A=$u(i,n,this._initPTS,this._initDTS)),s.samples.length&&(d=Yu(s,n,this._initPTS))),{audio:u,video:h,initSegment:c,independent:f,text:d,id3:A}}generateIS(t,e,i,s){const n=t.samples,r=e.samples,o=this.typeSupported,l={},h=this._initPTS;let u=!h||s,c="audio/mp4",d,A,f;if(u&&(d=A=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}l.audio={id:"audio",container:c,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(f=t.inputTimeScale,!h||f!==h.timescale?d=A=n[0].pts-Math.round(f*i):u=!1)}if(e.sps&&e.pps&&r.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}},u)if(f=e.inputTimeScale,!h||f!==h.timescale){const g=this.getVideoStartPts(r),m=Math.round(f*i);A=Math.min(A,Ae(r[0].dts,g)-m),d=Math.min(d,g-m)}else u=!1;this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:f},this._initDTS={baseTime:A,timescale:f}):d=f=void 0,{tracks:l,initPTS:d,timescale:f}}remuxVideo(t,e,i,s){const n=t.inputTimeScale,r=t.samples,o=[],l=r.length,h=this._initPTS;let u=this.nextAvcDts,c=8,d=this.videoSampleDuration,A,f,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||u===null){const U=e*n,F=r[0].pts-Ae(r[0].dts,r[0].pts);wi&&u!==null&&Math.abs(U-F-u)<15e3?i=!0:u=U-F}const C=h.baseTime*n/h.timescale;for(let U=0;U<l;U++){const F=r[U];F.pts=Ae(F.pts-C,u),F.dts=Ae(F.dts-C,u),F.dts<r[U>0?U-1:U].dts&&(p=!0)}p&&r.sort(function(U,F){const N=U.dts-F.dts,K=U.pts-F.pts;return N||K}),A=r[0].dts,f=r[r.length-1].dts;const E=f-A,y=E?Math.round(E/(l-1)):d||t.inputTimeScale/30;if(i){const U=A-u,F=U>y,N=U<-1;if((F||N)&&(F?this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ds(U,!0)} ms (${U}dts) hole between fragments detected at ${e.toFixed(3)}`):this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ds(-U,!0)} ms (${U}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!N||u>=r[0].pts||wi)){A=u;const K=r[0].pts-U;if(F)r[0].dts=A,r[0].pts=K;else{let $=!0;for(let R=0;R<r.length&&!(r[R].dts>K&&$);R++){const tt=r[R].pts;if(r[R].dts-=U,r[R].pts-=U,R<r.length-1){const it=r[R+1].pts,lt=r[R].pts,Dt=it<=lt,qt=it<=tt;$=Dt==qt}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${ds(K,!0)}/${ds(A,!0)}, delta: ${ds(U,!0)} ms`)}}A=Math.max(0,A);let v=0,T=0,B=A;for(let U=0;U<l;U++){const F=r[U],N=F.units,K=N.length;let $=0;for(let R=0;R<K;R++)$+=N[R].data.length;T+=$,v+=K,F.length=$,F.dts<B?(F.dts=B,B+=y/4|0||1):B=F.dts,g=Math.min(F.pts,g),m=Math.max(F.pts,m)}f=r[l-1].dts;const _=T+4*v+8;let D;try{D=new Uint8Array(_)}catch(U){this.observer.emit(I.ERROR,I.ERROR,{type:et.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:_,reason:`fail allocating video mdat ${_}`});return}const x=new DataView(D.buffer);x.setUint32(0,_),D.set(L.types.mdat,4);let M=!1,k=Number.POSITIVE_INFINITY,X=Number.POSITIVE_INFINITY,W=Number.NEGATIVE_INFINITY,H=Number.NEGATIVE_INFINITY;for(let U=0;U<l;U++){const F=r[U],N=F.units;let K=0;for(let tt=0,it=N.length;tt<it;tt++){const lt=N[tt],Dt=lt.data,qt=lt.data.byteLength;x.setUint32(c,qt),c+=4,D.set(Dt,c),c+=qt,K+=4+qt}let $;if(U<l-1)d=r[U+1].dts-F.dts,$=r[U+1].pts-F.pts;else{const tt=this.config,it=U>0?F.dts-r[U-1].dts:y;if($=U>0?F.pts-r[U-1].pts:y,tt.stretchShortVideoTrack&&this.nextAudioPts!==null){const lt=Math.floor(tt.maxBufferHole*n),Dt=(s?g+s*n:this.nextAudioPts)-F.pts;Dt>lt?(d=Dt-it,d<0?d=it:M=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${Dt/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=it}else d=it}const R=Math.round(F.pts-F.dts);k=Math.min(k,d),W=Math.max(W,d),X=Math.min(X,$),H=Math.max(H,$),o.push(lh(F.key,d,K,R))}if(o.length){if(wi){if(wi<70){const U=o[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(Rr&&H-X<W-k&&y/W<.025&&o[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=A;for(let F=0,N=o.length;F<N;F++){const K=U+o[F].duration,$=U+o[F].cts;if(F<N-1){const R=K+o[F+1].cts;o[F].duration=R-$}else o[F].duration=F?o[F-1].duration:y;o[F].cts=0,U=K}}}d=M||!d?y:d,this.nextAvcDts=u=f+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const J={data1:L.moof(t.sequenceNumber++,A,xt(t,{samples:o})),data2:D,startPTS:g/n,endPTS:(m+d)/n,startDTS:A/n,endDTS:u/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,J}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return pv;case"ac3":return Ev;default:return mv}}remuxAudio(t,e,i,s,n){const r=t.inputTimeScale,o=t.samplerate?t.samplerate:r,l=r/o,h=this.getSamplesPerFrame(t),u=h*l,c=this._initPTS,d=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,A=[],f=n!==void 0;let g=t.samples,m=d?0:8,p=this.nextAudioPts||-1;const C=e*r,E=c.baseTime*r/c.timescale;if(this.isAudioContiguous=i=i||g.length&&p>0&&(s&&Math.abs(C-p)<9e3||Math.abs(Ae(g[0].pts-E,C)-p)<20*u),g.forEach(function(Y){Y.pts=Ae(Y.pts-E,C)}),!i||p<0){if(g=g.filter(Y=>Y.pts>=0),!g.length)return;n===0?p=0:s&&!f?p=Math.max(0,C):p=g[0].pts}if(t.segmentCodec==="aac"){const Y=this.config.maxAudioFramesDrift;for(let z=0,J=p;z<g.length;z++){const U=g[z],F=U.pts,N=F-J,K=Math.abs(1e3*N/r);if(N<=-Y*u&&f)z===0&&(this.logger.warn(`Audio frame @ ${(F/r).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*N/r)} ms.`),this.nextAudioPts=p=J=F);else if(N>=Y*u&&K<gv&&f){let $=Math.round(N/u);J=F-$*u,J<0&&($--,J+=u),z===0&&(this.nextAudioPts=p=J),this.logger.warn(`[mp4-remuxer]: Injecting ${$} audio frame @ ${(J/r).toFixed(3)}s due to ${Math.round(1e3*N/r)} ms gap.`);for(let R=0;R<$;R++){const tt=Math.max(J,0);let it=dv.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);it||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),it=U.unit.subarray()),g.splice(z,0,{unit:it,pts:tt}),J+=u,z++}}U.pts=J,J+=u}}let y=null,v=null,T,B=0,_=g.length;for(;_--;)B+=g[_].unit.byteLength;for(let Y=0,z=g.length;Y<z;Y++){const J=g[Y],U=J.unit;let F=J.pts;if(v!==null){const K=A[Y-1];K.duration=Math.round((F-v)/l)}else if(i&&t.segmentCodec==="aac"&&(F=p),y=F,B>0){B+=m;try{T=new Uint8Array(B)}catch(K){this.observer.emit(I.ERROR,I.ERROR,{type:et.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:K,bytes:B,reason:`fail allocating audio mdat ${B}`});return}d||(new DataView(T.buffer).setUint32(0,B),T.set(L.types.mdat,4))}else return;T.set(U,m);const N=U.byteLength;m+=N,A.push(lh(!0,h,N,0)),v=F}const D=A.length;if(!D)return;const x=A[A.length-1];this.nextAudioPts=p=v+l*x.duration;const M=d?new Uint8Array(0):L.moof(t.sequenceNumber++,y/l,xt({},t,{samples:A}));t.samples=[];const k=y/r,X=p/r,H={data1:M,data2:T,startPTS:k,endPTS:X,startDTS:k,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,H}}function Ae(a,t){let e;if(t===null)return a;for(t<a?e=-8589934592:e=8589934592;Math.abs(a-t)>4294967296;)a+=e;return a}function Iv(a){for(let t=0;t<a.length;t++)if(a[t].key)return t;return-1}function $u(a,t,e,i){const s=a.samples.length;if(!s)return;const n=a.inputTimeScale;for(let o=0;o<s;o++){const l=a.samples[o];l.pts=Ae(l.pts-e.baseTime*n/e.timescale,t*n)/n,l.dts=Ae(l.dts-i.baseTime*n/i.timescale,t*n)/n}const r=a.samples;return a.samples=[],{samples:r}}function Yu(a,t,e){const i=a.samples.length;if(!i)return;const s=a.inputTimeScale;for(let r=0;r<i;r++){const o=a.samples[r];o.pts=Ae(o.pts-e.baseTime*s/e.timescale,t*s)/s}a.samples.sort((r,o)=>r.pts-o.pts);const n=a.samples;return a.samples=[],{samples:n}}class Cv{constructor(t,e,i,s){this.logger=void 0,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,this.logger=s}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(uC(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=Zc(t);s.audio&&(e=hh(s.audio,_t.AUDIO)),s.video&&(i=hh(s.video,_t.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:e+","+i,supplemental:s.video.supplemental,initSegment:t,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,supplemental:s.video.supplemental,initSegment:t,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,e,i,s,n,r){var o,l;let{initPTS:h,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};j(u)||(u=this.lastEndTime=n||0);const d=e.samples;if(!(d!=null&&d.length))return c;const A={initPTS:void 0,timescale:1};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((l=f)!=null&&l.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(A.tracks=this.initTracks,this.emitInitSegment=!1);const g=AC(d,f),m=dC(f,d),p=m===null?n:m;(r||!h)&&(yv(h,p,n,g)||A.timescale!==h.timescale)&&(A.initPTS=p-n,h&&h.timescale===1&&this.logger.warn(`Adjusting initPTS @${n} from ${h.baseTime/h.timescale} to ${A.initPTS}`),this.initPTS=h={baseTime:A.initPTS,timescale:1});const C=t?p-h.baseTime/h.timescale:u,E=C+g;gC(f,d,h.baseTime/h.timescale),g>0?this.lastEndTime=E:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!f.audio,v=!!f.video;let T="";y&&(T+="audio"),v&&(T+="video");const B={data1:d,startPTS:C,startDTS:C,endPTS:E,endDTS:E,type:T,hasAudio:y,hasVideo:v,nb:1,dropped:0};return c.audio=B.type==="audio"?B:void 0,c.video=B.type!=="audio"?B:void 0,c.initSegment=A,c.id3=$u(i,n,h,h),s.samples.length&&(c.text=Yu(s,n,h)),c}}function yv(a,t,e,i){if(a===null)return!0;const s=Math.max(i,1),n=t-a.baseTime/a.timescale;return Math.abs(n-e)>s}function hh(a,t){const e=a==null?void 0:a.codec;return e&&e.length>4?e:t===_t.AUDIO?e==="ec-3"||e==="ac-3"||e==="alac"?e:e==="fLaC"||e==="Opus"?Sn(e,!1):(Et.warn(`Unhandled audio codec "${e}" in mp4 MAP`),e||"mp4a"):(Et.warn(`Unhandled video codec "${e}" in mp4 MAP`),e||"avc1")}let Ne;try{Ne=self.performance.now.bind(self.performance)}catch{Ne=Date.now}const An=[{demux:lv,remux:Cv},{demux:ei,remux:dn},{demux:nv,remux:dn},{demux:av,remux:dn}];An.splice(2,0,{demux:rv,remux:dn});class ch{constructor(t,e,i,s,n,r){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=n,this.logger=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const n=i.transmuxing;n.executeStart=Ne();let r=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:h,discontinuity:u,trackSwitch:c,accurateTimeOffset:d,timeOffset:A,initSegmentChange:f}=s||o,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:C,initSegmentData:E}=l,y=vv(r,e);if(y&&Ui(y.method)){const _=this.getDecrypter(),D=Ya(y.method);if(_.isSync()){let x=_.softwareDecrypt(r,y.key.buffer,y.iv.buffer,D);if(i.part>-1){const k=_.flush();x=k&&k.buffer}if(!x)return n.executeEnd=Ne(),Lr(i);r=new Uint8Array(x)}else return this.asyncResult=!0,this.decryptionPromise=_.webCryptoDecrypt(r,y.key.buffer,y.iv.buffer,D).then(x=>{const M=this.push(x,null,i);return this.decryptionPromise=null,M}),this.decryptionPromise}const v=this.needsProbing(u,c);if(v){const _=this.configureTransmuxer(r);if(_)return this.logger.warn(`[transmuxer] ${_.message}`),this.observer.emit(I.ERROR,I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:_,reason:_.message}),n.executeEnd=Ne(),Lr(i)}(u||c||f||v)&&this.resetInitSegment(E,g,m,C,e),(u||f||v)&&this.resetInitialTimestamp(p),h||this.resetContiguity();const T=this.transmux(r,y,A,d,i);this.asyncResult=xs(T);const B=this.currentTransmuxState;return B.contiguous=!0,B.discontinuity=!1,B.trackSwitch=!1,n.executeEnd=Ne(),T}flush(t){const e=t.transmuxing;e.executeStart=Ne();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(t));const r=[],{timeOffset:o}=s;if(i){const c=i.flush();c&&r.push(this.push(c.buffer,null,t))}const{demuxer:l,remuxer:h}=this;if(!l||!h){e.executeEnd=Ne();const c=[Lr(t)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(o);return xs(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(r,c,t),r))):(this.flushRemux(r,u,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:n,id3Track:r,textTrack:o}=e,{accurateTimeOffset:l,timeOffset:h}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===Z.MAIN?"level":"track"} ${i.level}`);const u=this.remuxer.remux(s,n,r,o,h,l,!0,this.id);t.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Ne()}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,n){const{demuxer:r,remuxer:o}=this;!r||!o||(r.resetInitSegment(t,e,i,s),o.resetInitSegment(t,e,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,n){let r;return e&&e.method==="SAMPLE-AES"?r=this.transmuxSampleAes(t,e,i,s,n):r=this.transmuxUnencrypted(t,i,s,n),r}transmuxUnencrypted(t,e,i,s){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,o,l,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,n){return this.demuxer.demuxSampleAes(t,e,i).then(r=>({remuxResult:this.remuxer.remux(r.audioTrack,r.videoTrack,r.id3Track,r.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;let n;for(let c=0,d=An.length;c<d;c++){var r;if((r=An[c].demux)!=null&&r.probe(t,this.logger)){n=An[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=n.remux,u=n.demux;(!l||!(l instanceof h))&&(this.remuxer=new h(i,e,s,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(i,e,s,this.logger),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 Ka(this.config)),t}}function vv(a,t){let e=null;return a.byteLength>0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const Lr=a=>({remuxResult:{},chunkMeta:a});function xs(a){return"then"in a&&a.then instanceof Function}class Bv{constructor(t,e,i,s,n){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=n||null}}class Sv{constructor(t,e,i,s,n,r){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=n,this.initSegmentChange=r}}let uh=0;class Vu{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=uh++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const h=l.data,u=this.hls;if(!(!u||!(h!=null&&h.event)||h.instanceNo!==this.instanceNo))switch(h.event){case"init":{var c;const d=(c=this.workerContext)==null?void 0:c.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(h.data);break}case"flush":{this.onFlush(h.data);break}case"workerLog":{u.logger[h.data.logType]&&u.logger[h.data.logType](h.data.message);break}default:{h.data=h.data||{},h.data.frag=this.frag,h.data.part=this.part,h.data.id=this.id,u.trigger(h.event,h.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const h=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:h})};const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const r=(l,h)=>{h=h||{},h.frag=this.frag||void 0,l===I.ERROR&&(h=h,h.parent=this.id,h.part=this.part,this.error=h.error),this.hls.trigger(l,h)};this.observer=new za,this.observer.on(I.FRAG_DECRYPTED,r),this.observer.on(I.ERROR,r);const o=Dl(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(n.workerPath||xy()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=Ry(n.workerPath)):(l.log(`injecting Web Worker for "${e}"`),this.workerContext=Dy());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:Mt(n)})}catch(u){l.warn(`Error setting up "${e}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new ch(this.observer,o,n,"",e,t.logger)}return}}this.transmuxer=new ch(this.observer,o,n,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=uh++;const e=this.hls.config,i=Dl(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Mt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Ly(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,n,r,o,l,h,u){var c,d;h.transmuxing.start=self.performance.now();const{instanceNo:A,transmuxer:f}=this,g=r?r.start:n.start,m=n.decryptdata,p=this.frag,C=!(p&&n.cc===p.cc),E=!(p&&h.level===p.level),y=p?h.sn-p.sn:-1,v=this.part?h.part-this.part.index:-1,T=y===0&&h.id>1&&h.id===(p==null?void 0:p.stats.chunkCount),B=!E&&(y===1||y===0&&(v===1||T&&v<=0)),_=self.performance.now();(E||y||n.stats.parsing.start===0)&&(n.stats.parsing.start=_),r&&(v||!B)&&(r.stats.parsing.start=_);const D=!(p&&((c=n.initSegment)==null?void 0:c.url)===((d=p.initSegment)==null?void 0:d.url)),x=new Sv(C,B,l,E,g,D);if(!B||C||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${h.sn}${h.part>-1?" part: "+h.part:""} ${this.id===Z.MAIN?"level":"track"}: ${h.level} id: ${h.id}
|
|
26
|
+
discontinuity: ${C}
|
|
27
|
+
trackSwitch: ${E}
|
|
28
|
+
contiguous: ${B}
|
|
29
|
+
accurateTimeOffset: ${l}
|
|
30
|
+
timeOffset: ${g}
|
|
31
|
+
initSegmentChange: ${D}`);const M=new Bv(i,s,e,o,u);this.configureTransmuxer(M)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:A,cmd:"demux",data:t,decryptdata:m,chunkMeta:h,state:x},t instanceof ArrayBuffer?[t]:[]);else if(f){const M=f.push(t,m,h,x);xs(M)?M.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,h,"transmuxer-interface push error")}):this.handleTransmuxComplete(M)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const s=i.flush(t);xs(s)?s.then(n=>{this.handleFlushResult(n,t)}).catch(n=>{this.transmuxerError(n,t,"transmuxer-interface flush error")}):this.handleFlushResult(s,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const dh=100;class Ju extends Nn{constructor(t,e,i){super(t,e,i,"audio-stream-controller",Z.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!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.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=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.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_LOADING,this.onFragLoading,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),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.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_LOADING,this.onFragLoading,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:n}){if(i===Z.MAIN){const r=e.cc,o=this.fragCurrent;if(this.initPTS[r]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${r} found from main: ${s}/${n}`),this.mainAnchor=e,this.state===G.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==r)&&(this.nextLoadPosition=this.findSyncFrag(e).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==r?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(e).start,o.abortRequests(),this.resetLoadingState()):this.state===G.IDLE&&this.tick()}}findSyncFrag(t){const e=this.getLevelDetails(),i=t.cc;return KC(e,i,t)||e&&uu(e.fragments,i)||t}startLoad(t,e){if(!this.levels){this.startPosition=t,this.state=G.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(dh),i>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=G.IDLE):this.state=G.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case G.IDLE:this.doTickIdle();break;case G.WAITING_TRACK:{const{levels:e,trackId:i}=this,s=e==null?void 0:e[i],n=s==null?void 0:s.details;if(n&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(n))break;this.state=G.WAITING_INIT_PTS}break}case G.FRAG_LOADING_WAITING_RETRY:{var t;const e=performance.now(),i=this.retryDate;if(!i||e>=i||(t=this.media)!=null&&t.seeking){const{levels:s,trackId:n}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((s==null?void 0:s[n])||null),this.state=G.IDLE}break}case G.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:i,part:s,cache:n,complete:r}=e,o=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=G.FRAG_LOADING;const l=n.flush().buffer,h={frag:i,part:s,payload:l,networkDetails:null};this._handleFragmentLoadProgress(h),r&&super._handleFragmentLoadComplete(h)}else o&&o.cc!==e.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${o.cc}`),this.nextLoadPosition=this.findSyncFrag(o).start,this.clearWaitingFragment())}else this.state=G.IDLE}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.state!==G.STOPPED&&(this.state=G.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:n}=this,r=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||!(i!=null&&i[n]))return;const o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=G.WAITING_TRACK,this.startFragRequested=!1;return}const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,_t.AUDIO,Z.AUDIO));const u=this.getFwdBufferInfo(h,Z.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){e.trigger(I.BUFFER_EOS,{type:"audio"}),this.state=G.ENDED;return}const c=u.len,d=e.maxBufferLength,A=l.fragments,f=A[0].start,g=this.getLoadPosition(),m=this.flushing?g:u.end;if(this.switchingTrack&&s){const E=g;l.PTSKnown&&E<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=d&&!this.switchingTrack&&m<A[A.length-1].start)return;let p=this.getNextFragment(m,l);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,l,u,Z.MAIN,d)),!p){this.bufferFlushed=!0;return}let C=((t=this.mainFragLoading)==null?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&C&&zt(p)&&!p.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(C)===$t.OK&&(this.mainFragLoading=C=null),C&&zt(C))){if(p.start>C.end){const y=this.fragmentTracker.getFragAtPos(m,Z.MAIN);y&&y.end>C.end&&(C=y,this.mainFragLoading={frag:y,targetBufferTime:null})}if(p.start>C.end)return}this.loadFragment(p,o,m)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(i=>new Hi(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.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==G.STOPPED&&(this.setInterval(dh),this.state=G.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:n,id:r,groupId:o,track:l}=e;if(!s){this.warn(`Audio tracks reset while loading track ${r} "${l.name}" of "${o}"`);return}const h=this.mainDetails;if(!h||n.endCC>h.endCC||h.expired){this.cachedTrackLoadedData=e,this.state!==G.STOPPED&&(this.state=G.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const u=s[r];let c=0;if(n.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var d;c=this.alignPlaylists(n,u.details,(d=this.levelLastLoaded)==null?void 0:d.details)}n.alignedSliding||(Tu(n,h),n.alignedSliding||Ln(n,h),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:e.groupId}),this.state===G.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=G.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{config:r,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 h=l[o];if(!h){this.warn("Audio track is undefined on fragment load progress");return}const u=h.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=r.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Vu(this.hls,Z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const A=this.initPTS[i.cc],f=(e=i.initSegment)==null?void 0:e.data;if(A!==void 0){const m=s?s.index:-1,p=m!==-1,C=new Gn(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p);d.push(n,f,c,"",i,s,u.totalduration,!1,C,A)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new _u,complete:!1};g.push(new Uint8Array(n)),this.state!==G.STOPPED&&(this.state=G.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===Z.MAIN&&zt(e.frag)&&(this.mainFragLoading=e,this.state===G.IDLE&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type!==Z.AUDIO){!this.audioOnly&&i.type===Z.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);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(zt(i)){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,St({},n)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(t,e){var i;if(e.fatal){this.state=G.ERROR;return}switch(e.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.AUDIO,e);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===G.WAITING_TRACK&&((i=e.context)==null?void 0:i.type)===gt.AUDIO_TRACK&&(this.state=G.IDLE);break;case b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(e.parent!=="audio")return;this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushing(t,{type:e}){e!==_t.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==_t.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===G.ENDED&&(this.state=G.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,e,Z.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:l,part:h,level:u}=o,{details:c}=u,{audio:d,text:A,id3:f,initSegment:g}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=G.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const m=l.initSegment||l;this._bufferInitSegment(u,g.tracks,m,r),s.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:g.tracks})}if(d){const{startPTS:m,endPTS:p,startDTS:C,endDTS:E}=d;h&&(h.elementaryStreams[_t.AUDIO]={startPTS:m,endPTS:p,startDTS:C,endDTS:E}),l.setElementaryStreamInfo(_t.AUDIO,m,p,C,E),this.bufferFragmentData(d,l,h,r)}if(f!=null&&(e=f.samples)!=null&&e.length){const m=xt({id:i,frag:l,details:c},f);s.trigger(I.FRAG_PARSING_METADATA,m)}if(A){const m=xt({id:i,frag:l,details:c},A);s.trigger(I.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(t,e,i,s){if(this.state!==G.PARSING||(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio))return;const n=e.audio;n.id=Z.AUDIO;const r=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),r&&r.split(",").length===1&&(n.levelCodec=r),this.hls.trigger(I.BUFFER_CODECS,e);const o=n.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.switchingTrack||s===$t.NOT_LOADED||s===$t.PARTIAL){var n;if(!zt(t))this._loadInitSegment(t,e);else if((n=e.details)!=null&&n.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=G.WAITING_INIT_PTS;const r=this.mainDetails;r&&r.fragmentStart!==e.details.fragmentStart&&Ln(e.details,r)}else super.loadFragment(t,e,i)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o}=this.bufferedTrack;mi({name:e,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o},t,gi)||(_n(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(I.AUDIO_TRACK_SWITCHED,St({},t))}}class Kn extends qe{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,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.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const s=e==null?void 0:e.renditionReports;if(s){let n=-1;for(let r=0;r<s.length;r++){const o=s[r];let l;try{l=new self.URL(o.URI,e.url).href}catch(h){this.warn(`Could not construct new URL for Rendition Report: ${h}`),l=o.URI||""}if(l===t){n=r;break}else l===t.substring(0,l.length)&&(n=r)}if(n!==-1){const r=s[n],o=parseInt(r["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let l=parseInt(r["LAST-PART"])||(e==null?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(e.age-e.partTarget,e.targetduration);l>=0&&u>e.partTarget&&(l+=1)}const h=i&&Ll(i);return new ra(o,l>=0?l:void 0,h)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:n}=e,r=self.performance.now(),o=n.loading.first?Math.max(0,r-n.loading.first):0;s.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==s.appliedTimelineOffset){const u=Math.max(l||0,0);s.appliedTimelineOffset=u,s.fragments.forEach(c=>{c.start=c.playlistOffset+u})}if(s.live||i!=null&&i.live){const u="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){py(i,s);const C=s.playlistParsingError;if(C){this.warn(C);const E=this.hls;if(!E.config.ignorePlaylistParsingErrors){var h;const{networkDetails:y}=e;E.trigger(I.ERROR,{type:et.NETWORK_ERROR,details:b.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:C,reason:C.message,level:e.level||void 0,parent:(h=s.fragments[0])==null?void 0:h.type,networkDetails:y,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const c=this.hls.mainForwardBufferInfo,d=c?c.end-c.len:0,A=(s.edge-d)*1e3,f=Cu(s,A);if(s.requestScheduled+f<r?s.requestScheduled=r:s.requestScheduled+=f,this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let g,m,p;if(s.canBlockReload&&s.endSN&&s.advanced){const C=this.hls.config.lowLatencyMode,E=s.lastPartSn,y=s.endSN,v=s.lastPartIndex,T=v!==-1,B=E===y;T?B?(m=y+1,p=C?0:v):(m=E,p=C?v+1:s.maxPartIndex):m=y+1;const _=s.age,D=_+s.ageHeader;let x=Math.min(D-s.partTarget,s.targetduration*1.5);if(x>0){if(D>s.targetduration*3)this.log(`Playlist last advanced ${_.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,p=void 0;else if(i!=null&&i.tuneInGoal&&D-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${x} with playlist age: ${s.age}`),x=0;else{const M=Math.floor(x/s.targetduration);if(m+=M,p!==void 0){const k=Math.round(x%s.targetduration/s.partTarget);p+=k}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${x} skip sn ${M} to part ${p}`)}s.tuneInGoal=x}if(g=this.getDeliveryDirectives(s,e.deliveryDirectives,m,p),C||!B){s.requestScheduled=r,this.loadingPlaylist(u,g);return}}else(s.canBlockReload||s.canSkipUntil)&&(g=this.getDeliveryDirectives(s,e.deliveryDirectives,m,p));g&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(u,g,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s){this.loadingPlaylist(t,e);return}const n=self.performance.now(),r=s.requestScheduled;if(n>=r){this.loadingPlaylist(t,e);return}const o=r-n;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),o)}getDeliveryDirectives(t,e,i,s){let n=Ll(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=Is.No),new ra(i,s,n)}checkRetry(t){const e=t.details,i=xn(t),s=t.errorAction,{action:n,retryCount:r=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===Jt.RetryRequest||!s.resolved&&n===Jt.SendAlternateToPenaltyBox);if(l){var h;if(r>=o.maxNumRetry)return!1;if(i&&(h=t.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const u=Ha(o,r);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${e}" in ${u}ms`)}t.levelRetry=!0,s.resolved=!0}return l}}function zu(a,t){if(a.length!==t.length)return!1;for(let e=0;e<a.length;e++)if(!Ds(a[e].attrs,t[e].attrs))return!1;return!0}function Ds(a,t,e){const i=a["STABLE-RENDITION-ID"];return i&&!e?i===t["STABLE-RENDITION-ID"]:!(e||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>a[s]!==t[s])}function da(a,t){return t.label.toLowerCase()===a.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(a.lang||"").toLowerCase())}class qu extends Kn{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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${r==null?void 0:r.groupId}`);return}const o=r.details;r.details=e.details,this.log(`Audio track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=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(d=>!i||i.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,A)=>{d.id=A});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!n&&l){const d=we(l,o,gi);if(d>-1)n=o[d];else{const A=we(l,this.tracks);n=this.tracks[A]}}let h=this.findTrackId(n);h===-1&&n&&(h=this.findTrackId(null));const u={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,u);const c=this.trackId;if(h!==-1&&c===-1)this.setAudioTrack(h);else if(o.length&&c===-1){var r;const d=new Error(`No audio track selected for current audio group-ID(s): ${(r=this.groupIds)==null?void 0:r.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(t,e){e.fatal||!e.context||e.context.type===gt.AUDIO_TRACK&&e.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(e.context.groupId)!==-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&&mi(t,s,gi))return s;const n=we(t,this.tracksInGroup,gi);if(n>-1){const r=this.tracksInGroup[n];return this.setAudioTrack(n),r}else if(s){let r=e.loadLevel;r===-1&&(r=e.firstAutoLevel);const o=UC(t,e.levels,i,r,gi);if(o===-1)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){const r=we(t,i);if(r>-1)return i[r]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],n=s.details&&!s.details.live;if(t===this.trackId&&s===i&&n||(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,St({},s)),n))return;const r=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(r)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if(!(this.selectDefaultTrack&&!s.default)&&(!t||mi(t,s,gi)))return i}if(t){const{name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:l}=t;for(let h=0;h<e.length;h++){const u=e[h];if(mi({name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:l},u,gi))return h}for(let h=0;h<e.length;h++){const u=e[h];if(Ds(t.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return h}for(let h=0;h<e.length;h++){const u=e[h];if(Ds(t.attrs,u.attrs,["LANGUAGE"]))return h}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&_n(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=r==null?void 0:r.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null,track:t})}}class Tv{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(this.queues===null||this.tracks===null)return;const s=this.queues[e];s.push(t),s.length===1&&!i&&this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=(e=t[0])==null?void 0:e.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;const r=(i=this.tracks[t])==null?void 0:i.buffer;r!=null&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return((e=this.queues)==null?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return t===null||e===null?"<destroyed>":`
|
|
32
|
+
${this.list("video")}
|
|
33
|
+
${this.list("audio")}
|
|
34
|
+
${this.list("audiovideo")}}`}list(t){var e,i;return(e=this.queues)!=null&&e[t]||(i=this.tracks)!=null&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=(e=this.tracks)==null?void 0:e[t],s=i==null?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return((e=this.queues)==null?void 0:e[t].map(i=>i.label).join(", "))||""}}const Ah=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Xu="HlsJsTrackRemovedError";class _v extends Error{constructor(t){super(t),this.name=Xu}}class Wu extends qe{constructor(t,e){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(I.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&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&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=sC(Je(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=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),t.on(I.ERROR,this.onError,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),t.off(I.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const r=this.isQueued();(n||r)&&this.warn(`Transfering MediaSource with${r?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?xt(i,s.tracks):this.sourceBuffers.forEach(n=>{const[r]=n;r&&(i[r]=xt({},this.tracks[r]),this.removeBuffer(r)),n[0]=n[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var i;let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media,s=Je(this.appendSource);if(this.transferData=this.overrides=void 0,i&&s){const n=!!e.mediaSource;(n||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(r),n)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&r instanceof l,fh(i),xv(i,o),i.load()}catch{i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${(i=t.constructor)==null?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,n=s?Object.keys(s):null,r=n?n.length:0,o=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(s&&n&&r){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
35
|
+
required tracks: ${Mt(i,(l,h)=>l==="initSegment"?void 0:h)};
|
|
36
|
+
transfer tracks: ${Mt(s,(l,h)=>l==="initSegment"?void 0:h)}}`),!Jc(s,i)){e.mediaSource=null,e.tracks=void 0;const l=t.currentTime,h=this.details,u=Math.max(l,(h==null?void 0:h.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,e),t.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{const h=l,u=s[h];if(u){const c=u.buffer;if(c){const d=this.fragmentTracker,A=u.id;if(d.hasFragments(A)||d.hasParts(A)){const m=ft.getBuffered(c);d.detectEvictedFragments(h,m,A,null,!0)}const f=br(h),g=[h,c];this.sourceBuffers[f]=g,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(h),this.trackSourceBuffer(h,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=(t=this.mediaSource)==null?void 0:t.readyState;return e==="open"||e==="ended"}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:n,_objectUrl:r}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const l=n.sourceBuffers;for(let h=l.length;h--;)o&&l[h].abort(),n.removeSourceBuffer(l[h]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(s.removeAttribute("src"),this.appendSource&&fh(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=(e=this.tracks[t])==null?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${t}`,n)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[br(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Tv(this.tracks)}onBufferCodecs(t,e){const i=this.tracks,s=Object.keys(e);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),r=!n&&this.sourceBufferCount&&this.media&&s.some(o=>!i[o]);if(n||r){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`);return}s.forEach(o=>{var l,h,u;const c=e[o],{id:d,codec:A,levelCodec:f,container:g,metadata:m,supplemental:p}=c;let C=i[o];const E=(l=this.transferData)==null||(h=l.tracks)==null?void 0:h[o],y=E!=null&&E.buffer?E:C,v=(y==null?void 0:y.pendingCodec)||(y==null?void 0:y.codec),T=y==null?void 0:y.levelCodec;C||(C=i[o]={buffer:void 0,listeners:[],codec:A,supplemental:p,container:g,levelCodec:f,metadata:m,id:d});const B=un(v,T),_=B==null?void 0:B.replace(Ah,"$1");let D=un(A,f);const x=(u=D)==null?void 0:u.replace(Ah,"$1");D&&B&&_!==x&&(o.slice(0,5)==="audio"&&(D=Sn(D,this.appendSource)),this.log(`switching codec ${v} to ${D}`),D!==(C.pendingCodec||C.codec)&&(C.pendingCodec=D),C.container=g,this.appendChangeType(o,g,D))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const o=r.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),o.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${t} SourceBuffer type`,r)}};this.append(n,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+t.duration*.05;if(((e=this.fragmentTracker.getAppendedFrag(i,Z.MAIN))==null?void 0:e.gap)===!0)return;const r={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>s||l!=null&&l.buffer&&ft.isBuffered(l.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,Z.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:i}=this,{data:s,type:n,parent:r,frag:o,part:l,chunkMeta:h}=e,u=h.buffering[n],c=o.sn,d=self.performance.now();u.start=d;const A=o.stats.buffering,f=l?l.stats.buffering:null;A.start===0&&(A.start=d),f&&f.start===0&&(f.start=d);const g=i.audio;let m=!1;n==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=this.tracks.video,C=p==null?void 0:p.buffer;if(C&&c!=="initSegment"){const v=l||o,T=this.blockedAudioAppend;if(n==="audio"&&r!=="main"&&!this.blockedAudioAppend){const _=v.start+v.duration*.05,D=C.buffered,x=this.currentOp("video");!D.length&&!x?this.blockAudio(v):!x&&!ft.isBuffered(C,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(v)}else if(n==="video"){const B=v.end;if(T){const _=T.frag.start;(B>_||B<this.lastVideoAppendEnd||ft.isBuffered(C,_))&&this.unblockAudio()}this.lastVideoAppendEnd=B}}const E=(l||o).start,y={label:`append-${n}`,execute:()=>{if(u.executeStart=self.performance.now(),m){const v=this.tracks[n];if(v){const T=v.buffer;if(T){const B=E-T.timestampOffset;Math.abs(B)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${E} (delta: ${B}) sn: ${c})`),T.timestampOffset=E)}}}this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const v=self.performance.now();u.executeEnd=u.end=v,A.first===0&&(A.first=v),f&&f.first===0&&(f.first=v);const T={};this.sourceBuffers.forEach(([B,_])=>{B&&(T[B]=ft.getBuffered(_))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(I.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:T})},onError:v=>{var T;const B={type:et.MEDIA_ERROR,parent:o.type,details:b.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:h,error:v,err:v,fatal:!1},_=(T=this.media)==null?void 0:T.error;if(v.code===DOMException.QUOTA_EXCEEDED_ERR)B.details=b.BUFFER_FULL_ERROR;else if(v.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!_)B.errorAction=Ss(!0);else if(v.name===Xu&&this.sourceBufferCount===0)B.errorAction=Ss(!0);else{const D=++this.appendErrors[n];this.warn(`Failed ${D}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${_||"no media error"})`),(D>=this.hls.config.appendErrorMaxRetry||_)&&(B.fatal=!0)}this.hls.trigger(I.ERROR,B)}};this.append(y,n,this.isPending(this.tracks[n]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(I.BUFFER_FLUSHED,{type:t})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s)}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:n}=e;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([r])=>{r&&this.append(this.getFlushOp(r,s,n),r)})}onFragParsed(t,e){const{frag:i,part:s}=e,n=[],r=s?s.elementaryStreams:i.elementaryStreams;r[_t.AUDIOVIDEO]?n.push("audiovideo"):(r[_t.AUDIO]&&n.push("audio"),r[_t.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const h=s?s.stats:i.stats;this.hls.trigger(I.FRAG_BUFFERED,{frag:i,part:s,stats:h,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e,i;return t&&(!((e=this.tracks[t])!=null&&e.ended)||((i=this.tracks[t])==null?void 0:i.ending))})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([r])=>{if(r){const o=this.tracks[r];(!e.type||e.type===r)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${r} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var o;return r&&!((o=this.tracks[r])!=null&&o.ended)})&&(s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(I.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){const t=this.getDurationAndRange();t&&this.blockUntilOpen(()=>this.updateMediaSource(t))}onError(t,e){if(e.details===b.BUFFER_APPEND_ERROR&&e.frag){var i;const s=(i=e.errorAction)==null?void 0:i.nextAutoLevel;j(s)&&s!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||e===null||!this.sourceBufferCount)return;const s=t.config,n=i.currentTime,r=e.levelTargetDuration,o=e.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(j(o)&&o>=0){const l=Math.max(o,r),h=Math.floor(n/r)*r-l;this.flushBackBuffer(n,r,h)}if(j(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const l=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),h=Math.max(l,r),u=Math.floor(n/r)*r+h;this.flushFrontBuffer(n,r,u)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const o=ft.getBuffered(n);if(o.length>0&&i>o.start(0)){var r;this.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});const l=this.tracks[s];if((r=this.details)!=null&&r.live)this.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const r=ft.getBuffered(n),o=r.length;if(o<2)return;const l=r.start(o-1),h=r.end(o-1);if(i>l||t>=l&&t<=h)return;this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&e.live&&i.setLiveSeekableRange){const h=Math.max(0,e.fragmentStart),u=Math.max(h,s);return{duration:1/0,start:h,end:u}}return{duration:1/0}}const n=(t=this.overrides)==null?void 0:t.duration;if(n)return j(n)?{duration:n}:null;const r=this.media.duration,o=j(i.duration)?i.duration:0;return s>o&&s>r||!j(r)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==t&&(j(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),e!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`),s.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Mt(i)}`),this.tracksReady){var s;const n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(I.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in t){const r=n,o=t[r];if(this.isPending(o)){const l=this.getTrackCodec(o,r),h=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${h})${this.currentOp(r)?" Queued":""} ${Mt(o)}`);try{const u=i.addSourceBuffer(h),c=br(r),d=[r,u];e[c]=d,o.buffer=u}catch(u){var s;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(r),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[r],this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:r,mimeType:h,parent:o.id});return}this.trackSourceBuffer(r,o)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&(e==="video"||e==="audiovideo")&&sa(i,"video")&&(s=TC(s,i));const n=un(s,t.levelCodec);return n?e.slice(0,5)==="audio"?Sn(n,this.appendSource):n:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(n,r)=>{const o=r.removedRanges;o!=null&&o.length&&this.hls.trigger(I.BUFFER_FLUSHED,{type:n})})}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 e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const i=this.currentOp(t);i&&(i.onComplete(),this.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:et.MEDIA_ERROR,details:b.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const n=this.currentOp(t);n&&n.onError(s)}removeExecutor(t,e,i){const{media:s,mediaSource:n}=this,r=this.tracks[t],o=r==null?void 0:r.buffer;if(!s||!n||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const l=j(s.duration)?s.duration:1/0,h=j(n.duration)?n.duration:1/0,u=Math.max(0,e),c=Math.min(i,l,h);c>u&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${u},${c}] from the ${t} SourceBuffer`),o.remove(u,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=i==null?void 0:i.buffer;if(!s)throw new _v(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map(r=>this.appendBlocker(r));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(r=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(e=>{var i;const s=(i=this.tracks[e])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(e)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const n=s.buffer;if(!n)return;const r=i.bind(this,t);s.listeners.push({event:e,listener:r}),n.addEventListener(e,r)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),e.listeners.length=0)}}function fh(a){const t=a.querySelectorAll("source");[].slice.call(t).forEach(e=>{a.removeChild(e)})}function xv(a,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,a.appendChild(e)}function br(a){return a==="audio"?1:0}class $n{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(),this.media=null}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&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&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,n)=>this.isLevelAllowed(s)&&n<=t);return this.clientRect=null,$n.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 Math.min(t,this.hls.config.maxDevicePixelRatio)}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 n=t.length-1;const r=Math.max(e,i);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=r||l.height>=r)&&s(l,t[o+1])){n=o;break}}return n}}const Dv={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ee=Dv,Rv={HLS:"h"},Lv=Rv,bv="CMCD-Object",wv="CMCD-Request",Pv="CMCD-Session",Mv="CMCD-Status",gs={OBJECT:bv,REQUEST:wv,SESSION:Pv,STATUS:Mv},Fv={[gs.OBJECT]:["br","d","ot","tb"],[gs.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[gs.SESSION]:["cid","pr","sf","sid","st","v"],[gs.STATUS]:["bs","rtp"]};class Yi{constructor(t,e){Array.isArray(t)&&(t=t.map(i=>i instanceof Yi?i:new Yi(i))),this.value=t,this.params=e}}const kv="Dict";function Ov(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function Qv(a,t,e,i){return new Error(`failed to ${a} "${Ov(t)}" as ${e}`,{cause:i})}function Fe(a,t,e){return Qv("serialize",a,t,e)}class ju{constructor(t){this.description=t}}const gh="Bare Item",Uv="Boolean";function Gv(a){if(typeof a!="boolean")throw Fe(a,Uv);return a?"?1":"?0"}const Nv="Byte Sequence";function Hv(a){if(ArrayBuffer.isView(a)===!1)throw Fe(a,Nv);return`:${Gy(a)}:`}const Kv="Integer";function $v(a){return a<-999999999999999||999999999999999<a}function Zu(a){if($v(a))throw Fe(a,Kv);return a.toString()}function Yv(a){return`@${Zu(a.getTime()/1e3)}`}const Vv="Decimal";function Jv(a){const t=Pu(a,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Fe(a,Vv);const e=t.toString();return e.includes(".")?e:`${e}.0`}const zv="String",qv=/[\x00-\x1f\x7f]+/;function Xv(a){if(qv.test(a))throw Fe(a,zv);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Wv(a){return a.description||a.toString().slice(7,-1)}const jv="Token";function mh(a){const t=Wv(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Fe(t,jv);return t}function Aa(a){switch(typeof a){case"number":if(!j(a))throw Fe(a,gh);return Number.isInteger(a)?Zu(a):Jv(a);case"string":return Xv(a);case"symbol":return mh(a);case"boolean":return Gv(a);case"object":if(a instanceof Date)return Yv(a);if(a instanceof Uint8Array)return Hv(a);if(a instanceof ju)return mh(a);default:throw Fe(a,gh)}}const Zv="Key";function fa(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw Fe(a,Zv);return a}function eo(a){return a==null?"":Object.entries(a).map(([t,e])=>e===!0?`;${fa(t)}`:`;${fa(t)}=${Aa(e)}`).join("")}function td(a){return a instanceof Yi?`${Aa(a.value)}${eo(a.params)}`:Aa(a)}function tB(a){return`(${a.value.map(td).join(" ")})${eo(a.params)}`}function eB(a,t={whitespace:!0}){if(typeof a!="object")throw Fe(a,kv);const e=a instanceof Map?a.entries():Object.entries(a),i=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([s,n])=>{n instanceof Yi||(n=new Yi(n));let r=fa(s);return n.value===!0?r+=eo(n.params):(r+="=",Array.isArray(n.value)?r+=tB(n):r+=td(n)),r}).join(`,${i}`)}function iB(a,t){return eB(a,t)}function sB(a){return a==="ot"||a==="sf"||a==="st"}function nB(a){return typeof a=="number"?j(a):a!=null&&a!==""&&a!==!1}const fn=a=>Math.round(a),rB=(a,t)=>(t!=null&&t.baseUrl&&(a=Ny(a,t.baseUrl)),encodeURIComponent(a)),en=a=>fn(a/100)*100,aB={br:fn,d:fn,bl:en,dl:en,mtp:en,nor:rB,rtp:en,tb:fn};function oB(a,t){const e={};if(a==null||typeof a!="object")return e;const i=Object.keys(a).sort(),s=xt({},aB,t==null?void 0:t.formatters),n=t==null?void 0:t.filter;return i.forEach(r=>{if(n!=null&&n(r))return;let o=a[r];const l=s[r];l&&(o=l(o,t)),!(r==="v"&&o===1)&&(r=="pr"&&o===1||nB(o)&&(sB(r)&&typeof o=="string"&&(o=new ju(o)),e[r]=o))}),e}function ed(a,t={}){return a?iB(oB(a,t),xt({whitespace:!1},t)):""}function lB(a,t={}){const e={};if(!a)return e;const i=Object.entries(a),s=Object.entries(Fv).concat(Object.entries((t==null?void 0:t.customHeaderMap)||{})),n=i.reduce((r,o)=>{var l,h;const[u,c]=o,d=((l=s.find(A=>A[1].includes(u)))===null||l===void 0?void 0:l[0])||gs.REQUEST;return(h=r[d])!==null&&h!==void 0||(r[d]={}),r[d][u]=c,r},{});return Object.entries(n).reduce((r,[o,l])=>(r[o]=ed(l,t),r),e)}function hB(a,t,e){return xt(a,lB(t,e))}const cB="CMCD";function uB(a,t={}){if(!a)return"";const e=ed(a,t);return`${cB}=${encodeURIComponent(e)}`}const ph=/CMCD=[^&#]+/;function dB(a,t,e){const i=uB(t,e);if(!i)return a;if(ph.test(a))return a.replace(ph,i);const s=a.includes("?")?"&":"?";return`${a}${s}${i}`}class id{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:ee.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const{frag:n,part:r}=s,o=this.hls.levels[n.level],l=this.getObjectType(n),h={d:(r||n).duration*1e3,ot:l};(l===ee.VIDEO||l===ee.AUDIO||l==ee.MUXED)&&(h.br=o.bitrate/1e3,h.tb=this.getTopBandwidth(l)/1e3,h.bl=this.getBufferLength(l));const u=r?this.getNextPart(r):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(h.nor=u.url),this.apply(s,h)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},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||t.sessionId,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=this.media=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:Lv.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){xt(e,this.createData());const i=e.ot===ee.INIT||e.ot===ee.VIDEO||e.ot===ee.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((r,o)=>(s.includes(o)&&(r[o]=e[o]),r),{}));const n={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),hB(t.headers,e,n)):t.url=dB(t.url,e,n)}getNextFrag(t){var e;const i=(e=this.hls.levels[t.level])==null?void 0:e.details;if(i){const s=t.sn-i.startSN;return i.fragments[s+1]}}getNextPart(t){var e,i;const{index:s,fragment:n}=t,r=(e=this.hls.levels[n.level])==null||(i=e.details)==null?void 0:i.partList;if(r){const{sn:o}=n;for(let l=r.length-1;l>=0;l--){const h=r[l];if(h.index===s&&h.fragment.sn===o)return r[l+1]}}}getObjectType(t){const{type:e}=t;if(e==="subtitle")return ee.TIMED_TEXT;if(t.sn==="initSegment")return ee.INIT;if(e==="audio")return ee.AUDIO;if(e==="main")return this.hls.audioTracks.length?ee.VIDEO:ee.MUXED}getTopBandwidth(t){let e=0,i;const s=this.hls;if(t===ee.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,r=n>-1?n+1:s.levels.length;i=s.levels.slice(0,r)}for(const n of i)n.bitrate>e&&(e=n.bitrate);return e>0?e:NaN}getBufferLength(t){const e=this.media,i=t===ee.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!e?NaN:ft.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(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,r,o){e(n),this.loader.load(n,r,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,r,o){e(n),this.loader.load(n,r,o)}}}}const AB=3e5;class sd extends qe{constructor(t){super("content-steering",t.logger),this.hls=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.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))}pathways(){return(this.levels||[]).reduce((t,e)=>(t.indexOf(e.pathwayId)===-1&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}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)===Jt.SendAlternateToPenaltyBox&&i.flags===de.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:o,pathwayId:l,type:h}=e.context;o&&s?r=this.getPathwayForGroupId(o,h,r):l&&(r=l)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==r),i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${s&&s.length} priorities: ${Mt(n)} penalized: ${Mt(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(n=>{s-i[n]>AB&&delete i[n]});for(let n=0;n<t.length;n++){const r=t[n];if(r in i)continue;if(r===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Bu(e),this.hls.trigger(I.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(e===gt.AUDIO_TRACK&&s[n].hasAudioGroup(t)||e===gt.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(t))return s[n].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(n=>{const{ID:r,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(e.some(u=>u.pathwayId===r))return;const h=this.getLevelsForPathway(o).map(u=>{const c=new Pt(u.attrs);c["PATHWAY-ID"]=r;const d=c.AUDIO&&`${c.AUDIO}_clone_${r}`,A=c.SUBTITLES&&`${c.SUBTITLES}_clone_${r}`;d&&(i[c.AUDIO]=d,c.AUDIO=d),A&&(s[c.SUBTITLES]=A,c.SUBTITLES=A);const f=nd(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Hi({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let m=1;m<u.audioGroups.length;m++)g.addGroupId("audio",`${u.audioGroups[m]}_clone_${r}`);if(u.subtitleGroups)for(let m=1;m<u.subtitleGroups.length;m++)g.addGroupId("text",`${u.subtitleGroups[m]}_clone_${r}`);return g});e.push(...h),Eh(this.audioTracks,i,l,r),Eh(this.subtitleTracks,s,l,r)})}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 u=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:s.href},r=e.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},l={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(u,c,d,A)=>{this.log(`Loaded steering manifest: "${s}"`);const f=u.data;if((f==null?void 0: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":m,"PATHWAY-PRIORITY":p}=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||d.url),m&&this.clonePathways(m);const C={steeringManifest:f,url:s.toString()};this.hls.trigger(I.STEERING_MANIFEST_LOADED,C),p&&this.updatePathwayPriority(p)},onError:(u,c,d,A)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const m=g.getResponseHeader("Retry-After");m&&(f=parseFloat(m)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(u,c,d)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,h)}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 Eh(a,t,e,i){a&&Object.keys(t).forEach(s=>{const n=a.filter(r=>r.groupId===s).map(r=>{const o=xt({},r);return o.details=void 0,o.attrs=new Pt(o.attrs),o.url=o.attrs.URI=nd(r.url,r.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=i,o});a.push(...n)})}function nd(a,t,e,i){const{HOST:s,PARAMS:n,[e]:r}=i;let o;t&&(o=r==null?void 0:r[t],o&&(a=o));const l=new self.URL(a);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(h=>{h&&l.searchParams.set(h,n[h])}),l.href}class pi extends qe{constructor(t){super("eme",t.logger),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=pi.CDMCleanupPromise?[pi.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:i,initData:s}=e,n=`"${e.type}" event: init data type: "${i}"`;if(this.debug(n),s!==null){if(!this.keyFormatPromise){let r=Object.keys(this.keySystemAccessPromises);r.length||(r=Ws(this.config));const o=r.map(Br).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(r=>{const o=yr(r);let l,h;if(i==="sinf"){if(o!==vt.FAIRPLAY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const f=Ht(new Uint8Array(s));try{const g=Va(JSON.parse(f).sinf),m=tu(g);if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(m.subarray(8,24)),h=vt.FAIRPLAY}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}}else{if(o!==vt.WIDEVINE&&o!==vt.PLAYREADY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const f=yC(s),g=f.filter(p=>!!p.systemId&&vr(p.systemId)===o);g.length>1&&this.warn(`${n} Using first of ${g.length} pssh found for selected key-system ${o}`);const m=g[0];if(!m){f.length===0||f.some(p=>!p.systemId)?this.warn(`${n} contains incomplete or invalid pssh data`):this.log(`ignoring ${n} for ${f.map(p=>vr(p.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(h=vr(m.systemId),m.version===0&&m.data)if(h===vt.WIDEVINE){const p=m.data.length-22;l=new Uint8Array(m.data.subarray(p,p+16))}else h===vt.PLAYREADY&&(l=mu(m.data))}if(!h||!l)return;const u=Le.hexDump(l),{keyIdToKeySessionPromise:c,mediaKeySessions:d}=this;let A=c[u];for(let f=0;f<d.length;f++){const g=d[f],m=g.decryptdata;if(!m.keyId)continue;const p=Le.hexDump(m.keyId);if(u===p||m.uri.replace(/-/g,"").indexOf(u)!==-1){if(A=c[p],m.pssh)break;delete c[p],m.pssh=new Uint8Array(s),m.keyId=l,A=c[u]=A.then(()=>this.generateRequestWithPreferredKeySession(g,i,s,"encrypted-event-key-match")),A.catch(C=>this.handleError(C));break}}if(!A){if(h!==o){this.log(`Ignoring "${e.type}" event with ${h} init data for selected key-system ${o}`);return}A=c[u]=this.getKeySystemSelectionPromise([h]).then(({keySystem:f,mediaKeys:g})=>{var m;this.throwIfDestroyed();const p=new Ki("ISO-23001-7",u,(m=Br(f))!=null?m:"");return p.pssh=new Uint8Array(s),p.keyId=l,this.attemptSetMediaKeys(f,g).then(()=>{this.throwIfDestroyed();const C=this.createMediaKeySessionContext({decryptdata:p,keySystem:f,mediaKeys:g});return this.generateRequestWithPreferredKeySession(C,i,s,"encrypted-event-no-match")})}),A.catch(f=>this.handleError(f))}})}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){const t=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(t);const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(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===vt.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=(r,o,l)=>!!r&&l.indexOf(r)===o,s=e.map(r=>r.audioCodec).filter(i),n=e.map(r=>r.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((r,o)=>{const l=h=>{const u=h.shift();this.getMediaKeysPromise(u,s,n).then(c=>r({keySystem:u,mediaKeys:c})).catch(c=>{h.length?l(h):c instanceof ue?o(c):o(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.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 Ja===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=hy(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let r=n==null?void 0:n.keySystemAccess;if(!r){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Mt(s)}`),r=this.requestMediaKeySystemAccess(t,s);const o=this.keySystemAccessPromises[t]={keySystemAccess:r};return r.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`)}),r.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${t}"`),h.then(c=>c?this.setMediaKeysServerCertificate(u,t,c):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${t}"}: ${u}`)}),o.mediaKeys})}return r.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Le.hexDump(t.keyId||[])}`);const s=i.createSession(),n={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=this.getKeyIdString(e),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,e.pssh.buffer,"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 Le.hexDump(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Le.hexDump(((i=t.decryptdata)==null?void 0:i.keyId)||[])}
|
|
37
|
+
} (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=Ws(this.config),n=t.map(yr).filter(r=>!!r&&s.indexOf(r)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:r})=>{const o=Br(r);o?e(o):i(new Error(`Unable to find format for key-system "${r}"`))}).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 n=this.keyIdToKeySessionPromise[i];return n||(n=this.getKeySystemForKeyPromise(e).then(({keySystem:o,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:l,decryptdata:e}))))),(this.keyIdToKeySessionPromise[i]=n.then(o=>{const l="cenc",h=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,l,h,"playlist-key")})).catch(o=>this.handleError(o))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof ue?this.hls.trigger(I.ERROR,t.data):this.hls.trigger(I.ERROR,{type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const s=yr(t.keyFormat),n=s?[s]:Ws(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Ws(this.config)),t.length===0)throw new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Mt({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(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,e,i,s){var n,r;const o=(n=this.config.drmSystems)==null||(r=n[t.keySystem])==null?void 0:r.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=f.initData?f.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):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 h=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${h} (init data type: ${e} length: ${i?i.byteLength:null})`);const u=new za,c=t._onmessage=f=>{const g=t.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}const{messageType:m,message:p}=f;this.log(`"${m}" message event for session "${g.sessionId}" message size: ${p.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(t,p).catch(C=>{u.eventNames().length?u.emit("error",C):this.handleError(C)}):m==="license-release"?t.keySystem===vt.FAIRPLAY&&(this.updateKeySession(t,oa("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${m}"`)},d=t._onkeystatuseschange=f=>{if(!t.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const m=t.keyStatus;u.emit("keyStatus",m),m==="expired"&&(this.warn(`${t.keySystem} expired for key ${h}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",c),t.mediaKeysSession.addEventListener("keystatuseschange",d);const A=new Promise((f,g)=>{u.on("error",g),u.on("keyStatus",m=>{m.startsWith("usable")?f():m==="output-restricted"?g(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):m==="internal-error"?g(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${m}"`)):m==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${m}"`)})});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: ${h}`)}).catch(f=>{throw new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>A).catch(f=>{throw u.removeAllListeners(),this.removeSession(t),f}).then(()=>(u.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,i)=>{if(typeof i=="string"&&typeof e=="object"){const s=i;i=e,e=s}this.log(`key status change "${e}" for keyStatuses keyId: ${Le.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Le.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),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,o)=>{const l={responseType:"arraybuffer",url:n},h=e.certLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(d,A,f,g)=>{r(d.data)},onError:(d,A,f,g)=>{o(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:St({url:l.url,data:void 0},d)},`"${t}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,A,f)=>{o(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(d,A,f)=>{o(new Error("aborted"))}};s.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,n)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${e}"`),s(t)}).catch(r=>{n(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:r,fatal:!0},r.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(s=>{throw new ue({type:et.KEY_SYSTEM_ERROR,details:b.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"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,d=n.length;c<d;c++){var r,o;u=n[c];const A=(r=u.querySelector("name"))==null?void 0:r.textContent,f=(o=u.querySelector("value"))==null?void 0:o.textContent;A&&f&&t.setRequestHeader(A,f)}}const l=s.querySelector("Challenge"),h=l==null?void 0:l.textContent;if(!h)throw new Error("Cannot find <Challenge> in key message");return oa(atob(h))}setupLicenseXHR(t,e,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,e,i,s)}).catch(r=>{if(!i.decryptdata)throw r;return t.open("POST",e,!0),n.call(this.hls,t,e,i,s)}).then(r=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:r||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,n)=>{const r=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${r}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(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 h=this.config.licenseResponseCallback;if(h)try{l=h.call(this.hls,o,r,t)}catch(u){this.error(u)}s(l)}else{const l=i.errorRetry,h=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||o.status>=400&&o.status<500)n(new ue({type:et.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:r,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${r}). Status: ${o.status} (${o.statusText})`));else{const u=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(t,e).then(s,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,r,t,e).then(({xhr:l,licenseChallenge:h})=>{t.keySystem==vt.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(l,h)),l.send(h)})})}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;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(t){var e;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Ki.clearKeyUriToKeyIdMap();const s=i.length;pi.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat(t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(n=>{var r;this.log(`Could not clear media keys: ${n}`),(r=this.hls)==null||r.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)}).catch(n=>{var r;this.log(`Could not close sessions and clear media keys: ${n}`),(r=this.hls)==null||r.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=e.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.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);s>-1&&this.mediaKeySessions.splice(s,1);const{drmSystemOptions:n}=this.config;return(uy(n)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(o)}):Promise.resolve()).catch(o=>{var l;this.log(`Could not remove session: ${o}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>e.close()).catch(o=>{var l;this.log(`Could not close session: ${o}`),(l=this.hls)==null||l.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}}}pi.CDMCleanupPromise=void 0;class ue 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}}class rd{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),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const n=s-this.lastTime,r=i-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*r/n,h=this.hls;if(h.trigger(I.FPS_DROP,{currentDropped:r,currentDecoded:o,totalDroppedFrames:i}),l>0&&r>h.config.fpsDroppedMonitoringThreshold*o){let u=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=u)&&(u=u-1,h.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:h.currentLevel}),h.autoLevelCapping=u,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)}}function ad(a,t){let e;try{e=new Event("addtrack")}catch{e=document.createEvent("Event"),e.initEvent("addtrack",!1,!1)}e.track=a,t.dispatchEvent(e)}function od(a,t){const e=a.mode;if(e==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(t.id))try{if(a.addCue(t),!a.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){Et.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,a.addCue(s)}catch(s){Et.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}e==="disabled"&&(a.mode=e)}function ki(a,t){const e=a.mode;if(e==="disabled"&&(a.mode="hidden"),a.cues)for(let i=a.cues.length;i--;)t&&a.cues[i].removeEventListener("enter",t),a.removeCue(a.cues[i]);e==="disabled"&&(a.mode=e)}function ga(a,t,e,i){const s=a.mode;if(s==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const n=gB(a.cues,t,e);for(let r=0;r<n.length;r++)(!i||i(n[r]))&&a.removeCue(n[r])}s==="disabled"&&(a.mode=s)}function fB(a,t){if(t<=a[0].startTime)return 0;const e=a.length-1;if(t>a[e].endTime)return-1;let i=0,s=e,n;for(;i<=s;)if(n=Math.floor((s+i)/2),t<a[n].startTime)s=n-1;else if(t>a[n].startTime&&i<e)i=n+1;else return n;return a[i].startTime-t<t-a[s].startTime?i:s}function gB(a,t,e){const i=[],s=fB(a,t);if(s>-1)for(let n=s,r=a.length;n<r;n++){const o=a[n];if(o.startTime>=t&&o.endTime<=e)i.push(o);else if(o.startTime>e)return i}return i}function gn(a){const t=[];for(let e=0;e<a.length;e++){const i=a[e];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&t.push(a[e])}return t}class ld extends Kn{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const i=gn(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")e=i[n];else if(i[n].mode==="showing"){e=i[n];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(t,e){const i=this.media;if(!i)return;const s=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;gn(i.textTracks).forEach(r=>{ki(r)})}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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${r==null?void 0:r.groupId}`);return}const o=r.details;r.details=e.details,this.log(`Subtitle track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(r=>(s==null?void 0:s.indexOf(r))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const r=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(r.length)this.selectDefaultTrack&&!r.some(u=>u.default)&&(this.selectDefaultTrack=!1),r.forEach((u,c)=>{u.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=r;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const u=we(o,r);if(u>-1)n=r[u];else{const c=we(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const h={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,h),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const n=e[s];if(!(i&&!n.default||!i&&!t)&&(!t||mi(n,t)))return s}if(t){for(let s=0;s<e.length;s++){const n=e[s];if(Ds(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const n=e[s];if(Ds(t.attrs,n.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(da(s,t))return i}}return-1}onError(t,e){e.fatal||!e.context||e.context.type===gt.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){if(t.id===-1)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&mi(t,i))return i;const s=we(t,this.tracksInGroup);if(s>-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(i)return null;{const n=we(t,e);if(n>-1)return e[n]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=r==null?void 0:r.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=gn(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(n=>da(i,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){const n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}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.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 n=!!s.details&&!s.details.live;if(t===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${t}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:r,groupId:o="",name:l,type:h,url:u}=s;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:r,groupId:o,name:l,type:h,url:u});const c=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(c)}}function vs(a){let t=5381,e=a.length;for(;e;)t=t*33^a.charCodeAt(--e);return(t>>>0).toString()}const Gi=.025;let wn=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function mB(a,t,e){return`${a.identifier}-${e+1}-${vs(t)}`}class pB{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){if(t>=this.assetList.length)return!0;const e=this.playoutLimit;return t<=0||isNaN(e)?!1:this.assetList[t].startOffset>e}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return wr(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime,i=wr(e,t);return e-i<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=j(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return wr(t,e)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Gi))}set appendInPlace(t){if(this.appendInPlaceStarted){this.resetOnResume=!t;return}this.appendInPlaceDisabled=!t}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return this._duration!==null?e=this._duration:this.dateRange.duration?e=this.dateRange.duration:e=this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?wn.Range:wn.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return EB(this)}}function wr(a,t){return a-t.start<t.duration/2&&!(Math.abs(a-(t.start+t.duration))<Gi)?t.start:t.start+t.duration}function hd(a,t,e){const i=new self.URL(a,e);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",t),i}function EB(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function ma(a){const t=a.timelineStart,e=a.duration||0;return`["${a.identifier}" ${t.toFixed(2)}-${(t+e).toFixed(2)}]`}class IB{constructor(t,e,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const h=this.interstitial.playoutLimit,u=this.currentTime;this.startOffset+u>=h&&this.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new t(e);this.interstitial=i,this.assetItem=s;let r=s.uri;try{r=hd(r,n.sessionId).href}catch{}n.loadSource(r);const o=()=>{this.hasDetails=!0};n.once(I.LEVEL_LOADED,o),n.once(I.AUDIO_TRACK_LOADED,o),n.once(I.SUBTITLE_TRACK_LOADED,o),n.on(I.MEDIA_ATTACHING,(l,{media:h})=>{this.removeMediaListeners(),this.mediaAttached=h,this.interstitial.playoutLimit&&h.addEventListener("timeupdate",this.checkPlayout)})}bufferedInPlaceToEnd(t){var e;if(!this.interstitial.appendInPlace)return!1;if((e=this.hls)!=null&&e.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const i=this.timelineOffset,s=ft.bufferInfo(t,i,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=ft.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;return t||0}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return((t=this.hls)==null?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){this.hls.attachMedia(t)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(t,e,i){this.hls.on(t,e)}once(t,e,i){this.hls.once(t,e)}off(t,e,i){this.hls.off(t,e)}toString(){var t,e;return`HlsAssetPlayer: ${ma(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${(e=this.interstitial)!=null&&e.appendInPlace?"append-in-place":""}`}}const Ih=.033;class CB extends qe{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(e===void 0&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];if(e&&e!=="primary"&&(n=n[e]),t===n.start||t>n.start&&t<n.end)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if(((i=e[s].event)==null?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let n=0;n<s;n++){const r=i[n];if(!r.error){const o=r.timelineStart;if(e===o||e>o&&e<o+(r.duration||0))return n}}return 0}get assetIdAtEnd(){var t,e;const i=(t=this.items)==null||(e=t[this.length-1])==null?void 0:e.event;if(i){const s=i.assetList,n=s[s.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:s}=i,n=this.events,r=this.parseDateRanges(s,{url:i.url},e),o=Object.keys(s),l=n?n.filter(h=>!o.includes(h.identifier)):[];r.length&&r.sort((h,u)=>{const c=h.cue.pre,d=h.cue.post,A=u.cue.pre,f=u.cue.post;if(c&&!A)return-1;if(A&&!c||d&&!f)return 1;if(f&&!d)return-1;if(!c&&!A&&!d&&!f){const g=h.startTime,m=u.startTime;if(g!==m)return g-m}return h.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=r,l.forEach(h=>{this.removeEvent(h)}),this.updateSchedule(t,l)}updateSchedule(t,e=[]){const i=this.events||[];if(i.length||e.length||this.length<2){const s=this.items,n=this.parseSchedule(i,t);(e.length||(s==null?void 0:s.length)!==n.length||n.some((o,l)=>Math.abs(o.playout.start-s[l].playout.start)>.005||Math.abs(o.playout.end-s[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(e,s))}}parseDateRanges(t,e,i){const s=[],n=Object.keys(t);for(let r=0;r<n.length;r++){const o=n[r],l=t[o];if(l.isInterstitial){let h=this.eventMap[o];h?h.setDateRange(l):(h=new pB(l,e),this.eventMap[o]=h,i===!1&&(h.appendInPlace=i)),s.push(h)}}return s}parseSchedule(t,e){const i=[],s=e.main.details,n=s.live?1/0:s.edge;let r=0;if(t=t.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),t.length){this.resolveOffsets(t,e);let l=0,h=0;if(t.forEach((u,c)=>{const d=u.cue.pre,A=u.cue.post,f=t[c-1]||null,g=u.appendInPlace,m=A?n:u.startOffset,p=u.duration,C=u.timelineOccupancy===wn.Range?p:0,E=u.resumptionOffset,y=(f==null?void 0:f.startTime)===m,v=m+u.cumulativeDuration;let T=g?v+p:m+E;if(d||!A&&m<=0){const _=h;h+=C,u.timelineStart=v;const D=r;r+=p,i.push({event:u,start:v,end:T,playout:{start:D,end:r},integrated:{start:_,end:h}})}else if(m<=n){if(!y){const x=m-l;if(x>Ih){const M=l,k=h;h+=x;const X=r;r+=x;const W={previousEvent:t[c-1]||null,nextEvent:u,start:M,end:M+x,playout:{start:X,end:r},integrated:{start:k,end:h}};i.push(W)}else x>0&&f&&(f.cumulativeDuration+=x,i[i.length-1].end=m)}A&&(T=v),u.timelineStart=v;const _=h;h+=C;const D=r;r+=p,i.push({event:u,start:v,end:T,playout:{start:D,end:r},integrated:{start:_,end:h}})}else return;const B=u.resumeTime;A||B>n?l=n:l=B}),l<n){var o;const u=l,c=h,d=n-l;h+=d;const A=r;r+=d,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+d,playout:{start:A,end:r},integrated:{start:c,end:h}})}this.setDurations(n,r,h)}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,s=i.live?1/0:i.edge;let n=0,r=-1;t.forEach((o,l)=>{const h=o.cue.pre,u=o.cue.post,c=h?0:u?s:o.startTime;this.updateAssetDurations(o),r===c?o.cumulativeDuration=n:(n=0,r=c),!u&&o.snapOptions.in&&(o.resumeAnchor=Ei(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<t.length&&t[l+1].startTime-t[l].resumeTime<Ih&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const A=j(o.resumeOffset)?o.resumeOffset:o.duration;n+=A})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;return Math.abs(i-s)>Gi?(this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):e?!Object.keys(e).some(r=>{const o=e[r].details,l=o.edge;if(i>=l)return this.log(`"${t.identifier}" resumption ${i} past ${r} playlist end ${l}`),!1;const h=Ei(null,o.fragments,i);if(!h)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=r==="audio"?.175:0;return Math.abs(h.start-i)<Gi+u||Math.abs(h.end-i)<Gi+u?!1:(this.log(`"${t.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${h.start}-${h.end} sn: ${h.sn} cc: ${h.cc})`),!0)}):(this.log(`"${t.identifier}" resumption ${i} can not be aligned with media (none selected)`),!1)}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,n=!1;t.assetList.forEach((r,o)=>{const l=e+i;r.startOffset=i,r.timelineStart=l,s||(s=r.duration===null),n||(n=!!r.error);const h=r.error?0:r.duration||0;i+=h}),s&&!n?t.duration=Math.max(i,t.duration):t.duration=i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function je(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class yB{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=hd(i,this.hls.sessionId,t.baseUrl)}catch(d){const A=this.assignAssetListError(t,b.ASSET_LIST_LOAD_ERROR,d,i);this.hls.trigger(I.ERROR,A);return}e&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+e);const n=this.hls.config,r=n.loader,o=new r(n),l={responseType:"json",url:s.href},h=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(d,A,f,g)=>{const m=d.data,p=m==null?void 0:m.ASSETS;if(!Array.isArray(p)){const C=this.assignAssetListError(t,b.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,A,g);this.hls.trigger(I.ERROR,C);return}t.assetListResponse=m,this.hls.trigger(I.ASSET_LIST_LOADED,{event:t,assetListResponse:m,networkDetails:g})},onError:(d,A,f,g)=>{const m=this.assignAssetListError(t,b.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${A.url})`),A.url,g,f);this.hls.trigger(I.ERROR,m)},onTimeout:(d,A,f)=>{const g=this.assignAssetListError(t,b.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${A.url})`),A.url,d,f);this.hls.trigger(I.ERROR,g)}};return o.load(l,u,c),this.hls.trigger(I.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,n,r){return t.error=i,{type:et.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:r,stats:n}}}function Ye(a,t,e){Pe(a,t,e),a.addEventListener(t,e)}function Pe(a,t,e){a.removeEventListener(t,e)}function Ch(a){a==null||a.play().catch(()=>{})}class vB extends qe{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const r=s<=-.01;this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(r&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(),this.checkBuffer(),r&&i<o.start||i>=o.end){var l;const d=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!r){const A=this.findItemIndex(o);if(d>A){const f=this.schedule.findJumpRestrictedIndex(A+1,d);if(f>A){this.setSchedulePosition(f);return}}}this.setSchedulePosition(d);return}const h=this.playingAsset;if(!h){if(this.playingLastItem&&this.isInterstitial(o)){const d=o.event.assetList[0];d&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,d))}return}const u=h.timelineStart,c=h.duration||0;(r&&i<u||i>=u+c)&&this.setScheduleToAssetAtTime(i,h)},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const r=n.timelineStart+(n.duration||0);i>=r&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{const n=this.schedule,r=this.playingItem,o=n.events||[],l=n.items||[],h=n.durations,u=i.map(A=>A.identifier),c=!!(o.length||u.length);if(c&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
38
|
+
Schedule: ${l.map(A=>je(A))}`),u.length&&this.log(`Removed events ${u}`),this.playerQueue.forEach(A=>{if(A.interstitial.appendInPlace){const f=A.assetItem.timelineStart,g=A.timelineOffset-f;if(g)try{A.timelineOffset=f}catch(m){Math.abs(g)>Gi&&this.warn(`${m} ("${A.assetId}" ${A.timelineOffset}->${f})`)}}}),r){const A=this.updateItem(r,this.timelinePos);this.itemsMatch(r,A)&&(this.playingItem=A,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d){const A=this.updateItem(d,this.bufferedPos);this.itemsMatch(d,A)?this.bufferingItem=A:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))}if(i.forEach(A=>{A.assetList.forEach(f=>{this.clearAssetPlayer(f.identifier,null)})}),c||s){if(this.hls.trigger(I.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:h,removedIds:u}),this.isInterstitial(r)&&u.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new yB(t),this.schedule=new CB(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,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_UPDATED,this.onLevelUpdated,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(I.BUFFER_APPENDED,this.onBufferAppended,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(I.MEDIA_ENDED,this.onMediaEnded,this),t.on(I.ERROR,this.onError,this),t.on(I.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,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_UPDATED,this.onLevelUpdated,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(I.BUFFER_CODECS,this.onBufferCodecs,this),t.off(I.BUFFER_APPENDED,this.onBufferAppended,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(I.MEDIA_ENDED,this.onMediaEnded,this),t.off(I.ERROR,this.onError,this),t.off(I.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;(t=this.getBufferingPlayer())==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.getBufferingPlayer())==null||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Pe(t,"play",this.onPlay),Pe(t,"pause",this.onPause),Pe(t,"seeking",this.onSeeking),Pe(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;Ye(i,"seeking",this.onSeeking),Ye(i,"timeupdate",this.onTimeupdate),Ye(i,"play",this.onPlay),Ye(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=c=>c&&t.getAssetPlayer(c.identifier),s=(c,d,A,f,g)=>{if(c){let m=c[d].start;const p=c.event;if(p){if(d==="playout"||p.timelineOccupancy!==wn.Point){const C=i(A);(C==null?void 0:C.interstitial)===p&&(m+=C.assetItem.startOffset+C[g])}}else{const C=f==="bufferedPos"?r():t[f];m+=C-c.start}return m}return 0},n=(c,d)=>{if(c!==0&&d!=="primary"&&t.schedule.length){var A;const f=t.schedule.findItemIndexAtTime(c),g=(A=t.schedule.items)==null?void 0:A[f];if(g){const m=g[d].start-g.start;return c+m}}return c},r=()=>{const c=t.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var d;return(d=t.primaryDetails)!=null&&d.live?t.primaryDetails.edge:t.schedule.durations[c]},l=(c,d)=>{var A,f;const g=t.effectivePlayingItem;if(g!=null&&(A=g.event)!=null&&A.restrictions.skip)return;t.log(`seek to ${c} "${d}"`);const m=t.effectivePlayingItem,p=t.schedule.findItemIndexAtTime(c,d),C=(f=t.schedule.items)==null?void 0:f[p],E=t.getBufferingPlayer(),y=E==null?void 0:E.interstitial,v=y==null?void 0:y.appendInPlace,T=m&&t.itemsMatch(m,C);if(m&&(v||T)){const _=i(t.playingAsset),D=(_==null?void 0:_.media)||t.primaryMedia;if(D){const x=d==="primary"?D.currentTime:s(m,d,t.playingAsset,"timelinePos","currentTime"),M=c-x,k=(v?x:D.currentTime)+M;if(k>=0&&(!_||v||k<=_.duration)){D.currentTime=k;return}}}if(C){let _=c;if(d!=="primary"){const x=C[d].start,M=c-x;_=C.start+M}const D=!t.isInterstitial(C);if((!t.isInterstitial(m)||m.event.appendInPlace)&&(D||C.event.appendInPlace)){const x=t.media||(v?E==null?void 0:E.media:null);x&&(x.currentTime=_)}else if(m){const x=t.findItemIndex(m);if(p>x){const k=t.schedule.findJumpRestrictedIndex(x+1,p);if(k>x){t.setSchedulePosition(k);return}}let M=0;if(D)t.timelinePos=_,t.checkBuffer();else{var B;const k=C==null||(B=C.event)==null?void 0:B.assetList;if(k){const X=c-(C[d]||C).start;for(let W=k.length;W--;){const H=k[W];if(H.duration&&X>=H.startOffset&&X<H.startOffset+H.duration){M=W;break}}}}t.setSchedulePosition(p,M)}}},h=()=>{const c=t.effectivePlayingItem;if(t.isInterstitial(c))return c;const d=e();return t.isInterstitial(d)?d:null},u={get currentTime(){const c=h(),d=t.effectivePlayingItem;return d&&d===c?s(d,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(c){const d=h(),A=t.effectivePlayingItem;A&&A===d&&l(c+A.playout.start,"playout")},get duration(){const c=h();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const d=(c=h())==null?void 0:c.event.assetList;return d?d.map(A=>t.getAssetPlayer(A.identifier)):[]},get playingIndex(){var c;const d=(c=h())==null?void 0:c.event;return d&&t.effectivePlayingAsset?d.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return h()}};this.manager={get events(){var c,d;return((c=t.schedule)==null||(d=c.events)==null?void 0:d.slice(0))||[]},get schedule(){var c,d;return((c=t.schedule)==null||(d=c.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return h()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const c=e();return t.findItemIndex(c)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const c=t.effectivePlayingItem;return t.findItemIndex(c)},primary:{get bufferedEnd(){return r()},get currentTime(){const c=t.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=t.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=t.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=t.effectivePlayingItem,d=c==null?void 0:c.event;if(d&&!d.restrictions.skip){const A=t.findItemIndex(c);if(d.appendInPlace){const f=c.playout.start+c.event.duration;l(f+.001,"playout")}else t.advanceAfterAssetEnded(d,A,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!e||!i?!1:this.findItemIndex(e)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,e,i;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let n=this.media;!n&&(t=this.bufferingItem)!=null&&(e=t.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(i=n)==null?void 0:i.currentTime;if(!(r===void 0||!j(r)))return r}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s){this.detachedData={media:s};return}const n=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Mt(n)}`),this.detachedData=n}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let n=null;const r=this.hls,o=t!==r,l=o&&t.interstitial.appendInPlace,h=(i=this.detachedData)==null?void 0:i.mediaSource;let u;if(r.media)l&&(n=r.transferMedia(),this.detachedData=n),u="Primary";else if(h){const A=this.getBufferingPlayer();A?(n=A.transferMedia(),u=`${A}`):u="detached MediaSource"}else u="detached media";if(!n){if(h)n=this.detachedData,this.log(`using detachedData: MediaSource ${Mt(n)}`);else if(!this.detachedData||r.media===e){const A=this.playerQueue;A.length>1&&A.forEach(f=>{if(o&&f.interstitial.appendInPlace!==l){const g=f.interstitial;this.clearInterstitial(f.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}}const c=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed",d=c&&n?n:e;if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u}`),d===n){const A=o&&t.assetId===this.schedule.assetIdAtEnd;d.overrides={duration:this.schedule.duration,endOfStream:!o||A,cueRemoval:!o}}t.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=t.events;if(!e||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(i===-1){const n=this.hls.startPosition;if(this.timelinePos=n,e.length&&e[0].cue.pre){const r=t.findEventIndex(e[0].identifier);this.setSchedulePosition(r)}else if(n>=0||!this.primaryLive){const r=this.timelinePos=n>0?n:0,o=t.findItemIndexAtTime(r);this.setSchedulePosition(o)}}else if(s&&!this.playingItem){const n=t.findItemIndex(s);this.setSchedulePosition(n)}}advanceAfterAssetEnded(t,e,i){const s=i+1;if(!t.isAssetPastPlayoutLimit(s)&&!t.assetList[s].error)this.setSchedulePosition(e,s);else{const n=this.schedule.items;if(n){const r=e+1,o=n.length;if(r>=o){this.setSchedulePosition(-1);return}const l=t.resumeTime;this.timelinePos<l&&(this.timelinePos=l,this.checkBuffer()),this.setSchedulePosition(r)}}}setScheduleToAssetAtTime(t,e){const i=this.schedule,s=e.parentIdentifier,n=i.getEvent(s);if(n){const r=i.findEventIndex(s),o=i.findAssetIndex(n,t);this.setSchedulePosition(r,o)}}setSchedulePosition(t,e){const i=this.schedule.items;if(!i||this.playbackDisabled)return;this.log(`setSchedulePosition ${t}, ${e}`);const s=t>=0?i[t]:null,n=this.playingItem,r=this.playingLastItem;if(this.isInterstitial(n)){var o;const h=n.event,u=this.playingAsset,c=u==null?void 0:u.identifier,d=c?this.getAssetPlayer(c):null;if(d&&c&&(!this.eventItemsMatch(n,s)||e!==void 0&&c!==((o=h.assetList)==null?void 0:o[e].identifier))){var l;const A=h.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${A+1}/${h.assetList.length} ${ma(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:A,event:h,schedule:i.slice(0),scheduleIndex:t,player:d}),this.retreiveMediaSource(c,s),d.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&d.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${je(n)}`),h.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:t}),h.cue.once)){this.updateSchedule();const A=this.schedule.items;if(s&&A){const f=this.schedule.findItemIndex(s);this.advanceSchedule(f,A,e,n,r)}return}}this.advanceSchedule(t,i,e,n,r)}advanceSchedule(t,e,i,s,n){const r=t>=0?e[t]:null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,c=this.schedule.findEventIndex(u.identifier);(c<t||c>t+1)&&this.clearInterstitial(u,r)}),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const h=r.event;i===void 0&&(i=this.schedule.findAssetIndex(h,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(r,o)||this.setBufferingItem(r);let c=this.preloadAssets(h,i);if(this.eventItemsMatch(r,u||s)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${je(r)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:h,schedule:e.slice(0),scheduleIndex:t})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=r;const d=h.assetList[i];if(!d){const A=e[t+1],f=this.media;A&&f&&!this.isInterstitial(A)&&f.currentTime<A.start&&(f.currentTime=this.timelinePos=A.start),this.advanceAfterAssetEnded(h,t,i||0);return}if(c||(c=this.getAssetPlayer(d.identifier)),c===null||c.destroyed){const A=h.assetList.length;this.warn(`asset ${i+1}/${A} player destroyed ${h}`),c=this.createAssetPlayer(h,d,i)}if(!this.eventItemsMatch(r,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(c,i,e,t,o),this.shouldPlay&&Ch(c.media)}else r!==null?(this.resumePrimary(r,t,s),this.shouldPlay&&Ch(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t,e;return(t=this.mediaSelection)==null||(e=t.main)==null?void 0:e.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,e,i){var s;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${je(t)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let r=this.timelinePos;(r<t.start||r>=t.end)&&(r=this.getPrimaryResumption(t,e),this.timelinePos=r),this.attachPrimary(r,t)}if(!i)return;const n=this.schedule.items;n&&(this.log(`resumed ${je(t)}`),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const s=this.primaryDetails;if(e===0)return this.hls.startPosition;if(s&&(i<s.fragmentStart||i>s.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);return e!=null&&e.hls?e.hls.bufferedToEnd:ft.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-t)>.5?s.startLoad(t,e):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(I.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(I.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(e.level===-1)return;const i=this.hls.levels[e.level],s=St(St({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s){this.altSelection=St(St({},this.altSelection),{},{audio:i});return}const n=St(St({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s){this.altSelection=St(St({},this.altSelection),{},{subtitles:i});return}const n=St(St({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(t,e){const i=wl(e);this.playerQueue.forEach(s=>s.hls.setAudioOption(e)||s.hls.setAudioOption(i))}onSubtitleTrackSwitch(t,e){const i=wl(e);this.playerQueue.forEach(s=>s.hls.setSubtitleOption(e)||e.id!==-1&&s.hls.setSubtitleOption(i))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(t){const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let s=0;s<e.length;s++){const n=e[s];if(n.cue.post){var i;const r=this.schedule.findEventIndex(n.identifier),o=(i=this.schedule.items)==null?void 0:i[r];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const i=this.findItemIndex(e);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(t,e){const i=this.schedule.items;if(t&&i){const s=this.findItemIndex(t,e);return i[s]||null}return null}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===((i=e.event)==null?void 0:i.identifier))}findItemIndex(t,e){return t?this.schedule.findItemIndex(t,e):-1}updateSchedule(){const t=this.mediaSelection;t&&this.schedule.updateSchedule(t,[])}checkBuffer(t){const e=this.schedule.items;if(!e)return;const i=ft.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,e,t)}updateBufferedPos(t,e,i){const s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>t)return;if(e.length===1&&this.itemsMatch(e[0],n)){this.bufferedPos=t;return}const r=this.playingItem,o=this.findItemIndex(r);let l=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var h,u;const c=this.findItemIndex(n),d=Math.min(c+1,e.length-1),A=e[d];if((l===-1&&n&&t>=n.end||(h=A.event)!=null&&h.appendInPlace&&t+.01>=A.start)&&(l=d),d-o>1&&(n==null||(u=n.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=t,l>c&&l>o)this.bufferedToItem(A);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&A.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(A)&&this.preloadAssets(A.event,0)}}else i&&r&&!this.itemsMatch(r,n)&&(l===o?this.bufferedToItem(r):l===o+1&&this.bufferedToItem(e[l]))}assetsBuffered(t,e){return t.event.assetList.length===0?!1:!t.event.assetList.some(s=>{const n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(this.itemsMatch(t,e))this.bufferingItem!==t&&(this.bufferingItem=t);else{const{items:s,events:n}=i;if(!s||!n)return e;const r=this.isInterstitial(t),o=this.getBufferingPlayer();if(this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos)),!this.playbackDisabled){const l=o?o.remaining:e?e.end-this.timelinePos:0;this.log(`buffered to boundary ${je(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),r?t.event.assetList.forEach(h=>{const u=this.getAssetPlayer(h.identifier);u&&u.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(h=>h.pauseBuffering()))}this.hls.trigger(I.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(i!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){const r=this.preloadAssets(i,e);if(r!=null&&r.interstitial.appendInPlace){const o=i.assetList[e],l=this.primaryMedia;o&&l&&this.bufferAssetPlayer(r,l)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,n=s===0&&!t.assetListLoader,r=t.cue.once;if(n){const l=t.timelineStart;if(t.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(l+.25)}let h,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(t.cue.pre||t.cue.post)){const d=u-l;d>0&&(h=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${h?` live-start: ${u} start-offset: ${h}`:""}`),i)return this.createAsset(t,0,0,l,t.duration,i);const c=this.assetListLoader.loadAssetList(t,h);c&&(t.assetListLoader=c)}else if(!r&&s){for(let l=e;l<s;l++){const h=t.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(t,h,l)}return this.getAssetPlayer(t.assetList[e].identifier)}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`),Object.keys(e).forEach(s=>{this.hls.trigger(I.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:s})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e){for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i]}return null}createAsset(t,e,i,s,n,r){const o={parentIdentifier:t.identifier,identifier:mB(t,r,e),duration:n,startOffset:i,timelineStart:s,uri:r};return this.createAssetPlayer(t,o,e)}createAssetPlayer(t,e,i){this.log(`create HLSAssetPlayer for ${ma(e)}`);const s=this.hls,n=s.userConfig;let r=n.videoPreference;const o=s.loadLevelObj||s.levels[s.currentLevel];(r||o)&&(r=xt({},r),o.videoCodec&&(r.videoCodec=o.videoCodec),o.videoRange&&(r.allowedVideoRanges=[o.videoRange]));const l=s.audioTracks[s.audioTrack],h=s.subtitleTracks[s.subtitleTrack];let u=0;if(this.primaryLive||t.appendInPlace){const E=this.timelinePos-e.timelineStart;if(E>1){const y=e.duration;y&&E<y&&(u=E)}}const c=e.identifier,d=St(St({},n),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:r,audioPreference:l||n.audioPreference,subtitlePreference:h||n.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(d.timelineOffset=e.timelineStart));const A=d.cmcd;A!=null&&A.sessionId&&A.contentId&&(d.cmcd=xt({},A,{contentId:vs(e.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${t} and asset ${c}`);const f=new IB(this.HlsPlayerClass,d,t,e);this.playerQueue.push(f),t.assetList[i]=e;const g=E=>{if(E.live){const T=new Error(`Interstitials MUST be VOD assets ${t}`),B={fatal:!0,type:et.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(B,t,this.schedule.findEventIndex(t.identifier),i,T.message);return}const y=E.edge-E.fragmentStart,v=e.duration;(v===null||y>v)&&(this.log(`Interstitial asset "${c}" duration change ${v} > ${y}`),e.duration=y,this.updateSchedule())};f.on(I.LEVEL_UPDATED,(E,{details:y})=>g(y)),f.on(I.LEVEL_PTS_UPDATED,(E,{details:y})=>g(y));const m=(E,y)=>{const v=this.getAssetPlayer(c);if(v&&y.tracks){v.off(I.BUFFER_CODECS,m),v.tracks=y.tracks;const T=this.primaryMedia;this.bufferingAsset===v.assetItem&&T&&!v.media&&this.bufferAssetPlayer(v,T)}};f.on(I.BUFFER_CODECS,m);const p=()=>{var E;const y=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${y}`),!y)return;const v=this.schedule.findEventIndex(t.identifier),T=t.findAssetIndex(e),B=T+1,_=(E=this.schedule.items)==null?void 0:E[v];if(this.isInterstitial(_))if(T!==-1&&!t.isAssetPastPlayoutLimit(B)&&!t.assetList[B].error)this.bufferedToItem(_,B);else{var D;const x=(D=this.schedule.items)==null?void 0:D[v+1];x&&this.bufferedToItem(x)}};f.on(I.BUFFERED_TO_END,p);const C=E=>()=>{if(!this.getAssetPlayer(c))return;this.shouldPlay=!0;const v=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,v,E)};return f.once(I.MEDIA_ENDED,C(i)),f.once(I.PLAYOUT_LIMIT_REACHED,C(1/0)),f.on(I.ERROR,(E,y)=>{const v=this.getAssetPlayer(c);if(y.details===b.BUFFER_STALLED_ERROR){if(v!=null&&v.media){const T=v.currentTime,B=v.duration-T;T&&t.appendInPlace&&B/v.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${c} ${t} at ${v.media.currentTime}`),p()):(this.warn(`Stalled at ${T} of ${T+B} in asset ${c} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(y,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${y.error} ${t}`)}),f.on(I.DESTROYING,()=>{if(!this.getAssetPlayer(c))return;const y=new Error(`Asset player destroyed unexpectedly ${c}`),v={fatal:!0,type:et.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:y};this.handleAssetItemError(v,t,this.schedule.findEventIndex(t.identifier),i,y.message)}),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:f}),f}clearInterstitial(t,e){t.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,e)}),t.reset()}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(i!==-1){this.log(`clearAssetPlayer "${t}" toSegment: ${e&&je(e)}`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,e),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,n){const{interstitial:r,assetItem:o,assetId:l}=t,h=r.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,i[s]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${t}`),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:r,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,n)}bufferAssetPlayer(t,e){var i,s;const{interstitial:n,assetItem:r,assetId:o}=t,l=this.schedule.findEventIndex(n.identifier),h=(i=this.schedule.items)==null?void 0:i[l];if(!h)return;this.setBufferingItem(h),this.bufferingAsset=r;const u=this.getBufferingPlayer();if(u===t)return;const c=n.appendInPlace;if(c&&(u==null?void 0:u.interstitial.appendInPlace)===!1)return;const d=(u==null?void 0:u.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(c&&r!==this.playingAsset){if(!t.tracks)return;if(d&&!Jc(d,t.tracks)){const A=new Error(`Asset "${o}" SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:et.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:A},g=n.findAssetIndex(r);this.handleAssetItemError(f,n,l,g,A.message);return}}this.transferMediaTo(t,e)}handleAssetItemError(t,e,i,s,n){if(t.details===b.BUFFER_STALLED_ERROR)return;const r=e.assetList[s]||null;let o=null;if(r){const c=this.getAssetPlayerQueueIndex(r.identifier);o=this.playerQueue[c]||null}const l=this.schedule.items,h=xt({},t,{fatal:!1,errorAction:Ss(!0),asset:r,assetListIndex:s,event:e,schedule:l,scheduleIndex:i,player:o});if(this.warn(`Asset item error: ${t.error}`),this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,h),!t.fatal)return;const u=new Error(n);r&&(this.playingAsset!==r&&this.clearAssetPlayer(r.identifier,null),r.error=u),e.assetList.some(c=>!c.error)?e.appendInPlace&&(e.error=u):e.error=u,this.primaryFallback(e)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${this.timelinePos} playing: ${i?je(i):"<none>"} error: ${t.error}`),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e));let s=this.timelinePos;s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);if(this.itemsMatch(i,n))this.clearInterstitial(t,null);else{const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}}else this.checkStart()}onAssetListLoaded(t,e){var i;const s=e.event,n=s.identifier,r=e.assetListResponse.ASSETS;if(!this.schedule.hasEvent(n))return;const o=s.timelineStart,l=s.duration;let h=0;r.forEach((f,g)=>{const m=parseFloat(f.DURATION);this.createAsset(s,g,h,o+h,m,f.URI),h+=m}),s.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${s}`);const u=this.waitingItem,c=(u==null?void 0:u.event.identifier)===n;this.updateSchedule();const d=(i=this.bufferingItem)==null?void 0:i.event;if(c){var A;const f=this.schedule.findEventIndex(n),g=(A=this.schedule.items)==null?void 0:A[f];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==f){s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),this.primaryFallback(s);return}this.setBufferingItem(g)}this.setSchedulePosition(f)}else if((d==null?void 0:d.identifier)===n&&d.appendInPlace){const f=s.assetList[0],g=this.getAssetPlayer(f.identifier),m=this.primaryMedia;f&&g&&m&&this.bufferAssetPlayer(g,m)}}onError(t,e){switch(e.details){case b.ASSET_LIST_PARSING_ERROR:case b.ASSET_LIST_LOAD_ERROR:case b.ASSET_LIST_LOAD_TIMEOUT:{const i=e.interstitial;i&&this.primaryFallback(i);break}case b.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const yh=500;class cd extends Nn{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",Z.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(I.LEVEL_LOADED,this.onLevelLoaded,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)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(I.LEVEL_LOADED,this.onLevelLoaded,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)}startLoad(t,e){this.stopLoad(),this.state=G.IDLE,this.setInterval(yh),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(zt(i)&&(this.fragPrevious=i),this.state=G.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let r;const o=i.start;for(let h=0;h<n.length;h++)if(o>=n[h].start&&o<=n[h].end){r=n[h];break}const l=i.start+i.duration;r?r.end=l:(r={start:o,end:l},n.push(r)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(r=>{for(let o=0;o<r.length;){if(r[o].end<=n){r.shift();continue}else if(r[o].start<n)r[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,Z.SUBTITLE)}}onError(t,e){const i=e.frag;(i==null?void 0:i.type)===Z.SUBTITLE&&(e.details===b.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==G.STOPPED&&(this.state=G.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(this.levels&&zu(this.levels,e)){this.levels=e.map(i=>new Hi(i));return}this.tracksBuffered=[],this.levels=e.map(i=>{const s=new Hi(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Z.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.state!==G.STOPPED&&this.setInterval(yh)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:n}=this,{details:r,id:o}=e;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(r.live||(i=l.details)!=null&&i.live){const c=this.mainDetails;if(r.deltaUpdateFailed||!c)return;const d=c.fragments[0];if(!l.details)r.hasProgramDateTime&&c.hasProgramDateTime?(Ln(r,c),h=r.fragmentStart):d&&(h=d.start,ha(r,h));else{var u;h=this.alignPlaylists(r,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),h===0&&d&&(h=d.start,ha(r,h))}}l.details=r,this.levelLastLoaded=l,o===s&&(this.hls.trigger(I.SUBTITLE_TRACK_UPDATED,{details:r,id:o,groupId:e.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===G.IDLE&&(Ei(null,r.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,n=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&Ui(s.method)){const r=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Ya(s.method)).catch(o=>{throw n.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:e}),o}).then(o=>{const l=performance.now();n.trigger(I.FRAG_DECRYPTED,{frag:e,payload:o,stats:{tstart:r,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=G.IDLE})}}doTick(){if(!this.media){this.state=G.IDLE;return}if(this.state===G.IDLE){const{currentTrackId:t,levels:e}=this,i=e==null?void 0:e[t];if(!i||!e.length||!i.details||this.waitForLive(i))return;const{config:s}=this,n=this.getLoadPosition(),r=ft.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:l}=r,h=i.details,u=this.hls.maxBufferLength+h.levelTargetDuration;if(l>u)return;const c=h.fragments,d=c.length,A=h.edge;let f=null;const g=this.fragPrevious;if(o<A){const C=s.maxFragLookUpTolerance,E=o>A-C?0:C;f=Ei(g,c,Math.max(c[0].start,o),E),!f&&g&&g.start<c[0].start&&(f=c[0])}else f=c[d-1];if(f=this.filterReplacedPrimary(f,i.details),!f)return;const m=f.sn-h.startSN,p=c[m-1];if(p&&p.cc===f.cc&&this.fragmentTracker.getState(p)===$t.NOT_LOADED&&(f=p),this.fragmentTracker.getState(f)===$t.NOT_LOADED){const C=this.mapToInitFragWhenRequired(f);C&&this.loadFragment(C,i,o)}}}loadFragment(t,e,i){zt(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new BB(this.tracksBuffered[this.currentTrackId]||[])}}class BB{constructor(t){this.buffered=void 0;const e=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);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)}}}}const SB={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},ud=a=>String.fromCharCode(SB[a]||a),Ce=15,Qe=100,TB={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},_B={17:2,18:4,21:6,22:8,23:10,19:13,20:15},xB={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},DB={25:2,26:4,29:6,30:8,31:10,27:13,28:15},RB=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class LB{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i=typeof e=="function"?e():e;Et.log(`${this.time} [${t}] ${i}`)}}}const Ai=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class dd{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 bB{constructor(){this.uchar=" ",this.penState=new dd}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 wB{constructor(t){this.chars=[],this.pos=0,this.currPenState=new dd,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Qe;e++)this.chars.push(new bB);this.logger=t}equals(t){for(let e=0;e<Qe;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Qe;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Qe;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>Qe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Qe)}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=ud(t);if(this.pos>=Qe){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<Qe;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<Qe;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 Pr{constructor(t){this.rows=[],this.currRow=Ce-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Ce;e++)this.rows.push(new wB(t));this.logger=t}reset(){for(let t=0;t<Ce;t++)this.rows[t].clear();this.currRow=Ce-1}equals(t){let e=!0;for(let i=0;i<Ce;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Ce;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Ce;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 = "+Mt(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<Ce;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const o=r.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let h=0;h<this.nrRollUpRows;h++)this.rows[e-this.nrRollUpRows+h+1].copy(r.rows[n+h])}}this.currRow=e;const i=this.rows[this.currRow];if(t.indent!==null){const n=t.indent,r=Math.max(n-1,0);i.setCursor(t.indent),t.color=i.chars[r].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 = "+Mt(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 n=0;n<Ce;n++){const r=this.rows[n].getTextString();r&&(s=n+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(t?i="["+e.join(" | ")+"]":i=e.join(`
|
|
39
|
+
`)),i}getTextAndFormat(){return this.rows}}class vh{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 Pr(i),this.nonDisplayedMemory=new Pr(i),this.lastOutputScreen=new Pr(i),this.currRollUpRow=this.displayedMemory.rows[Ce-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[Ce-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: "+Mt(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Bh{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=MB(),this.logger=void 0;const s=this.logger=new LB;this.channels=[null,new vh(t,e,s),new vh(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,n=e[i+1]&127;let r=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+Ai([e[i],e[i+1]])+"] -> ("+Ai([s,n])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(PB(s,n,l)){sn(null,null,l),this.logger.log(3,()=>"Repeated command ("+Ai([s,n])+") is dropped");continue}sn(s,n,this.cmdHistory),r=this.parseCmd(s,n),r||(r=this.parseMidrow(s,n)),r||(r=this.parsePAC(s,n)),r||(r=this.parseBackgroundAttributes(s,n))}else sn(null,null,l);if(!r&&(o=this.parseChars(s,n),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!r&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ai([s,n])+" orig: "+Ai([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 n=t===20||t===21||t===23?1:2,r=this.channels[n];return t===20||t===21||t===28||t===29?e===32?r.ccRCL():e===33?r.ccBS():e===34?r.ccAOF():e===35?r.ccAON():e===36?r.ccDER():e===37?r.ccRU(2):e===38?r.ccRU(3):e===39?r.ccRU(4):e===40?r.ccFON():e===41?r.ccRDC():e===42?r.ccTR():e===43?r.ccRTD():e===44?r.ccEDM():e===45?r.ccCR():e===46?r.ccENM():e===47&&r.ccEOC():r.ccTO(e-32),this.currentChannel=n,!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 ("+Ai([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,n=(t===16||t===24)&&e>=64&&e<=95;if(!(s||n))return!1;const r=t<=23?1:2;e>=64&&e<=95?i=r===1?TB[t]:xB[t]:i=r===1?_B[t]:DB[t];const o=this.channels[r];return o?(o.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!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,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let r;n===17?r=e+80:n===18?r=e+112:r=e+144,this.logger.log(2,()=>"Special char '"+ud(r)+"' in channel "+i),s=[r]}else t>=32&&t<=127&&(s=e===0?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+Ai(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 n;const r={};t===16||t===24?(n=Math.floor((e-32)/2),r.background=RB[n],e%2===1&&(r.background=r.background+"_semi")):e===45?r.background="transparent":(r.foreground="black",e===47&&(r.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(r),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}sn(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 sn(a,t,e){e.a=a,e.b=t}function PB(a,t,e){return e.a===a&&e.b===t}function MB(){return{a:null,b:null}}var io=function(){if(Rn!=null&&Rn.VTTCue)return self.VTTCue;const a=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function i(o){return e(a,o)}function s(o){return e(t,o)}function n(o,...l){let h=1;for(;h<arguments.length;h++){const u=arguments[h];for(const c in u)o[c]=u[c]}return o}function r(o,l,h){const u=this,c={enumerable:!0};u.hasBeenReset=!1;let d="",A=!1,f=o,g=l,m=h,p=null,C="",E=!0,y="auto",v="start",T=50,B="middle",_=50,D="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return d},set:function(x){d=""+x}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return A},set:function(x){A=!!x}})),Object.defineProperty(u,"startTime",n({},c,{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(u,"endTime",n({},c,{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(u,"text",n({},c,{get:function(){return m},set:function(x){m=""+x,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return p},set:function(x){p=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return C},set:function(x){const M=i(x);if(M===!1)throw new SyntaxError("An invalid or illegal string was specified.");C=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return E},set:function(x){E=!!x,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return y},set:function(x){if(typeof x!="number"&&x!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return v},set:function(x){const M=s(x);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return T},set:function(x){if(x<0||x>100)throw new Error("Position must be between 0 and 100.");T=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return B},set:function(x){const M=s(x);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");B=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},c,{get:function(){return _},set:function(x){if(x<0||x>100)throw new Error("Size must be between 0 and 100.");_=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},c,{get:function(){return D},set:function(x){const M=s(x);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");D=M,this.hasBeenReset=!0}})),u.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class FB{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Ad(a){function t(i,s,n,r){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(r||0)}const e=a.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 kB{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(a,t,e,i){const s=i?a.split(i):[a];for(const n in s){if(typeof s[n]!="string")continue;const r=s[n].split(e);if(r.length!==2)continue;const o=r[0],l=r[1];t(o,l)}}const pa=new io(0,0,""),nn=pa.align==="middle"?"middle":"center";function OB(a,t,e){const i=a;function s(){const o=Ad(a);if(o===null)throw new Error("Malformed timestamp: "+i);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const h=new kB;fd(o,function(d,A){let f;switch(d){case"region":for(let g=e.length-1;g>=0;g--)if(e[g].id===A){h.set(d,e[g].region);break}break;case"vertical":h.alt(d,A,["rl","lr"]);break;case"line":f=A.split(","),h.integer(d,f[0]),h.percent(d,f[0])&&h.set("snapToLines",!1),h.alt(d,f[0],["auto"]),f.length===2&&h.alt("lineAlign",f[1],["start",nn,"end"]);break;case"position":f=A.split(","),h.percent(d,f[0]),f.length===2&&h.alt("positionAlign",f[1],["start",nn,"end","line-left","line-right","auto"]);break;case"size":h.percent(d,A);break;case"align":h.alt(d,A,["start",nn,"end","left","right"]);break}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let u=h.get("line","auto");u==="auto"&&pa.line===-1&&(u=-1),l.line=u,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",nn);let c=h.get("position","auto");c==="auto"&&pa.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function r(){a=a.replace(/^\s+/,"")}if(r(),t.startTime=s(),r(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);a=a.slice(3),r(),t.endTime=s(),r(),n(a,t)}function gd(a){return a.replace(/<br(?: \/)?>/gi,`
|
|
40
|
+
`)}class QB{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new FB,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 n=e.buffer,r=0;for(n=gd(n);r<n.length&&n[r]!=="\r"&&n[r]!==`
|
|
41
|
+
`;)++r;const o=n.slice(0,r);return n[r]==="\r"&&++r,n[r]===`
|
|
42
|
+
`&&++r,e.buffer=n.slice(r),o}function s(n){fd(n,function(r,o){},/:/)}try{let n="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;n=i();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:n=i(),e.state){case"HEADER":/:/.test(n)?s(n):n||(e.state="ID");continue;case"NOTE":n||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){e.state="NOTE";break}if(!n)continue;if(e.cue=new io(0,0,""),e.state="CUE",n.indexOf("-->")===-1){e.cue.id=n;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{OB(n,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(r=!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+=`
|
|
43
|
+
`),e.cue.text+=n}continue;case"BADCUE":n||(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+=`
|
|
44
|
+
|
|
45
|
+
`,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 UB=/\r\n|\n\r|\n|\r/g,Mr=function(t,e,i=0){return t.slice(i,i+e.length)===e},GB=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!j(e)||!j(i)||!j(s)||!j(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=60*1e3*s,e+=60*60*1e3*n,e};function so(a,t,e){return vs(a.toString())+vs(t.toString())+vs(e)}const NB=function(t,e,i){let s=t[e],n=t[s.prevCC];if(!n||!n.new&&s.new){t.ccOffset=t.presentationOffset=s.start,s.new=!1;return}for(;(r=n)!=null&&r.new;){var r;t.ccOffset+=s.start-n.start,s.new=!1,s=n,n=t[s.prevCC]}t.presentationOffset=i};function HB(a,t,e,i,s,n,r){const o=new QB,l=ae(new Uint8Array(a)).trim().replace(UB,`
|
|
46
|
+
`).split(`
|
|
47
|
+
`),h=[],u=t?fv(t.baseTime,t.timescale):0;let c="00:00.000",d=0,A=0,f,g=!0;o.oncue=function(m){const p=e[i];let C=e.ccOffset;const E=(d-u)/9e4;if(p!=null&&p.new&&(A!==void 0?C=e.ccOffset=p.start:NB(e,i,E)),E){if(!t){f=new Error("Missing initPTS for VTT MPEGTS");return}C=E-e.presentationOffset}const y=m.endTime-m.startTime,v=Ae((m.startTime+C-A)*9e4,s*9e4)/9e4;m.startTime=Math.max(v,0),m.endTime=Math.max(v+y,0);const T=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(T)),m.id||(m.id=so(m.startTime,m.endTime,T)),m.endTime>0&&h.push(m)},o.onparsingerror=function(m){f=m},o.onflush=function(){if(f){r(f);return}n(h)},l.forEach(m=>{if(g)if(Mr(m,"X-TIMESTAMP-MAP=")){g=!1,m.slice(16).split(",").forEach(p=>{Mr(p,"LOCAL:")?c=p.slice(6):Mr(p,"MPEGTS:")&&(d=parseInt(p.slice(7)))});try{A=GB(c)/1e3}catch(p){f=p}return}else m===""&&(g=!1);o.parse(m+`
|
|
48
|
+
`)}),o.flush()}const Fr="stpp.ttml.im1t",md=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,pd=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,KB={left:"start",center:"center",right:"end",start:"start",end:"end"};function Sh(a,t,e,i){const s=ct(new Uint8Array(a),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>ae(o)),r=Av(t.baseTime,1,t.timescale);try{n.forEach(o=>e($B(o,r)))}catch(o){i(o)}}function $B(a,t){const s=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(n).reduce((c,d)=>(c[d]=s.getAttribute(`ttp:${d}`)||n[d],c),{}),o=s.getAttribute("xml:space")!=="preserve",l=Th(kr(s,"styling","style")),h=Th(kr(s,"layout","region")),u=kr(s,"body","[begin]");return[].map.call(u,c=>{const d=Ed(c,o);if(!d||!c.hasAttribute("begin"))return null;const A=Qr(c.getAttribute("begin"),r),f=Qr(c.getAttribute("dur"),r);let g=Qr(c.getAttribute("end"),r);if(A===null)throw _h(c);if(g===null){if(f===null)throw _h(c);g=A+f}const m=new io(A-t,g-t,d);m.id=so(m.startTime,m.endTime,m.text);const p=h[c.getAttribute("region")],C=l[c.getAttribute("style")],E=YB(p,C,l),{textAlign:y}=E;if(y){const v=KB[y];v&&(m.lineAlign=v),m.align=y}return xt(m,E),m}).filter(c=>c!==null)}function kr(a,t,e){const i=a.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function Th(a){return a.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Ed(a,t){return[].slice.call(a.childNodes).reduce((e,i,s)=>{var n;return i.nodeName==="br"&&s?e+`
|
|
49
|
+
`:(n=i.childNodes)!=null&&n.length?Ed(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function YB(a,t,e){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],r=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return r&&e.hasOwnProperty(r)&&(s=e[r]),n.reduce((o,l)=>{const h=Or(t,i,l)||Or(a,i,l)||Or(s,i,l);return h&&(o[l]=h),o},{})}function Or(a,t,e){return a&&a.hasAttributeNS(t,e)?a.getAttributeNS(t,e):null}function _h(a){return new Error(`Could not parse ttml timestamp ${a}`)}function Qr(a,t){if(!a)return null;let e=Ad(a);return e===null&&(md.test(a)?e=VB(a,t):pd.test(a)&&(e=JB(a,t))),e}function VB(a,t){const e=md.exec(a),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 JB(a,t){const e=pd.exec(a),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 rn{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}}class Id{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=Dh(),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=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new rn(this,"textTrack1"),e=new rn(this,"textTrack2"),i=new rn(this,"textTrack3"),s=new rn(this,"textTrack4");this.cea608Parser1=new Bh(1,t,e),this.cea608Parser2=new Bh(3,i,s)}addCues(t,e,i,s,n){let r=!1;for(let o=n.length;o--;){const l=n[o],h=zB(l[0],l[1],e,i);if(h>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],i),r=!0,h/(i-e)>.5))return}if(r||n.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:n}){const{unparsedVttFrags:r}=this;i===Z.MAIN&&(this.initPTS[e.cc]={baseTime:s,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.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 n=i.textTracks[s];if(xh(n,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}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:n,languageCode:r}=e[t],o=this.getExistingTrack(n,r);if(o)i[t]=o,ki(i[t]),ad(i[t],s);else{const l=this.createTextTrack("captions",n,r);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,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(n=>{ki(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Dh(),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++)ki(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(n=>n.textCodec===Fr);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(zu(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const r=this.media,o=r?gn(r.textTracks):null;if(this.tracks.forEach((l,h)=>{let u;if(o){let c=null;for(let d=0;d<o.length;d++)if(o[d]&&xh(o[d],l)){c=o[d],o[d]=null;break}c&&(u=c)}if(u)ki(u);else{const c=Cd(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(h=>h!==null).map(h=>h.label);l.length&&this.hls.logger.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 r=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:r})}}}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 n=`textTrack${s[1]}`,r=this.captionsProperties[n];r&&(r.label=i.name,i.lang&&(r.languageCode=i.lang),r.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===Z.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:r,lastSn:o}=this,{cc:l,sn:h}=e.frag,u=(i=(s=e.part)==null?void 0:s.index)!=null?i:-1;n&&r&&(h!==o+1||h===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),r.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=u}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===Z.SUBTITLE)if(s.byteLength){const n=i.decryptdata,r="stats"in e;if(n==null||!n.encrypted||r){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===Fr?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;Sh(e,this.initPTS[t.cc],s=>{this._appendCues(s,t.level),i.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{i.logger.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:n,unparsedVttFrags:r}=this,o=n.length-1;if(!n[i.cc]&&o===-1){r.push(t);return}const l=this.hls,h=(e=i.initSegment)!=null&&e.data?fe(i.initSegment.data,new Uint8Array(s)).buffer:s;HB(h,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{const c=u.message==="Missing initPTS for VTT MPEGTS";c?r.push(t):this._fallbackToIMSC1(i,s),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>i.cc)&&l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||Sh(e,this.initPTS[t.cc],()=>{i.textCodec=Fr,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(n=>od(s,n))}else{const s=this.tracks[e];if(!s)return;const n=s.default?"default":"subtitles"+e;i.trigger(I.CUES_PARSED,{type:"subtitles",cues:t,track:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===Z.SUBTITLE&&this.onFragLoaded(I.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(!(i.type===Z.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){const r=s[n].bytes;if(r){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(r);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:r}=this;if(!(!r||r.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>ga(o[l],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>ga(o[l],e,s))}}}extractCea608Data(t){const e=[[],[]],i=t[0]&31;let s=2;for(let n=0;n<i;n++){const r=t[s++],o=127&t[s++],l=127&t[s++];if(o===0&&l===0)continue;if((4&r)!==0){const u=3&r;(u===0||u===1)&&(e[u].push(o),e[u].push(l))}}return e}}function Cd(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function xh(a,t){return!!a&&a.kind===Cd(t)&&da(t,a)}function zB(a,t,e,i){return Math.min(t,i)-Math.max(a,e)}function Dh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const qB=/\s/,yd={newCue(a,t,e,i){const s=[];let n,r,o,l,h;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,h="",!n.isEmpty()){var c;for(let g=0;g<n.chars.length;g++)qB.test(n.chars[g].uchar)&&o?l++:(h+=n.chars[g].uchar,o=!1);n.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const A=gd(h.trim()),f=so(t,e,A);a!=null&&(c=a.cues)!=null&&c.getCueById(f)||(r=new u(t,e,A),r.id=f,r.line=d+1,r.align="left",r.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(r))}return a&&s.length&&(s.sort((d,A)=>d.line==="auto"||A.line==="auto"?0:d.line>8&&A.line>8?A.line-d.line:d.line-A.line),s.forEach(d=>od(a,d))),s}};function vd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const XB=/(\d+)-(\d+)\/(\d+)/;class Ea{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||tS,this.controller=new self.AbortController,this.stats=new Qn}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 n=WB(t,this.controller.signal),r=t.responseType==="arraybuffer",o=r?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=l&&j(l)?l:h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},e.timeout),(xs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var d;this.response=this.loader=c;const A=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},h-(A-s.loading.start)),!c.ok){const{status:g,statusText:m}=c;throw new eS(m||"fetch, bad network response",g,c)}s.loading.first=A,s.total=ZB(c.headers)||s.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&j(e.highWaterMark)?this.loadProgressively(c,s,t,e.highWaterMark,f):r?c.arrayBuffer():t.responseType==="json"?c.json():c.text()}).then(c=>{var d,A;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const g=c[o];g&&(s.loaded=s.total=g);const m={url:f.url,data:c,code:f.status},p=(d=this.callbacks)==null?void 0:d.onProgress;p&&!j(e.highWaterMark)&&p(s,t,c,f),(A=this.callbacks)==null||A.onSuccess(m,s,t,f)}).catch(c=>{var d;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const A=c&&c.code||0,f=c?c.message:null;(d=this.callbacks)==null||d.onError({code:A,text:f},t,c?c.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,n){const r=new _u,o=t.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return r.dataLength&&n(e,i,r.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const u=h.value,c=u.length;return e.loaded+=c,c<s||r.dataLength?(r.push(u),r.dataLength>=s&&n(e,i,r.flush().buffer,t)):n(e,i,u.buffer,t),l()}).catch(()=>Promise.reject());return l()}}function WB(a,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(xt({},a.headers))};return a.rangeEnd&&e.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),e}function jB(a){const t=XB.exec(a);if(t)return parseInt(t[2])-parseInt(t[1])+1}function ZB(a){const t=a.get("Content-Range");if(t){const i=jB(t);if(j(i))return i}const e=a.get("Content-Length");if(e)return parseInt(e)}function tS(a,t){return new self.Request(a.url,t)}class eS extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const iS=/^age:\s*[\d.]+\s*$/im;class no{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 Qn,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 n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,e.url)}).catch(r=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",e.url,!0),n(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(r=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:r.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:n,maxLoadTimeMs:r}=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=n&&j(n)?n:r,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,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const h=e.status,u=e.responseType==="text"?e.responseText:null;if(h>=200&&h<300){const f=u??e.response;if(f!=null){var r,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const g=e.responseType==="arraybuffer"?f.byteLength:f.length;i.loaded=i.total=g,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const m=(r=this.callbacks)==null?void 0:r.onProgress;m&&m(i,t,f,e);const p={url:e.responseURL,data:f,code:h};(o=this.callbacks)==null||o.onSuccess(p,i,t,e);return}}const c=n.loadPolicy.errorRetry,d=i.retry,A={url:t.url,data:void 0,code:h};if(Dn(c,d,!1,A))this.retry(c);else{var l;Et.error(`${h} while loading ${t.url}`),(l=this.callbacks)==null||l.onError({code:h,text:e.statusText},t,e,i)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(Dn(t,e,!0))this.retry(t);else{var i;Et.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=Ha(t,i.retry),i.retry++,Et.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&&iS.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}}const sS={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},nS=St(St({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:no,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:cu,bufferController:Wu,capLevelController:$n,errorController:du,fpsController:rd,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:Ja,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:sS},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},rS()),{},{subtitleStreamController:cd,subtitleTrackController:ld,timelineController:Id,audioStreamController:Ju,audioTrackController:qu,emeController:pi,cmcdController:id,contentSteeringController:sd,interstitialsController:vB});function rS(){return{cueHandler:yd,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 aS(a,t,e){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 i=Ia(a),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,l=t[o]===void 0,h=[];n.forEach(u=>{const c=`${r}Loading${u}`,d=t[c];if(d!==void 0&&l){h.push(c);const A=i[o].default;switch(t[o]={default:A},u){case"TimeOut":A.maxLoadTimeMs=d,A.maxTimeToFirstByteMs=d;break;case"MaxRetry":A.errorRetry.maxNumRetry=d,A.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":A.errorRetry.retryDelayMs=d,A.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":A.errorRetry.maxRetryDelayMs=d,A.timeoutRetry.maxRetryDelayMs=d;break}}}),h.length&&e.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${Mt(t[o])}`)}),St(St({},i),t)}function Ia(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Ia):Object.keys(a).reduce((t,e)=>(t[e]=Ia(a[e]),t),{}):a}function oS(a,t){const e=a.loader;e!==Ea&&e!==no?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):vd()&&(a.loader=Ea,a.progressive=!0,a.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const mn=2,lS=.1,hS=.05,cS=100;class uS extends Au{constructor(t,e){super("gap-controller",t.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(I.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(I.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(cS),this.mediaSource=e.mediaSource;const i=this.media=e.media;Ye(i,"playing",this.onMediaPlaying),Ye(i,"waiting",this.onMediaWaiting),Ye(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(Pe(i,"playing",this.onMediaPlaying),Pe(i,"waiting",this.onMediaWaiting),Pe(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const{media:r,stalled:o}=this;if(!r)return;const{seeking:l}=r,h=this.seeking&&!l,u=!this.seeking&&l,c=r.paused&&!l||r.ended||r.playbackRate===0;if(this.seeking=l,t!==e){e&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&t>e&&this.nudgeOnVideoHole(t,e)),this.waiting===0&&this.stallResolved(t);return}if(u||h){h&&this.stallResolved(t);return}if(c){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&r.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1}));return}if(!ft.getBuffered(r).length){this.nudgeRetry=0;return}const d=ft.bufferInfo(r,t,0),A=d.nextStart||0,f=this.fragmentTracker;if(l&&f&&this.hls){const T=Rh(this.hls.inFlightFragments,t),B=d.len>mn,_=!A||T||A-t>mn&&!f.getPartialFragment(t);if(B||_)return;this.moved=!1}const g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!A)return;const B=Math.max(A,d.start||0)-t,D=!!(g!=null&&g.live)?g.targetduration*2:mn,x=f.getPartialFragment(t);if(B>0&&(B<=D||x)){r.paused||this._trySkipBufferHole(x);return}}const m=n.detectStallWithCurrentTimeMs,p=self.performance.now(),C=this.waiting;if(o===null){C>0&&p-C<m?this.stalled=C:this.stalled=p;return}const E=p-o;if(!l&&(E>=m||C)&&this.hls){var y;if(((y=this.mediaSource)==null?void 0:y.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const v=ft.bufferInfo(r,t,n.maxBufferHole);this._tryFixBufferStall(v,E)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(I.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&t>s.end(0)){const n=ft.bufferedInfo(ft.timeRangesToArray(this.buffered.audio),t,0);if(n.len>1&&e>=n.start){const r=ft.timeRangesToArray(s),o=ft.bufferedInfo(r,e,0).bufferedIndex;if(o>-1&&o<r.length-1){const l=ft.bufferedInfo(r,t,0).bufferedIndex,h=r[o].end,u=r[o+1].start;if((l===-1||l>o)&&u-h<1&&t-h<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${h} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;const d=this.fragmentTracker.getPartialFragment(t)||void 0,A=ft.bufferInfo(this.media,t,0);this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:A.len,bufferInfo:A})}}}}}_tryFixBufferStall(t,e){var i,s;const{fragmentTracker:n,media:r}=this,o=(i=this.hls)==null?void 0:i.config;if(!r||!n||!o)return;const l=r.currentTime,h=(s=this.hls)==null?void 0:s.latestLevelDetails,u=n.getPartialFragment(l);if((u||h!=null&&h.live&&l<h.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const c=t.buffered;(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&t.nextStart-l<o.maxBufferHole)&&(e>o.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&e){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Mt(t)})`);this.warn(r.message),e.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len,bufferInfo:t,stalled:{start:n}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:s}=this,n=(e=this.hls)==null?void 0:e.config;if(!s||!i||!n)return 0;const r=s.currentTime,o=ft.bufferInfo(s,r,0),l=r<o.start?o.start:o.nextStart;if(l&&this.hls){const u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,d=l-r;if(d>0&&(u||c)){if(d>n.maxBufferHole){let f=!1;if(r===0){const g=i.getAppendedFrag(0,Z.MAIN);g&&l<g.end&&(f=!0)}if(!f){const g=t||i.getAppendedFrag(r,Z.MAIN);if(g){var h;if(!((h=this.hls.loadLevelObj)!=null&&h.details)||Rh(this.hls.inFlightFragments,l))return 0;let p=!1,C=g.end;for(;C<l;){const E=i.getPartialFragment(C);if(E)C+=E.duration;else{p=!0;break}}if(p)return 0}}}const A=Math.max(l+hS,r+lS);if(this.warn(`skipping hole, adjusting currentTime from ${r} to ${A}`),this.moved=!0,s.currentTime=A,!(t!=null&&t.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${A}`);this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,frag:t||void 0,buffer:o.len,bufferInfo:o})}return A}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,n=e==null?void 0:e.config;if(!i||!n)return 0;const r=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=r+(s+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${r} to ${o}`);this.warn(l.message),i.currentTime=o,e.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:t.len,bufferInfo:t})}else{const o=new Error(`Playhead still not moving while enough data buffered @${r} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),e.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Rh(a,t){const e=Lh(a.main);if(e&&e.start<=t)return e;const i=Lh(a.audio);return i&&i.start<=t?i:null}function Lh(a){if(!a)return null;switch(a.state){case G.IDLE:case G.STOPPED:case G.ENDED:case G.ERROR:return null}return a.frag}const dS=.25;function Ca(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function bh(a,t,e,i,s){let n=new a(t,e,"");try{n.value=i,s&&(n.type=s)}catch{n=new a(t,e,Mt(s?St({type:s},i):i))}return n}const an=(()=>{const a=Ca();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function AS(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class fS{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(I.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t.on(I.MEDIA_ATTACHING,this.onMediaAttaching,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),t.on(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(I.MEDIA_ATTACHING,this.onMediaAttaching,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),t.off(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,e){var i;this.media=e.media,((i=e.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const t=this.hls.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(t,e){this.media=null,!e.transferMedia&&(this.id3Track&&(this.removeCues&&ki(this.id3Track,this.onEventCueEnter),this.id3Track=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 ad(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:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Ca();if(r)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===se.emsg&&!i||!s)continue;const h=Mu(n[o].data);if(h){const u=n[o].pts;let c=u+n[o].duration;c>an&&(c=an),c-u<=0&&(c=u+dS);for(let A=0;A<h.length;A++){const f=h[A];if(!Fu(f)){this.updateId3CueEnds(u,l);const g=bh(r,u,c,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 n=s.length;n--;){const r=s[n];r.type===e&&r.startTime<t&&r.endTime===an&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=r;if(n&&(o||l)){let h;s==="audio"?h=u=>u.type===se.audioId3&&l:s==="video"?h=u=>u.type===se.emsg&&o:h=u=>u.type===se.audioId3&&l||u.type===se.emsg&&o,ga(n,e,i,h)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:i}=this,{dateRanges:s}=t,n=Object.keys(s);let r=this.dateRangeCuesAppended;if(i&&e){var o;if((o=i.cues)!=null&&o.length){const u=Object.keys(r).filter(c=>!n.includes(c));for(let c=u.length;c--;){const d=u[c],A=r[d].cues;delete r[d],Object.keys(A).forEach(f=>{try{const g=A[f];g.removeEventListener("enter",this.onEventCueEnter),i.removeCue(g)}catch{}})}}else r=this.dateRangeCuesAppended={}}const l=t.fragments[t.fragments.length-1];if(n.length===0||!j(l==null?void 0:l.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=Ca();for(let u=0;u<n.length;u++){const c=n[u],d=s[c],A=d.startTime,f=r[c],g=(f==null?void 0:f.cues)||{};let m=(f==null?void 0:f.durationKnown)||!1,p=an;const{duration:C,endDate:E}=d;if(E&&C!==null)p=A+C,m=!0;else if(d.endOnNext&&!m){const v=n.reduce((T,B)=>{if(B!==d.id){const _=s[B];if(_.class===d.class&&_.startDate>d.startDate&&(!T||d.startDate<T.startDate))return _}return T},null);v&&(p=v.startTime,m=!0)}const y=Object.keys(d.attr);for(let v=0;v<y.length;v++){const T=y[v];if(!sy(T))continue;const B=g[T];if(B)m&&!f.durationKnown?B.endTime=p:Math.abs(B.startTime-A)>.01&&(B.startTime=A,B.endTime=p);else if(h){let _=d.attr[T];ny(T)&&(_=AS(_));const x=bh(h,A,p,{key:T,data:_},se.dateRange);x&&(x.id=c,this.id3Track.addCue(x),g[T]=x,this.hls.config.interstitialsController&&(T==="X-ASSET-LIST"||T==="X-ASSET-URL")&&x.addEventListener("enter",this.onEventCueEnter))}}r[c]={cues:g,dateRange:d,durationKnown:m}}}}class gS{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,i=this.levelDetails;if(!e||!i)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:r}=this.config;if(!n||r===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const l=s-o,h=Math.min(this.maxLatency,o+i.targetduration);if(l<h&&l>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,r)),d=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,A=Math.min(c,Math.max(1,d));this.changeMediaPlaybackRate(e,A)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:n,liveSyncDurationCount:r,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let h=o&&i||e;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||h===0)&&(h=n!==void 0?n:r*s);const u=s;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(t===null||e===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=t-e-this.edgeStalled,r=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(r,n),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;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}=this,e=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(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_UPDATED,this.onLevelUpdated,this),t.on(I.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(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_UPDATED,this.onLevelUpdated,this),t.off(I.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===b.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,s;t.playbackRate!==e&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class mS extends Kn{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=[],n={},r={};let o=!1,l=!1,h=!1;e.levels.forEach(u=>{var c;const d=u.attrs;let{audioCodec:A,videoCodec:f}=u;A&&(u.audioCodec=A=Sn(A,i)||void 0),((c=f)==null?void 0:c.indexOf("avc1"))===0&&(f=u.videoCodec=_C(f));const{width:g,height:m,unknownCodecs:p}=u;let C=p?p.length:0;if(p)for(let M=C;M--;){const k=p[M];this.isAudioSupported(k)?(u.audioCodec=A=A?`${A},${k}`:k,C--,Ni.audio[A.substring(0,4)]=2):this.isVideoSupported(k)&&(u.videoCodec=f=f?`${f},${k}`:k,C--,Ni.video[f.substring(0,4)]=2)}if(o||(o=!!(g&&m)),l||(l=!!f),h||(h=!!A),C||A&&!this.isAudioSupported(A)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":T,RESOLUTION:B,"VIDEO-RANGE":_}=d,x=`${`${T||"."}-`}${u.bitrate}-${B}-${y}-${E}-${_}-${v}`;if(n[x])if(n[x].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const M=r[x]+=1;u.attrs["PATHWAY-ID"]=new Array(M+1).join(".");const k=this.createLevel(u);n[x]=k,s.push(k)}else n[x].addGroupId("audio",d.AUDIO),n[x].addGroupId("text",d.SUBTITLES);else{const M=this.createLevel(u);n[x]=M,r[x]=1,s.push(M)}}),this.filterAndSortMediaOptions(s,e,o,l,h)}createLevel(t){const e=new Hi(t),i=t.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),e.supportedResult=ou(s,[])}return e}isAudioSupported(t){return sa(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return sa(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,n){let r=[],o=[],l=t;if((i||s)&&n&&(l=l.filter(({videoCodec:m,videoRange:p,width:C,height:E})=>(!!m||!!(C&&E))&&bC(p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let m="no level with compatible codecs found in manifest",p=m;e.levels.length&&(p=`one or more CODECS in variant not supported: ${Mt(e.levels.map(E=>E.attrs.CODECS).filter((E,y,v)=>v.indexOf(E)===y))}`,this.warn(p),m+=` (${p})`);const C=new Error(m);this.hls.trigger(I.ERROR,{type:et.MEDIA_ERROR,details:b.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:C,reason:p})}});return}e.audioTracks&&(r=e.audioTracks.filter(m=>!m.audioCodec||this.isAudioSupported(m.audioCodec)),wh(r)),e.subtitles&&(o=e.subtitles,wh(o));const h=l.slice(0);l.sort((m,p)=>{if(m.attrs["HDCP-LEVEL"]!==p.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(p.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==p.height)return m.height-p.height;if(m.frameRate!==p.frameRate)return m.frameRate-p.frameRate;if(m.videoRange!==p.videoRange)return Tn.indexOf(m.videoRange)-Tn.indexOf(p.videoRange);if(m.videoCodec!==p.videoCodec){const C=xl(m.videoCodec),E=xl(p.videoCodec);if(C!==E)return E-C}if(m.uri===p.uri&&m.codecSet!==p.codecSet){const C=Bn(m.codecSet),E=Bn(p.codecSet);if(C!==E)return E-C}return m.averageBitrate!==p.averageBitrate?m.averageBitrate-p.averageBitrate:0});let u=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let m=0;m<h.length;m++)if(h[m].pathwayId===l[0].pathwayId){u=h[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===u){var c;this._firstLevel=m;const p=u.bitrate,C=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${p}`),((c=this.hls.userConfig)==null?void 0:c.abrEwmaDefaultEstimate)===void 0){const E=Math.min(p,this.hls.config.abrEwmaDefaultEstimateMax);E>C&&C===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const d=n&&!s,A=this.hls.config,f=!!(A.audioStreamController&&A.audioTrackController),g={levels:l,audioTracks:r,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:n,video:s,altAudio:f&&!d&&r.some(m=>!!m.url)};this.hls.trigger(I.MANIFEST_PARSED,g)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const u=new Error("invalid level idx"),c=t<0;if(this.hls.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.LEVEL_SWITCH_ERROR,level:t,fatal:c,error:u,reason:u.message}),c)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,r=e[t],o=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=r,i===t&&s&&n===o)return;this.log(`Switching to level ${t} (${r.height?r.height+"p ":""}${r.videoRange?r.videoRange+" ":""}${r.codecSet?r.codecSet+" ":""}@${r.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const l={level:t,attrs:r.attrs,details:r.details,bitrate:r.bitrate,averageBitrate:r.averageBitrate,maxBitrate:r.maxBitrate,realBitrate:r.realBitrate,width:r.width,height:r.height,codecSet:r.codecSet,audioCodec:r.audioCodec,videoCodec:r.videoCodec,audioGroups:r.audioGroups,subtitleGroups:r.subtitleGroups,loaded:r.loaded,loadError:r.loadError,fragmentError:r.fragmentError,name:r.name,id:r.id,uri:r.uri,url:r.url,urlId:0,audioGroupIds:r.audioGroupIds,textGroupIds:r.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,l);const h=r.details;if(!h||h.live){const u=this.switchParams(r.uri,s==null?void 0:s.details,h);this.loadPlaylist(u)}}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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(s=>e.indexOf(s)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);return}this.steering.pathwayPriority=i}}onError(t,e){e.fatal||!e.context||e.context.type===gt.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e!==void 0&&e.type===Z.MAIN){const i=e.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))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:n}=e,r=e.levelInfo;if(!r){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(r===this.currentLevel||e.withoutMultiVariant){r.fragmentError===0&&(r.loadError=0);let l=r.details;l===e.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,e,l)}else(i=e.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],r=t.details,o=r==null?void 0:r.age;this.log(`Loading level index ${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""}${n?" Pathway "+n:""}${o&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${i}`),this.hls.trigger(I.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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;if(this._levels.length===1)return;const i=this._levels.filter((n,r)=>r!==t?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Bu(i),this._levels=i,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),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 wh(a){const t={};a.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function Bd(){return self.SourceBuffer||self.WebKitSourceBuffer}function ro(){if(!Je())return!1;const t=Bd();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Sd(){if(!ro())return!1;const a=Je();return typeof(a==null?void 0:a.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>a.isTypeSupported(Bs(t,"video")))||["mp4a.40.2","fLaC"].some(t=>a.isTypeSupported(Bs(t,"audio"))))}function pS(){var a;const t=Bd();return typeof(t==null||(a=t.prototype)==null?void 0:a.changeType)=="function"}const ES=100;class IS extends Nn{constructor(t,e,i){super(t,e,i,"stream-controller",Z.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,n=s?s.currentTime:null;if(n===null||!j(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const r=this.getFwdBufferInfoAtPos(s,n,Z.MAIN,0);if(r===null||r.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${r?r.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=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.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(){super.unregisterListeners();const{hls:t}=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.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.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(ES),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&t===-1&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=G.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=G.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case G.WAITING_LEVEL:{const{levels:e,level:i}=this,s=e==null?void 0:e[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=G.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=G.IDLE;break}break}case G.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:n}=this,r=s==null?void 0:s[n];this.resetStartWhenNotLoaded(r||null),this.state=G.IDLE}}break}this.state===G.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(e===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(i!=null&&i[n]))return;const r=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(I.BUFFER_EOS,g),this.state=G.ENDED;return}if(!this.buffering)return;t.loadLevel!==n&&t.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const h=r.details;if(!h||this.state===G.WAITING_LEVEL||this.waitForLive(r)){this.level=n,this.state=G.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,c=this.getMaxBufferLength(r.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let A=this.getNextFragment(d,h);if(this.couldBacktrack&&!this.fragPrevious&&A&&zt(A)&&this.fragmentTracker.getState(A)!==$t.OK){var f;const m=((f=this.backtrackFragment)!=null?f:A).sn-h.startSN,p=h.fragments[m-1];p&&A.cc===p.cc&&(A=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(A&&this.isLoopLoading(A,d)){if(!A.gap){const m=this.audioOnly&&!this.altAudio?_t.AUDIO:_t.VIDEO,p=(m===_t.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;p&&this.afterBufferFlushed(p,m,Z.MAIN)}A=this.getNextFragmentLoopLoading(A,h,o,Z.MAIN,c)}A&&(A.initSegment&&!A.initSegment.data&&!this.bitrateTest&&(A=A.initSegment),this.loadFragment(A,r,d))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===$t.NOT_LOADED||s===$t.PARTIAL?zt(t)?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)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Z.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 n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!e.paused&&t){const o=this.hls.nextLoadLevel,l=t[o],h=this.fragLastKbps;h&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*h)+1:i=0}else i=0;const r=this.getBufferedFrag(e.currentTime+i);if(r){const o=this.followingBufferedFrag(r);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,h=o.duration,u=Math.max(r.end,l+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,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 G.KEY_LOADING:case G.FRAG_LOADING:case G.FRAG_LOADING_WAITING_RETRY:case G.PARSING:case G.PARSED:this.state=G.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio===2?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;Ye(i,"playing",this.onMediaPlaying),Ye(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(Pe(i,"playing",this.onMediaPlaying),Pe(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e),!e.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;e.levels.forEach(n=>{const r=n.audioCodec;r&&(i=i||r.indexOf("mp4a.40.2")!==-1,s=s||r.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!pS(),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!==G.IDLE)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=G.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:n}=this,r=e.level,o=e.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const h=e.levelInfo,u=this.fragCurrent;u&&(this.state===G.FRAG_LOADING||this.state===G.FRAG_LOADING_WAITING_RETRY)&&u.level!==e.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(i=h.details)!=null&&i.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(h.details=o,this.levelLastLoaded=h,n||this.setStartPosition(o,c),this.hls.trigger(I.LEVEL_UPDATED,{details:o,level:r}),this.state===G.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=G.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),r=t.fragmentStart,o=t.edge,l=n>=r-e.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){const h=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!l&&i.readyState<4||n<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{levels:r}=this;if(!r){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=r[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const 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 h=o.videoCodec,u=l.PTSKnown||!l.live,c=(e=i.initSegment)==null?void 0:e.data,d=this._getAudioCodec(o),A=this.transmuxer=this.transmuxer||new Vu(this.hls,Z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=f!==-1,m=new Gn(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,g),p=this.initPTS[i.cc];A.push(n,c,d,h,i,s,l.totalduration,u,m,p)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio===2;if(_n(e.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.fragmentTracker.removeAllFragments(),i.once(I.BUFFER_FLUSHED,()=>{var r;(r=this.hls)==null||r.trigger(I.AUDIO_TRACK_SWITCHED,e)}),i.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(I.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=_n(e.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,n,r=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){const h=i[o];h&&(this.videoBuffer=h.buffer)}}else r=!0}r&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,n=i.type===Z.MAIN;if(n){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===G.PARSED&&(this.state=G.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),zt(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const r=this.media;r&&(!this._hasEnoughToStart&&ft.getBuffered(r).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal){this.state=G.ERROR;return}switch(e.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.MAIN,e);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===G.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===gt.LEVEL&&(this.state=G.IDLE);break;case b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){this.state=G.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==_t.AUDIO||!this.altAudio){const i=(e===_t.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,e,Z.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;s&&i&&(i+=s);const n=this.getLevelDetails(),r=ft.getBuffered(t),o=r.length?r.start(0):0,l=o-i,h=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);l>0&&(l<h||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${o}`),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,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;e.fragmentError=0,this.state=G.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=n.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(I.FRAG_LOADED,i),n.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const i=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:l,part:h,level:u}=o,{video:c,text:d,id3:A,initSegment:f}=n,{details:g}=u,m=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=G.PARSING,f){if(f!=null&&f.tracks){const E=l.initSegment||l;this._bufferInitSegment(u,f.tracks,E,r),s.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:f.tracks})}const p=f.initPTS,C=f.timescale;j(p)&&(this.initPTS[l.cc]={baseTime:p,timescale:C},s.trigger(I.INIT_PTS_FOUND,{frag:l,id:i,initPTS:p,timescale:C}))}if(c&&g){m&&c.type==="audiovideo"&&this.logMuxedErr(l);const p=g.fragments[l.sn-1-g.startSN],C=l.sn===g.startSN,E=!p||l.cc>p.cc;if(n.independent!==!1){const{startPTS:y,endPTS:v,startDTS:T,endDTS:B}=c;if(h)h.elementaryStreams[c.type]={startPTS:y,endPTS:v,startDTS:T,endDTS:B};else if(c.firstKeyFrame&&c.independent&&r.id===1&&!E&&(this.couldBacktrack=!0),c.dropped&&c.independent){const _=this.getMainFwdBufferInfo(),D=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,x=c.firstKeyFramePTS?c.firstKeyFramePTS:y;if(!C&&D<x-this.config.maxBufferHole&&!E){this.backtrack(l);return}else E&&(l.gap=!0);l.setElementaryStreamInfo(c.type,l.start,v,l.start,B,!0)}else C&&y-(g.appliedTimelineOffset||0)>mn&&(l.gap=!0);l.setElementaryStreamInfo(c.type,y,v,T,B),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,h,r,C||E)}else if(C||E)l.gap=!0;else{this.backtrack(l);return}}if(m){const{startPTS:p,endPTS:C,startDTS:E,endDTS:y}=m;h&&(h.elementaryStreams[_t.AUDIO]={startPTS:p,endPTS:C,startDTS:E,endDTS:y}),l.setElementaryStreamInfo(_t.AUDIO,p,C,E,y),this.bufferFragmentData(m,l,h,r)}if(g&&A!=null&&(e=A.samples)!=null&&e.length){const p={id:i,frag:l,details:g,samples:A.samples};s.trigger(I.FRAG_PARSING_METADATA,p)}if(g&&d){const p={id:i,frag:l,details:g,samples:d.samples};s.trigger(I.FRAG_PARSING_USERDATA,p)}}logMuxedErr(t){this.warn(`${zt(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==G.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:n,video:r,audiovideo:o}=e;if(n){let h=un(n.codec,t.audioCodec);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),t.audioCodec&&t.audioCodec!==h&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${h}"`),n.levelCodec=h,n.id=Z.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${h||""}/${t.audioCodec||""}/${n.codec}]`),delete e.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=Z.MAIN;const h=r.codec;if((h==null?void 0:h.length)===4)switch(h){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${h}]${r.codec!==h?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete e.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(I.BUFFER_CODECS,e),!this.hls)return;l.forEach(h=>{const c=e[h].initSegment;c!=null&&c.byteLength&&this.hls.trigger(I.BUFFER_APPENDING,{type:h,data:c,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,Z.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,i=t==null?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}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=G.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(ft.isBuffered(t,i)?e=this.getAppendedFrag(i):ft.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const s=this.fragPlaying,n=e.level;(!s||e.sn!==s.sn||s.level!==n)&&(this.fragPlaying=e,this.hls.trigger(I.FRAG_CHANGED,{frag:e}),(!s||s.level!==n)&&this.hls.trigger(I.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return j(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(j(e)){const i=this.getLevelDetails(),s=this.currentFrag||(i?Ei(null,i.fragments,e):null);if(s){const n=s.programDateTime;if(n!==null){const r=n+(e-s.start)*1e3;return new Date(r)}}}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 CS{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=b.KEY_LOAD_ERROR,i,s,n){return new Ge({type:et.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:i,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=t;for(let n=0;n<e.length;n++){const r=e[n];if(s<=r.cc&&(i==="initSegment"||r.sn==="initSegment"||i<r.sn)){this.emeController.selectKeySystemFormat(r).then(o=>{r.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 n=t.decryptdata;if(!n){const h=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,b.KEY_LOAD_ERROR,h))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));let o=this.keyUriToKeyInfo[r];if((i=o)!=null&&i.decryptdata.key)return n.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(h=>(n.key=h.keyInfo.decryptdata.key,{frag:t,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[r]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.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(n=>(t.mediaKeySessionContext=n,i))).catch(n=>{throw t.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=i.loader,n=new s(i);return e.keyLoader=t.loader=n,t.keyLoadPromise=new Promise((r,o)=>{const l={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=i.keyLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(d,A,f,g)=>{const{frag:m,keyInfo:p,url:C}=f;if(!m.decryptdata||p!==this.keyUriToKeyInfo[C])return o(this.createKeyLoadError(m,b.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));p.decryptdata.key=m.decryptdata.key=new Uint8Array(d.data),m.keyLoader=null,p.loader=null,r({frag:m,keyInfo:p})},onError:(d,A,f,g)=>{this.resetLoader(A),o(this.createKeyLoadError(e,b.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,St({url:l.url,data:void 0},d)))},onTimeout:(d,A,f)=>{this.resetLoader(A),o(this.createKeyLoadError(e,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,A,f)=>{this.resetLoader(A),o(this.createKeyLoadError(e,b.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};n.load(l,u,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}function Ph(a){const{type:t}=a;switch(t){case gt.AUDIO_TRACK:return Z.AUDIO;case gt.SUBTITLE_TRACK:return Z.SUBTITLE;default:return Z.MAIN}}function Ur(a,t){let e=a.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class yS{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,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),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,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),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,n=i||s,r=new n(e);return this.loaders[t.type]=r,r}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:gt.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:n,url:r,deliveryDirectives:o,levelInfo:l}=e;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:gt.LEVEL,url:r,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:gt.AUDIO_TRACK,url:n,deliveryDirectives:r,levelOrTrack:o})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:gt.SUBTITLE_TRACK,url:n,deliveryDirectives:r,levelOrTrack:o})}onLevelsUpdated(t,e){const i=this.loaders[gt.LEVEL];if(i){const s=i.context;s&&!e.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[gt.LEVEL])}}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const h=this.hls.logger,u=s.context;if(u&&u.levelOrTrack===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){u.url===t.url?h.log(`[playlist-loader]: ignore ${t.url} ongoing request`):h.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}h.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let n;if(t.type===gt.MANIFEST?n=i.manifestLoadPolicy.default:n=xt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),j((e=t.deliveryDirectives)==null?void 0:e.part)){let h;if(t.type===gt.LEVEL&&t.level!==null?h=this.hls.levels[t.level].details:t.type===gt.AUDIO_TRACK&&t.id!==null?h=this.hls.audioTracks[t.id].details:t.type===gt.SUBTITLE_TRACK&&t.id!==null&&(h=this.hls.subtitleTracks[t.id].details),h){const u=h.partTarget,c=h.targetduration;if(u&&c){const d=Math.max(u*3,c*.8)*1e3;n=xt({},n,{maxTimeToFirstByteMs:Math.min(d,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,n.maxTimeToFirstByteMs)})}}}const r=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:r.maxNumRetry||0,retryDelay:r.retryDelayMs||0,maxRetryDelay:r.maxRetryDelayMs||0},l={onSuccess:(h,u,c,d)=>{const A=this.getInternalLoader(c);this.resetInternalLoader(c.type);const f=h.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(h,c,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),Be.isMediaPlaylist(f)||c.type!==gt.MANIFEST?this.handleTrackOrLevelPlaylist(h,u,c,d||null,A):this.handleMasterPlaylist(h,u,c,d)},onError:(h,u,c,d)=>{this.handleNetworkError(u,c,!1,h,d)},onTimeout:(h,u,c)=>{this.handleNetworkError(u,c,!0,void 0,h)}};s.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const n=this.hls,r=t.data,o=Ur(t,i),l=Be.parseMasterPlaylist(r,o);if(l.playlistParsingError){this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}const{contentSteering:h,levels:u,sessionData:c,sessionKeys:d,startTimeOffset:A,variableList:f}=l;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Be.parseMasterPlaylistMedia(r,o,l);g.length&&!g.some(E=>!E.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.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 Pt({}),bitrate:0,url:""})),n.trigger(I.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:m,captions:p,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:c,sessionKeys:d,startTimeOffset:A,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,s,n){const r=this.hls,{id:o,level:l,type:h}=i,u=Ur(t,i),c=j(l)?l:j(o)?o:0,d=Ph(i),A=Be.parseLevelPlaylist(t.data,u,c,d,0,this.variableList);if(h===gt.MANIFEST){const f={attrs:new Pt({}),bitrate:0,details:A,name:"",url:u};A.requestScheduled=e.loading.start+Cu(A,0),r.trigger(I.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=A,this.handlePlaylistLoaded(A,t,e,i,s,n)}handleManifestParsingError(t,e,i,s,n){this.hls.trigger(I.ERROR,{type:et.NETWORK_ERROR,details:b.MANIFEST_PARSING_ERROR,fatal:e.type===gt.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:n})}handleNetworkError(t,e,i=!1,s,n){let r=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===gt.LEVEL?r+=`: ${t.level} id: ${t.id}`:(t.type===gt.AUDIO_TRACK||t.type===gt.SUBTITLE_TRACK)&&(r+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let l=b.UNKNOWN,h=!1;const u=this.getInternalLoader(t);switch(t.type){case gt.MANIFEST:l=i?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,h=!0;break;case gt.LEVEL:l=i?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,h=!1;break;case gt.AUDIO_TRACK:l=i?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case gt.SUBTITLE_TRACK:l=i?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.SUBTITLE_LOAD_ERROR,h=!1;break}u&&this.resetInternalLoader(t.type);const c={type:et.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:u,context:t,error:o,networkDetails:e,stats:n};if(s){const d=(e==null?void 0:e.url)||t.url;c.response=St({url:d,data:void 0},s)}this.hls.trigger(I.ERROR,c)}handlePlaylistLoaded(t,e,i,s,n,r){const o=this.hls,{type:l,level:h,id:u,groupId:c,deliveryDirectives:d}=s,A=Ur(e,s),f=Ph(s),g=typeof s.level=="number"&&f===Z.MAIN?h:void 0;if(!t.fragments.length){const p=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(I.ERROR,{type:et.NETWORK_ERROR,details:b.LEVEL_EMPTY_ERROR,fatal:!1,url:A,error:p,reason:p.message,response:e,context:s,level:g,parent:f,networkDetails:n,stats:i});return}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(m),!o.config.ignorePlaylistParsingErrors){o.trigger(I.ERROR,{type:et.NETWORK_ERROR,details:b.LEVEL_PARSING_ERROR,fatal:!1,url:A,error:m,reason:m.message,response:e,context:s,level:g,parent:f,networkDetails:n,stats:i});return}t.playlistParsingError=null}switch(t.live&&r&&(r.getCacheAge&&(t.ageHeader=r.getCacheAge()||0),(!r.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case gt.MANIFEST:case gt.LEVEL:o.trigger(I.LEVEL_LOADED,{details:t,levelInfo:s.levelOrTrack||o.levels[0],level:g||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:d,withoutMultiVariant:l===gt.MANIFEST});break;case gt.AUDIO_TRACK:o.trigger(I.AUDIO_TRACK_LOADED,{details:t,track:s.levelOrTrack,id:u||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case gt.SUBTITLE_TRACK:o.trigger(I.SUBTITLE_TRACK_LOADED,{details:t,track:s.levelOrTrack,id:u||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:d});break}}}class Ke{static get version(){return Ts}static isMSESupported(){return ro()}static isSupported(){return Sd()}static getMediaSource(){return Je()}static get Events(){return I}static get MetadataSchema(){return se}static get ErrorTypes(){return et}static get ErrorDetails(){return b}static get DefaultConfig(){return Ke.defaultConfig?Ke.defaultConfig:nS}static set DefaultConfig(t){Ke.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new za,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=iC(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=aS(Ke.DefaultConfig,t,e);this.userConfig=t,i.progressive&&oS(i,e);const{abrController:s,bufferController:n,capLevelController:r,errorController:o,fpsController:l}=i,h=new o(this),u=this.abrController=new s(this),c=new YC(this),d=i.interstitialsController,A=d?this.interstitialsController=new d(this,Ke):null,f=this.bufferController=new n(this,c),g=this.capLevelController=new r(this),m=new l(this),p=new yS(this),C=i.contentSteeringController,E=C?new C(this):null,y=this.levelController=new mS(this,E),v=new fS(this),T=new CS(this.config),B=this.streamController=new IS(this,c,T),_=this.gapController=new uS(this,c);g.setStreamController(B),m.setStreamController(B);const D=[p,y,B];A&&D.splice(1,0,A),E&&D.splice(1,0,E),this.networkControllers=D;const x=[u,f,_,g,m,v,c];this.audioTrackController=this.createController(i.audioTrackController,D);const M=i.audioStreamController;M&&D.push(this.audioStreamController=new M(this,c,T)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const k=i.subtitleStreamController;k&&D.push(this.subtititleStreamController=new k(this,c,T)),this.createController(i.timelineController,x),T.emeController=this.emeController=this.createController(i.emeController,x),this.cmcdController=this.createController(i.cmcdController,x),this.latencyController=this.createController(gS,x),this.coreComponents=x,D.push(h);const X=h.onErrorOut;typeof X=="function"&&this.on(I.ERROR,X,h),this.on(I.MANIFEST_LOADED,p.onManifestLoaded,p)}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(this.logger.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:et.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:s,event:t,error:i}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.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){if(!t||"media"in t&&!t.media){const n=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(I.ERROR,{type:et.OTHER_ERROR,details:b.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(I.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(I.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=Qa.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(I.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[Z.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Z.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Z.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=Hy()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){LC(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 n=s;n--;){const r=t[n].attrs["HDCP-LEVEL"];if(r&&r<=i)return n}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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return((e=this.audioTrackController)==null?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return((e=this.subtitleTrackController)==null?void 0: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}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){const i=hu(e);return lu(t,i,navigator.mediaCapabilities)}}Ke.defaultConfig=void 0;const vS=Object.freeze(Object.defineProperty({__proto__:null,AbrController:cu,AttrList:Pt,AudioStreamController:Ju,AudioTrackController:qu,BasePlaylistController:Kn,BaseSegment:Ua,BaseStreamController:Nn,BufferController:Wu,CMCDController:id,CapLevelController:$n,ChunkMetadata:Gn,ContentSteeringController:sd,Cues:yd,DateRange:$a,EMEController:pi,ErrorActionFlags:de,ErrorController:du,ErrorDetails:b,ErrorTypes:et,Events:I,FPSController:rd,FetchLoader:Ea,Fragment:cn,Hls:Ke,HlsSkip:Is,HlsUrlParameters:ra,KeySystemFormats:jt,KeySystems:vt,Level:Hi,LevelDetails:gu,LevelKey:Ki,LoadStats:Qn,M3U8Parser:Be,MetadataSchema:se,NetworkErrorAction:Jt,Part:zc,PlaylistLevelType:Z,SubtitleStreamController:cd,SubtitleTrackController:ld,TimelineController:Id,XhrLoader:no,default:Ke,fetchSupported:vd,getMediaSource:Je,isMSESupported:ro,isSupported:Sd,requestMediaKeySystemAccess:Ja},Symbol.toStringTag,{value:"Module"})),BS=((a,t)=>typeof window<"u"&&typeof((a=window.document)==null?void 0:a.createElement)=="function"&&typeof((t=window.navigator)==null?void 0:t.userAgent)=="string")();let Gr=null;async function SS(...a){var t;(t=Gr)!==null&&t!==void 0||(Gr=await t0(()=>Promise.resolve().then(()=>vS),void 0));const e=Gr.default;return e.isSupported()?new e(...a):null}function Td(a,{unsuspend:t="loadedmetadata",start:e=!0,hls:i={},crossOrigin:s="anonymous",muted:n=!0,loop:r=!0,playsInline:o=!0,onVideoFrame:l,...h}={}){const u=q(f=>f.gl),c=S.useRef(null),d=Ji(()=>new Promise(async f=>{let g,m;typeof a=="string"?g=a:m=a;const p=Object.assign(document.createElement("video"),{src:g,srcObject:m,crossOrigin:s,loop:r,muted:n,playsInline:o,...h});if(g&&BS&&g.endsWith(".m3u8")){const E=c.current=await SS(i);E&&(E.on(I.MEDIA_ATTACHED,()=>void E.loadSource(g)),E.attachMedia(p))}const C=new yA(p);C.colorSpace=u.outputColorSpace,p.addEventListener(t,()=>f(C))}),[a]),A=d.source.data;return TS(A,l),S.useEffect(()=>(e&&d.image.play(),()=>{c.current&&(c.current.destroy(),c.current=null)}),[d,e]),d}const Yn=S.forwardRef(({children:a,src:t,...e},i)=>{const s=Td(t,e);return S.useEffect(()=>()=>void s.dispose(),[s]),S.useImperativeHandle(i,()=>s,[s]),S.createElement(S.Fragment,null,a==null?void 0:a(s))}),TS=(a,t)=>{S.useEffect(()=>{if(!t||!a.requestVideoFrameCallback)return;let e;const i=(...s)=>{t(...s),e=a.requestVideoFrameCallback(i)};return a.requestVideoFrameCallback(i),()=>a.cancelVideoFrameCallback(e)},[a,t])};var _d={exports:{}};(function(a,t){(function(e,i){a.exports=i()})(Zp,function(){var e=function(){function i(A){return r.appendChild(A.dom),A}function s(A){for(var f=0;f<r.children.length;f++)r.children[f].style.display=f===A?"block":"none";n=A}var n=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",function(A){A.preventDefault(),s(++n%r.children.length)},!1);var o=(performance||Date).now(),l=o,h=0,u=i(new e.Panel("FPS","#0ff","#002")),c=i(new e.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=i(new e.Panel("MB","#f08","#201"));return s(0),{REVISION:16,dom:r,addPanel:i,showPanel:s,begin:function(){o=(performance||Date).now()},end:function(){h++;var A=(performance||Date).now();if(c.update(A-o,200),A>l+1e3&&(u.update(1e3*h/(A-l),100),l=A,h=0,d)){var f=performance.memory;d.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return A},update:function(){o=this.end()},domElement:r,setMode:s}};return e.Panel=function(i,s,n){var r=1/0,o=0,l=Math.round,h=l(window.devicePixelRatio||1),u=80*h,c=48*h,d=3*h,A=2*h,f=3*h,g=15*h,m=74*h,p=30*h,C=document.createElement("canvas");C.width=u,C.height=c,C.style.cssText="width:80px;height:48px";var E=C.getContext("2d");return E.font="bold "+9*h+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=n,E.fillRect(0,0,u,c),E.fillStyle=s,E.fillText(i,d,A),E.fillRect(f,g,m,p),E.fillStyle=n,E.globalAlpha=.9,E.fillRect(f,g,m,p),{dom:C,update:function(y,v){r=Math.min(r,y),o=Math.max(o,y),E.fillStyle=n,E.globalAlpha=1,E.fillRect(0,0,u,g),E.fillStyle=s,E.fillText(l(y)+" "+i+" ("+l(r)+"-"+l(o)+")",d,A),E.drawImage(C,f+h,g,m-h,p,f,g,m-h,p),E.fillRect(f+m-h,g,h,p),E.fillStyle=n,E.globalAlpha=.9,E.fillRect(f+m-h,g,h,l((1-y/v)*p))}}},e})})(_d);var _S=_d.exports;const xS=jp(_S);function DS(a,t=[],e){const[i,s]=S.useState();return S.useLayoutEffect(()=>{const n=a();return s(n),()=>void 0},t),i}function RS({showPanel:a=0,className:t,parent:e}){const i=DS(()=>new xS,[]);return S.useEffect(()=>{if(i){const s=e&&e.current||document.body;i.showPanel(a),s==null||s.appendChild(i.dom);const n=(t??"").split(" ").filter(l=>l);n.length&&i.dom.classList.add(...n);const r=Xh(()=>i.begin()),o=Wh(()=>i.end());return()=>{n.length&&i.dom.classList.remove(...n),s==null||s.removeChild(i.dom),r(),o()}}},[e,i,t,a]),null}class LS{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,n=0){if(!this.context||!this.gradient)return;const r=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(n)} ${this.name} (${r.toFixed(n)}-${parseFloat(o.toFixed(n))})`,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 xd=class Mi{constructor({trackGPU:t=!1,logsPerSecond:e=30,samplesLog:i=60,samplesGraph:s=10,precision:n=2,minimal:r=!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=h=>{h.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=r,this.trackGPU=t,this.samplesLog=i,this.samplesGraph=s,this.precision=n,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 Mi.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new Mi.Panel("CPU","#0f0","#020"),1),this.setupEventListeners()}initializeDOM(){this.dom.style.cssText=`
|
|
50
|
+
position: fixed;
|
|
51
|
+
top: 0;
|
|
52
|
+
left: 0;
|
|
53
|
+
opacity: 0.9;
|
|
54
|
+
z-index: 10000;
|
|
55
|
+
${this.minimal?"cursor: pointer;":""}
|
|
56
|
+
`}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 Mi.Panel("GPU","#ff0","#220"),2),this.gpuPanelCompute=this.addPanel(new Mi.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 Mi.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 r=this.gl.getQueryParameter(t.query,this.gl.QUERY_RESULT)*1e-6;this.totalGpuDuration+=r,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,n=.01;for(let l=0;l<e.logs.length;l++)s+=e.logs[l],e.logs[l]>n&&(n=e.logs[l]);let r=0,o=.01;for(let l=0;l<e.graph.length;l++)r+=e.graph[l],e.graph[l]>o&&(o=e.graph[l]);t&&t.update(s/Math.min(e.logs.length,this.samplesLog),r/Math.min(e.graph.length,this.samplesGraph),n,o,i)}}get domElement(){return this.dom}patchThreeRenderer(t){const e=t.render,i=this;t.render=function(s,n){i.begin(),e.call(this,s,n),i.end()},this.threeRendererPatched=!0}};xd.Panel=LS;let bS=xd;const wS=S.forwardRef(function({className:t,parent:e,id:i,clearStatsGlStyle:s,...n},r){const o=q(h=>h.gl),l=S.useMemo(()=>{const h=new bS({...n});return h.init(o),h},[o]);return S.useImperativeHandle(r,()=>l.domElement,[l]),S.useEffect(()=>{if(l){const h=e&&e.current||document.body;h==null||h.appendChild(l.domElement),l.domElement.querySelectorAll("canvas").forEach(d=>{d.style.removeProperty("position")}),i&&(l.domElement.id=i),s&&l.domElement.removeAttribute("style"),l.domElement.removeAttribute("style");const u=(t??"").split(" ").filter(d=>d);u.length&&l.domElement.classList.add(...u);const c=Wh(()=>l.update());return()=>{u.length&&l.domElement.classList.remove(...u),h==null||h.removeChild(l.domElement),c()}}},[e,l,t,i,s]),null});function PS({size:a=256,frames:t=1/0}={}){const e=q(u=>u.viewport.dpr),{width:i,height:s}=q(u=>u.size),n=a||i*e,r=a||s*e,o=S.useMemo(()=>{const u=new vA(n,r);return u.format=BA,u.type=SA,{depthTexture:u}},[n,r]);let l=0;const h=jh(n,r,o);return Qt(u=>{(t===1/0||l<t)&&(u.gl.setRenderTarget(h),u.gl.render(u.scene,u.camera),u.gl.setRenderTarget(null),l++)}),h.depthTexture}function MS(a,t,e=1){const i=q(r=>r.viewport),s=t*(i.aspect>a/t?i.width/a:i.height/t);return[a*(i.aspect>a/t?i.width/a:i.height/t)*e,s*e,1]}function FS(a,t){const e=q(s=>s.pointer),[i]=S.useState(()=>{const s=new Pn;return t&&Zh(s,t),function(n,r){s.setFromCamera(e,a instanceof TA?a:a.current);const o=this.constructor.prototype.raycast.bind(this);o&&o(s,r)}});return i}function Nr(a,t,e,i){return new(e||(e=Promise))(function(s,n){function r(h){try{l(i.next(h))}catch(u){n(u)}}function o(h){try{l(i.throw(h))}catch(u){n(u)}}function l(h){var u;h.done?s(h.value):(u=h.value,u instanceof e?u:new e(function(c){c(u)})).then(r,o)}l((i=i.apply(a,[])).next())})}const kS=["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 Mh(a){return a=a.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 Dd=typeof window>"u",Re=(()=>{if(Dd)return;const{userAgent:a,platform:t,maxTouchPoints:e}=window.navigator,i=/(iphone|ipod|ipad)/i.test(a),s=t==="iPad"||t==="MacIntel"&&e>0&&!window.MSStream;return{isIpad:s,isMobile:/android/i.test(a)||i||s,isSafari12:/Version\/12.+Safari/.test(a),isFirefox:/Firefox/.test(a)}})();function OS(a,t,e){if(!e)return[t];const i=function(h){const u=`
|
|
57
|
+
precision highp float;
|
|
58
|
+
attribute vec3 aPosition;
|
|
59
|
+
varying float vvv;
|
|
60
|
+
void main() {
|
|
61
|
+
vvv = 0.31622776601683794;
|
|
62
|
+
gl_Position = vec4(aPosition, 1.0);
|
|
63
|
+
}
|
|
64
|
+
`,c=`
|
|
65
|
+
precision highp float;
|
|
66
|
+
varying float vvv;
|
|
67
|
+
void main() {
|
|
68
|
+
vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv;
|
|
69
|
+
enc = fract(enc);
|
|
70
|
+
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
|
|
71
|
+
gl_FragColor = enc;
|
|
72
|
+
}
|
|
73
|
+
`,d=h.createShader(35633),A=h.createShader(35632),f=h.createProgram();if(!(A&&d&&f))return;h.shaderSource(d,u),h.shaderSource(A,c),h.compileShader(d),h.compileShader(A),h.attachShader(f,d),h.attachShader(f,A),h.linkProgram(f),h.detachShader(f,d),h.detachShader(f,A),h.deleteShader(d),h.deleteShader(A),h.useProgram(f);const g=h.createBuffer();h.bindBuffer(34962,g),h.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const m=h.getAttribLocation(f,"aPosition");h.vertexAttribPointer(m,3,5126,!1,0,0),h.enableVertexAttribArray(m),h.clearColor(1,1,1,1),h.clear(16384),h.viewport(0,0,1,1),h.drawArrays(4,0,3);const p=new Uint8Array(4);return h.readPixels(0,0,1,1,6408,5121,p),h.deleteProgram(f),h.deleteBuffer(g),p.join("")}(a),s="801621810",n="8016218135",r="80162181161",o=Re!=null&&Re.isIpad?[["a7",r,12],["a8",n,15],["a8x",n,15],["a9",n,15],["a9x",n,15],["a10",n,15],["a10x",n,15],["a12",s,15],["a12x",s,15],["a12z",s,15],["a14",s,15],["a15",s,15],["m1",s,15],["m2",s,15]]:[["a7",r,12],["a8",n,12],["a9",n,15],["a10",n,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(([,,h])=>h>=14):(l=o.filter(([,h])=>h===i),l.length||(l=o)),l.map(([h])=>`apple ${h} gpu`)}class Fh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}const Hr=[],kh=[];function QS(a,t){if(a===t)return 0;const e=a;a.length>t.length&&(a=t,t=e);let i=a.length,s=t.length;for(;i>0&&a.charCodeAt(~-i)===t.charCodeAt(~-s);)i--,s--;let n,r=0;for(;r<i&&a.charCodeAt(r)===t.charCodeAt(r);)r++;if(i-=r,s-=r,i===0)return s;let o,l,h=0,u=0,c=0;for(;u<i;)kh[u]=a.charCodeAt(r+u),Hr[u]=++u;for(;c<s;)for(n=t.charCodeAt(r+c),o=c++,h=c,u=0;u<i;u++)l=n===kh[u]?o:o+1,o=Hr[u],h=Hr[u]=o>h?l>h?h+1:l:l>o?o+1:l;return h}function US(a){return a!=null}const GS=({mobileTiers:a=[0,15,30,60],desktopTiers:t=[0,15,30,60],override:e={},glContext:i,failIfMajorPerformanceCaveat:s=!1,benchmarksURL:n="https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks"}={})=>Nr(void 0,void 0,void 0,function*(){const r={};if(Dd)return{tier:0,type:"SSR"};const{isIpad:o=!!(Re!=null&&Re.isIpad),isMobile:l=!!(Re!=null&&Re.isMobile),screenSize:h=window.screen,loadBenchmarks:u=v=>Nr(void 0,void 0,void 0,function*(){const T=yield fetch(`${n}/${v}`).then(B=>B.json());if(parseInt(T.shift().split(".")[0],10)<4)throw new Fh("Detect GPU benchmark data is out of date. Please update to version 4x");return T})}=e;let{renderer:c}=e;const d=(v,T,B,_,D)=>({device:D,fps:_,gpu:B,isMobile:l,tier:v,type:T});let A,f="";if(c)c=Mh(c),A=[c];else{const v=i||function(B,_=!1){const D={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:_,powerPreference:"high-performance",stencil:!1};B&&delete D.powerPreference;const x=window.document.createElement("canvas"),M=x.getContext("webgl",D)||x.getContext("experimental-webgl",D);return M??void 0}(Re==null?void 0:Re.isSafari12,s);if(!v)return d(0,"WEBGL_UNSUPPORTED");const T=Re!=null&&Re.isFirefox?null:v.getExtension("WEBGL_debug_renderer_info");if(c=T?v.getParameter(T.UNMASKED_RENDERER_WEBGL):v.getParameter(v.RENDERER),!c)return d(1,"FALLBACK");f=c,c=Mh(c),A=function(B,_,D){return _==="apple gpu"?OS(B,_,D):[_]}(v,c,l)}const g=(yield Promise.all(A.map(function(v){var T;return Nr(this,void 0,void 0,function*(){const B=($=>{const R=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const tt of R)if($.includes(tt))return tt})(v);if(!B)return;const _=`${l?"m":"d"}-${B}${o?"-ipad":""}.json`,D=r[_]=(T=r[_])!==null&&T!==void 0?T:u(_);let x;try{x=yield D}catch($){if($ instanceof Fh)throw $;return}const M=function($){var R;const tt=($=$.replace(/\([^)]+\)/,"")).match(/\d+/)||$.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(R=tt==null?void 0:tt.join("").replace(/\W|amd/g,""))!==null&&R!==void 0?R:""}(v);let k=x.filter(([,$])=>$===M);k.length||(k=x.filter(([$])=>$.includes(v)));const X=k.length;if(X===0)return;const W=v.split(/[.,()\[\]/\s]/g).sort().filter(($,R,tt)=>R===0||$!==tt[R-1]).join(" ");let H,[Y,,,,z]=X>1?k.map($=>[$,QS(W,$[2])]).sort(([,$],[,R])=>$-R)[0][0]:k[0],J=Number.MAX_VALUE;const{devicePixelRatio:U}=window,F=h.width*U*h.height*U;for(const $ of z){const[R,tt]=$,it=R*tt,lt=Math.abs(F-it);lt<J&&(J=lt,H=$)}if(!H)return;const[,,N,K]=H;return[J,N,Y,K]})}))).filter(US).sort(([v=Number.MAX_VALUE,T],[B=Number.MAX_VALUE,_])=>v===B?T-_:v-B);if(!g.length){const v=kS.find(T=>c.includes(T));return v?d(0,"BLOCKLISTED",v):d(1,"FALLBACK",`${c} (${f})`)}const[,m,p,C]=g[0];if(m===-1)return d(0,"BLOCKLISTED",p,m,C);const E=l?a:t;let y=0;for(let v=0;v<E.length;v++)m>=E[v]&&(y=v);return d(y,"BENCHMARK",p,m,C)}),Rd=a=>Ji(()=>GS(a),["useDetectGPU"]);function NS({children:a,...t}){const e=Rd(t);return S.createElement(S.Fragment,null,a==null?void 0:a(e))}function HS(...a){const t=S.useRef([]);return t.current=a.map(e=>S.useContext(e)),S.useMemo(()=>({children:e})=>a.reduceRight((i,s,n)=>S.createElement(s.Provider,{value:t.current[n],children:i}),e),[])}function KS(a,t){const e=S.useRef(null),[i]=S.useState(()=>t?t instanceof Zt?{current:t}:t:e),[s]=S.useState(()=>new _A(void 0));S.useLayoutEffect(()=>{t&&(i.current=t instanceof Zt?t:t.current),s._root=i.current});const n=S.useRef({}),r=S.useMemo(()=>{const o={};return a.forEach(l=>Object.defineProperty(o,l.name,{enumerable:!0,get(){if(i.current)return n.current[l.name]||(n.current[l.name]=s.clipAction(l,i.current))},configurable:!0})),{ref:i,clips:a,actions:o,names:a.map(l=>l.name),mixer:s}},[a]);return Qt((o,l)=>s.update(l)),S.useEffect(()=>{const o=i.current;return()=>{n.current={},s.stopAllAction(),Object.values(r.actions).forEach(l=>{o&&s.uncacheAction(l,o)})}},[a]),r}const $S=`
|
|
74
|
+
#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )
|
|
75
|
+
vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );
|
|
76
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
77
|
+
vWorldPosition = worldPosition.xyz;
|
|
78
|
+
#endif
|
|
79
|
+
#endif
|
|
80
|
+
`,YS=`
|
|
81
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
82
|
+
uniform vec3 envMapSize;
|
|
83
|
+
uniform vec3 envMapPosition;
|
|
84
|
+
varying vec3 vWorldPosition;
|
|
85
|
+
|
|
86
|
+
vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) {
|
|
87
|
+
vec3 nDir = normalize( v );
|
|
88
|
+
vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir;
|
|
89
|
+
vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir;
|
|
90
|
+
vec3 rbminmax;
|
|
91
|
+
rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x;
|
|
92
|
+
rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y;
|
|
93
|
+
rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z;
|
|
94
|
+
float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z );
|
|
95
|
+
vec3 boxIntersection = vWorldPosition + nDir * correction;
|
|
96
|
+
return boxIntersection - cubePos;
|
|
97
|
+
}
|
|
98
|
+
#endif
|
|
99
|
+
`,VS=`
|
|
100
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
101
|
+
worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition );
|
|
102
|
+
#endif
|
|
103
|
+
`,JS=`
|
|
104
|
+
#ifdef BOX_PROJECTED_ENV_MAP
|
|
105
|
+
reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition );
|
|
106
|
+
#endif
|
|
107
|
+
`;function zS(a,t,e){a.defines.BOX_PROJECTED_ENV_MAP=!0,a.uniforms.envMapPosition={value:t},a.uniforms.envMapSize={value:e},a.vertexShader=`
|
|
108
|
+
varying vec3 vWorldPosition;
|
|
109
|
+
${a.vertexShader.replace("#include <worldpos_vertex>",$S)}`,a.fragmentShader=`
|
|
110
|
+
${YS}
|
|
111
|
+
${a.fragmentShader.replace("#include <envmap_physical_pars_fragment>",xA.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );",`vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
|
|
112
|
+
${VS}
|
|
113
|
+
`).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );",`reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
|
|
114
|
+
${JS}
|
|
115
|
+
`)}`}function qS(a=new Q,t=new Q){const[e]=S.useState(()=>({position:new Q,size:new Q}));Zh(e,{position:a,size:t});const i=S.useRef(null),s=S.useMemo(()=>({ref:i,onBeforeCompile:n=>zS(n,e.position,e.size),customProgramCacheKey:()=>JSON.stringify(e.position.toArray())+JSON.stringify(e.size.toArray())}),[...e.position.toArray(),...e.size.toArray()]);return S.useLayoutEffect(()=>void(i.current.needsUpdate=!0),[e]),s}function XS(a,t,e=.9){return t*e+a*(1-e)}const WS=a=>Math.sqrt(1-Math.pow(a-1,2));class jS{constructor({size:t=256,maxAge:e=750,radius:i=.3,intensity:s=.2,interpolate:n=0,smoothing:r=0,minForce:o=.3,blend:l="screen",ease:h=WS}={}){this.size=t,this.maxAge=e,this.radius=i,this.intensity=s,this.ease=h,this.interpolate=n,this.smoothing=r,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 En(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,n=i*i+s*s,r=Math.max(this.minForce,Math.min(n*1e4,1));if(this.force=XS(r,this.force,this.smoothing),this.interpolate){const o=Math.ceil(n/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:r})}}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,n=this.ctx.createRadialGradient(e.x,e.y,Math.max(0,s*.25),e.x,e.y,Math.max(0,s));n.addColorStop(0,`rgba(255, 255, 255, ${this.intensity})`),n.addColorStop(1,"rgba(0, 0, 0, 0.0)"),this.ctx.beginPath(),this.ctx.fillStyle=n,this.ctx.arc(e.x,e.y,Math.max(0,s),0,Math.PI*2),this.ctx.fill()}}function Ld(a={}){const{size:t,maxAge:e,radius:i,intensity:s,interpolate:n,smoothing:r,minForce:o,blend:l,ease:h}=a,u=S.useMemo(()=>new jS(a),[t,e,i,s,n,r,o,l,h]);Qt((d,A)=>void u.update(A));const c=S.useCallback(d=>u.addTouch(d.uv),[u]);return[u.texture,c]}const ZS=({children:a,...t})=>{const e=Ld(t);return S.createElement(S.Fragment,null,a==null?void 0:a(e))},tT=S.forwardRef(({font:a,color:t="#cbcbcb",bevelSize:e=.04,debug:i=!1,children:s,...n},r)=>{const[o,l]=S.useState(0),h=S.useCallback((d=1)=>l(o+d),[o]),u=S.useCallback((d=1)=>l(o-d),[o]),c=S.useMemo(()=>({incr:h,decr:u}),[h,u]);return S.useImperativeHandle(r,()=>c,[c]),S.createElement("group",n,S.createElement(S.Suspense,{fallback:null},S.createElement(tc,{top:!0,cacheKey:JSON.stringify({counter:o,font:a})},S.createElement(ec,{bevelEnabled:!0,bevelSize:e,font:a},i?S.createElement("meshNormalMaterial",{wireframe:!0}):S.createElement("meshStandardMaterial",{color:t}),o))),s)});function eT(a){const t=S.useRef(null);return S.useLayoutEffect(()=>{const e=t.current.parent,i=e==null?void 0:e.geometry;if(i){const s=e.material;e.material=t.current.__r3f.children.map(r=>r.object);const n=[...i.groups];return i.clearGroups(),e.material.forEach((r,o)=>{o<e.material.length-1&&(r.depthWrite=!1),i.addGroup(0,1/0,o)}),()=>{e.material=s,i.groups=n}}}),S.createElement("group",wt({ref:t},a))}function iT(a){switch(a){case 64:return"-64px";case 128:return"-128px";case 256:return"-256px";case 512:return"-512px";default:return""}}const sT="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json",nT="https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d";function bd(a=0,t=1024,e){const i=Ji(()=>fetch(sT).then(u=>u.json()),["matcapList"]),s=i[0],n=S.useMemo(()=>Object.keys(i).length,[]),o=`${S.useMemo(()=>typeof a=="string"?a:typeof a=="number"?i[a]:null,[a])||s}${iT(t)}.png`,l=`${nT}/${t}/${o}`;return[xa(l,e),l,n]}const rT=({children:a,id:t,format:e,onLoad:i})=>{const s=bd(t,e,i);return S.createElement(S.Fragment,null,a==null?void 0:a(s))},aT="https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb",oT="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json";function wd(a=0,t={},e){const{repeat:i=[1,1],anisotropy:s=1,offset:n=[0,0]}=t,r=Ji(()=>fetch(oT).then(d=>d.json()),["normalsList"]),o=S.useMemo(()=>Object.keys(r).length,[]),l=r[0],h=r[a]||l,u=`${aT}/normals/${h}`,c=xa(u,e);return S.useLayoutEffect(()=>{c&&(c.wrapS=c.wrapT=Vr,c.repeat=new Kt(i[0],i[1]),c.offset=new Kt(n[0],n[1]),c.anisotropy=s)},[c,s,i,n]),[c,u,o]}const lT=({children:a,id:t,onLoad:e,...i})=>{const s=wd(t,i,e);return S.createElement(S.Fragment,null,a==null?void 0:a(s))},ii={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 Ot("#ff0000"),backfaceStroke:new Ot("#0000ff"),fill:new Ot("#00ff00")},vertex:`
|
|
116
|
+
attribute vec3 barycentric;
|
|
117
|
+
|
|
118
|
+
varying vec3 v_edges_Barycentric;
|
|
119
|
+
varying vec3 v_edges_Position;
|
|
120
|
+
|
|
121
|
+
void initWireframe() {
|
|
122
|
+
v_edges_Barycentric = barycentric;
|
|
123
|
+
v_edges_Position = position.xyz;
|
|
124
|
+
}
|
|
125
|
+
`,fragment:`
|
|
126
|
+
#ifndef PI
|
|
127
|
+
#define PI 3.1415926535897932384626433832795
|
|
128
|
+
#endif
|
|
129
|
+
|
|
130
|
+
varying vec3 v_edges_Barycentric;
|
|
131
|
+
varying vec3 v_edges_Position;
|
|
132
|
+
|
|
133
|
+
uniform float strokeOpacity;
|
|
134
|
+
uniform float fillOpacity;
|
|
135
|
+
uniform float fillMix;
|
|
136
|
+
uniform float thickness;
|
|
137
|
+
uniform bool colorBackfaces;
|
|
138
|
+
|
|
139
|
+
// Dash
|
|
140
|
+
uniform bool dashInvert;
|
|
141
|
+
uniform bool dash;
|
|
142
|
+
uniform bool dashOnly;
|
|
143
|
+
uniform float dashRepeats;
|
|
144
|
+
uniform float dashLength;
|
|
145
|
+
|
|
146
|
+
// Squeeze
|
|
147
|
+
uniform bool squeeze;
|
|
148
|
+
uniform float squeezeMin;
|
|
149
|
+
uniform float squeezeMax;
|
|
150
|
+
|
|
151
|
+
// Colors
|
|
152
|
+
uniform vec3 stroke;
|
|
153
|
+
uniform vec3 backfaceStroke;
|
|
154
|
+
uniform vec3 fill;
|
|
155
|
+
|
|
156
|
+
// This is like
|
|
157
|
+
float wireframe_aastep(float threshold, float dist) {
|
|
158
|
+
float afwidth = fwidth(dist) * 0.5;
|
|
159
|
+
return smoothstep(threshold - afwidth, threshold + afwidth, dist);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
float wireframe_map(float value, float min1, float max1, float min2, float max2) {
|
|
163
|
+
return min2 + (value - min1) * (max2 - min2) / (max1 - min1);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
float getWireframe() {
|
|
167
|
+
vec3 barycentric = v_edges_Barycentric;
|
|
168
|
+
|
|
169
|
+
// Distance from center of each triangle to its edges.
|
|
170
|
+
float d = min(min(barycentric.x, barycentric.y), barycentric.z);
|
|
171
|
+
|
|
172
|
+
// for dashed rendering, we can use this to get the 0 .. 1 value of the line length
|
|
173
|
+
float positionAlong = max(barycentric.x, barycentric.y);
|
|
174
|
+
if (barycentric.y < barycentric.x && barycentric.y < barycentric.z) {
|
|
175
|
+
positionAlong = 1.0 - positionAlong;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// the thickness of the stroke
|
|
179
|
+
float computedThickness = wireframe_map(thickness, 0.0, 1.0, 0.0, 0.34);
|
|
180
|
+
|
|
181
|
+
// if we want to shrink the thickness toward the center of the line segment
|
|
182
|
+
if (squeeze) {
|
|
183
|
+
computedThickness *= mix(squeezeMin, squeezeMax, (1.0 - sin(positionAlong * PI)));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Create dash pattern
|
|
187
|
+
if (dash) {
|
|
188
|
+
// here we offset the stroke position depending on whether it
|
|
189
|
+
// should overlap or not
|
|
190
|
+
float offset = 1.0 / dashRepeats * dashLength / 2.0;
|
|
191
|
+
if (!dashInvert) {
|
|
192
|
+
offset += 1.0 / dashRepeats / 2.0;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// if we should animate the dash or not
|
|
196
|
+
// if (dashAnimate) {
|
|
197
|
+
// offset += time * 0.22;
|
|
198
|
+
// }
|
|
199
|
+
|
|
200
|
+
// create the repeating dash pattern
|
|
201
|
+
float pattern = fract((positionAlong + offset) * dashRepeats);
|
|
202
|
+
computedThickness *= 1.0 - wireframe_aastep(dashLength, pattern);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// compute the anti-aliased stroke edge
|
|
206
|
+
float edge = 1.0 - wireframe_aastep(computedThickness, d);
|
|
207
|
+
|
|
208
|
+
return edge;
|
|
209
|
+
}
|
|
210
|
+
`},hT=ic(ii.uniforms,ii.vertex+`
|
|
211
|
+
void main() {
|
|
212
|
+
initWireframe();
|
|
213
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
214
|
+
}
|
|
215
|
+
`,ii.fragment+`
|
|
216
|
+
void main () {
|
|
217
|
+
// Compute color
|
|
218
|
+
|
|
219
|
+
float edge = getWireframe();
|
|
220
|
+
vec4 colorStroke = vec4(stroke, edge);
|
|
221
|
+
|
|
222
|
+
#ifdef FLIP_SIDED
|
|
223
|
+
colorStroke.rgb = backfaceStroke;
|
|
224
|
+
#endif
|
|
225
|
+
|
|
226
|
+
vec4 colorFill = vec4(fill, fillOpacity);
|
|
227
|
+
vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
|
|
228
|
+
|
|
229
|
+
gl_FragColor = outColor;
|
|
230
|
+
}
|
|
231
|
+
`);function cT(a,t){a.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...t},e.vertexShader=e.vertexShader.replace("void main() {",`
|
|
232
|
+
${ii.vertex}
|
|
233
|
+
void main() {
|
|
234
|
+
initWireframe();
|
|
235
|
+
`),e.fragmentShader=e.fragmentShader.replace("void main() {",`
|
|
236
|
+
${ii.fragment}
|
|
237
|
+
void main() {
|
|
238
|
+
`),e.fragmentShader=e.fragmentShader.replace("#include <color_fragment>",`
|
|
239
|
+
#include <color_fragment>
|
|
240
|
+
float edge = getWireframe();
|
|
241
|
+
vec4 colorStroke = vec4(stroke, edge);
|
|
242
|
+
#ifdef FLIP_SIDED
|
|
243
|
+
colorStroke.rgb = backfaceStroke;
|
|
244
|
+
#endif
|
|
245
|
+
vec4 colorFill = vec4(mix(diffuseColor.rgb, fill, fillMix), mix(diffuseColor.a, fillOpacity, fillMix));
|
|
246
|
+
vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
|
|
247
|
+
|
|
248
|
+
diffuseColor.rgb = outColor.rgb;
|
|
249
|
+
diffuseColor.a *= outColor.a;
|
|
250
|
+
`)},a.side=Rs,a.transparent=!0}function uT(a,t){S.useEffect(()=>{var e;return void(a.fillOpacity.value=(e=t.fillOpacity)!==null&&e!==void 0?e:a.fillOpacity.value)},[t.fillOpacity]),S.useEffect(()=>{var e;return void(a.fillMix.value=(e=t.fillMix)!==null&&e!==void 0?e:a.fillMix.value)},[t.fillMix]),S.useEffect(()=>{var e;return void(a.strokeOpacity.value=(e=t.strokeOpacity)!==null&&e!==void 0?e:a.strokeOpacity.value)},[t.strokeOpacity]),S.useEffect(()=>{var e;return void(a.thickness.value=(e=t.thickness)!==null&&e!==void 0?e:a.thickness.value)},[t.thickness]),S.useEffect(()=>void(a.colorBackfaces.value=!!t.colorBackfaces),[t.colorBackfaces]),S.useEffect(()=>void(a.dash.value=!!t.dash),[t.dash]),S.useEffect(()=>void(a.dashInvert.value=!!t.dashInvert),[t.dashInvert]),S.useEffect(()=>{var e;return void(a.dashRepeats.value=(e=t.dashRepeats)!==null&&e!==void 0?e:a.dashRepeats.value)},[t.dashRepeats]),S.useEffect(()=>{var e;return void(a.dashLength.value=(e=t.dashLength)!==null&&e!==void 0?e:a.dashLength.value)},[t.dashLength]),S.useEffect(()=>void(a.squeeze.value=!!t.squeeze),[t.squeeze]),S.useEffect(()=>{var e;return void(a.squeezeMin.value=(e=t.squeezeMin)!==null&&e!==void 0?e:a.squeezeMin.value)},[t.squeezeMin]),S.useEffect(()=>{var e;return void(a.squeezeMax.value=(e=t.squeezeMax)!==null&&e!==void 0?e:a.squeezeMax.value)},[t.squeezeMax]),S.useEffect(()=>void(a.stroke.value=t.stroke?new Ot(t.stroke):a.stroke.value),[t.stroke]),S.useEffect(()=>void(a.fill.value=t.fill?new Ot(t.fill):a.fill.value),[t.fill]),S.useEffect(()=>void(a.backfaceStroke.value=t.backfaceStroke?new Ot(t.backfaceStroke):a.backfaceStroke.value),[t.backfaceStroke])}function dT(a){return!!(a!=null&&a.geometry)}function AT(a){return!!(a!=null&&a.isBufferGeometry)}function fT(a){return!!(a!=null&&a.current)}function Oh(a){return(a==null?void 0:a.current)!==void 0}function Qh(a){return a.type==="WireframeGeometry"}function gT(){const a={};for(const t in ii.uniforms)a[t]={value:ii.uniforms[t]};return a}function mT(a,t){const i=a.getAttribute("position").count,s=[];for(let n=0;n<i;n++){const r=n%2===0,o=t?1:0;r?s.push(0,0,1,0,1,0,1,0,o):s.push(0,1,0,0,0,1,1,0,o)}return new Jr(Float32Array.from(s),3)}function Pd(a){const t=fT(a)?a.current:a;if(AT(t))return t;{if(Qh(t))throw new Error("Wireframe: WireframeGeometry is not supported.");const e=t.parent;if(dT(e)){if(Qh(e.geometry))throw new Error("Wireframe: WireframeGeometry is not supported.");return e.geometry}}}function Md(a,t){if(a.index){console.warn("Wireframe: Requires non-indexed geometry, converting to non-indexed geometry.");const i=a.toNonIndexed();a.copy(i),a.setIndex(null)}const e=mT(a,t);a.setAttribute("barycentric",e)}function pT({geometry:a,simplify:t=!1,...e}){zh({MeshWireframeMaterial:hT});const[i,s]=S.useState(null);S.useLayoutEffect(()=>{const r=Pd(a);if(!r)throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry.");Md(r,t),Oh(a)&&s(r)},[t,a]);const n=Oh(a)?i:a;return S.createElement(S.Fragment,null,n&&S.createElement("mesh",{geometry:n},S.createElement("meshWireframeMaterial",wt({attach:"material",transparent:!0,side:Rs,polygonOffset:!0,polygonOffsetFactor:-4},e,{extensions:{derivatives:!0,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1}}))))}function ET({simplify:a=!1,...t}){const e=S.useRef(null),i=S.useMemo(()=>gT(),[ii.uniforms]);return uT(i,t),S.useLayoutEffect(()=>{const s=Pd(e);if(!s)throw new Error("Wireframe: Must be a child of a Mesh, Line or Points object or specify a geometry prop.");const n=s.clone();return Md(s,a),()=>{s.copy(n),n.dispose()}},[a]),S.useLayoutEffect(()=>{const s=e.current.parent,n=s.material.clone();return cT(s.material,i),()=>{s.material.dispose(),s.material=n}},[]),S.createElement("object3D",{ref:e})}function IT({geometry:a,...t}){return a?S.createElement(pT,wt({geometry:a},t)):S.createElement(ET,t)}function CT({opacity:a,alphaMap:t}){const e=S.useRef(null),i=S.useRef(null),s=S.useRef({value:1}),n=S.useRef({value:null}),r=S.useRef({value:!1});return S.useLayoutEffect(()=>{e.current.onBeforeCompile=i.current.onBeforeCompile=o=>{const l=o.fragmentShader.indexOf("void main");let h="",u,c=l;for(;u!==`
|
|
251
|
+
`&&c<l+100;)u=o.fragmentShader.charAt(c),h+=u,c++;h=h.trim(),o.vertexShader=o.vertexShader.replace("void main() {",`
|
|
252
|
+
varying vec2 custom_vUv;
|
|
253
|
+
|
|
254
|
+
void main() {
|
|
255
|
+
custom_vUv = uv;
|
|
256
|
+
|
|
257
|
+
`),o.fragmentShader=o.fragmentShader.replace(h,`
|
|
258
|
+
uniform float uShadowOpacity;
|
|
259
|
+
uniform sampler2D uAlphaMap;
|
|
260
|
+
uniform bool uHasAlphaMap;
|
|
261
|
+
|
|
262
|
+
varying vec2 custom_vUv;
|
|
263
|
+
|
|
264
|
+
float bayerDither2x2( vec2 v ) {
|
|
265
|
+
return mod( 3.0 * v.y + 2.0 * v.x, 4.0 );
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
float bayerDither4x4( vec2 v ) {
|
|
269
|
+
vec2 P1 = mod( v, 2.0 );
|
|
270
|
+
vec2 P2 = mod( floor( 0.5 * v ), 2.0 );
|
|
271
|
+
return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
void main() {
|
|
275
|
+
float alpha =
|
|
276
|
+
uHasAlphaMap ?
|
|
277
|
+
uShadowOpacity * texture2D(uAlphaMap, custom_vUv).x
|
|
278
|
+
: uShadowOpacity;
|
|
279
|
+
|
|
280
|
+
if( ( bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ) ) / 16.0 >= alpha ) discard;
|
|
281
|
+
|
|
282
|
+
`),o.uniforms.uShadowOpacity=s.current,o.uniforms.uAlphaMap=n.current,o.uniforms.uHasAlphaMap=r.current}},[]),Qt(()=>{var o;const l=(o=e.current.__r3f)==null||(o=o.parent)==null?void 0:o.object;if(l){const h=l.material;h&&(s.current.value=a??h.opacity,t===!1?(n.current.value=null,r.current.value=!1):(n.current.value=t||h.alphaMap,r.current.value=!!n.current.value))}}),S.createElement(S.Fragment,null,S.createElement("meshDepthMaterial",{ref:e,attach:"customDepthMaterial",depthPacking:DA}),S.createElement("meshDistanceMaterial",{ref:i,attach:"customDistanceMaterial"}))}const Uh=new At,Gh=new RA,Kr=new Ba,$r=new Q;function yT(a,t){const e=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(e.boundingSphere===null&&e.computeBoundingSphere(),Kr.copy(e.boundingSphere),Kr.applyMatrix4(s),a.ray.intersectsSphere(Kr)!==!1&&(Uh.copy(s).invert(),Gh.copy(a.ray).applyMatrix4(Uh),!(e.boundingBox!==null&&Gh.intersectBox(e.boundingBox,$r)===null)&&t.push({distance:$r.distanceTo(a.ray.origin),point:$r.clone(),object:this})))}const vT=S.forwardRef(({options:a={video:!0},...t},e)=>{const i=Ji(()=>navigator.mediaDevices.getDisplayMedia(a),[]);return S.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),sc([])},[i]),S.createElement(Yn,wt({ref:e},t,{src:i}))}),Fd=S.forwardRef(({constraints:a={audio:!1,video:{facingMode:"user"}},...t},e)=>{const i=Ji(()=>navigator.mediaDevices.getUserMedia(a),[]);return S.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),sc([])},[i]),S.createElement(Yn,wt({ref:e},t,{src:i}))});function Nh(a,t){return a.clone().add(t).multiplyScalar(.5)}function Pi(a,t,e){const i=a.localToWorld(t);return e.worldToLocal(i)}const kd=S.createContext({}),BT=S.forwardRef(({camera:a,videoTexture:t={start:!0},manualDetect:e=!1,faceLandmarkerResult:i,manualUpdate:s=!1,makeDefault:n,smoothTime:r=.25,offset:o=!0,offsetScalar:l=80,eyes:h=!1,eyesAsOrigin:u=!0,depth:c=.15,debug:d=!1,facemesh:A},f)=>{var g,m;const p=q(it=>it.scene),C=q(it=>it.camera),E=q(it=>it.set),y=q(it=>it.get),v=a||C,T=S.useRef(null),[B]=S.useState(()=>new Zt),[_]=S.useState(()=>new Q),[D]=S.useState(()=>new Q),[x]=S.useState(()=>new Q),[M]=S.useState(()=>new Q),k=S.useCallback(()=>{B.parent=v.parent;const it=T.current;if(it){const{outerRef:lt,eyeRightRef:Dt,eyeLeftRef:qt}=it;if(Dt.current&&qt.current){const{irisDirRef:Xe}=Dt.current,{irisDirRef:zi}=qt.current;Xe.current&&zi.current&<.current&&(_.copy(Pi(Xe.current,new Q(0,0,0),lt.current)),D.copy(Pi(zi.current,new Q(0,0,0),lt.current)),B.position.copy(Pi(lt.current,Nh(_,D),v.parent||p)),x.copy(Pi(Xe.current,new Q(0,0,1),lt.current)),M.copy(Pi(zi.current,new Q(0,0,1),lt.current)),B.lookAt(lt.current.localToWorld(Nh(x,M))))}else lt.current&&(B.position.copy(Pi(lt.current,new Q(0,0,0),v.parent||p)),B.lookAt(lt.current.localToWorld(new Q(0,0,1))))}return B},[v,D,M,_,x,p,B]),[X]=S.useState(()=>new Zt),W=S.useCallback(function(it,lt){if(v){var Dt;(Dt=lt)!==null&&Dt!==void 0||(lt=k()),r>0?(si.damp3(X.position,lt.position,r,it,void 0,void 0,1e-9),si.dampE(X.rotation,lt.rotation,r,it,void 0,void 0,1e-9)):(X.position.copy(lt.position),X.rotation.copy(lt.rotation)),v.position.copy(X.position),v.rotation.copy(X.rotation)}},[v,k,r,X.position,X.rotation]);Qt((it,lt)=>{s||W(lt)});const H=S.useRef(null),[Y,z]=S.useState(),J=nc(),U=S.useCallback((it,lt)=>{const Dt=H.current;if(!Dt)return;const qt=Dt.source.data,Xe=J==null?void 0:J.detectForVideo(qt,it);z(Xe)},[J]),F=S.useMemo(()=>Object.assign(Object.create(LA.prototype),{computeTarget:k,update:W,facemeshApiRef:T}),[k,W]);S.useImperativeHandle(f,()=>F,[F]),S.useEffect(()=>{if(n){const it=y().controls;return E({controls:F}),()=>E({controls:it})}},[n,F,y,E]);const N=i??Y,K=N==null?void 0:N.faceLandmarks[0],$=N==null||(g=N.facialTransformationMatrixes)==null?void 0:g[0],R=N==null||(m=N.faceBlendshapes)==null?void 0:m[0],tt={onVideoFrame:U,...t};return S.createElement(kd.Provider,{value:F},!e&&S.createElement(S.Suspense,{fallback:null},"src"in tt?S.createElement(Yn,wt({ref:H},tt)):S.createElement(Fd,wt({ref:H},tt))),S.createElement(rc,wt({ref:T,children:S.createElement("meshNormalMaterial",{side:Rs})},A,{points:K,depth:c,facialTransformationMatrix:$,faceBlendshapes:R,eyes:h,eyesAsOrigin:u,offset:o,offsetScalar:l,debug:d,"rotation-z":Math.PI,visible:d})))}),ST=()=>S.useContext(kd),qT=Object.freeze(Object.defineProperty({__proto__:null,AccumulativeShadows:bA,AdaptiveDpr:wA,AdaptiveEvents:PA,ArcballControls:MI,AsciiRenderer:MA,BBAnchor:FA,Backdrop:kA,BakeShadows:OA,Billboard:QA,Bounds:UA,Box:GA,Bvh:NA,CameraControls:NI,CameraShake:HA,Capsule:KA,CatmullRomLine:$A,Caustics:YA,Center:tc,Circle:VA,Clone:Ta,Cloud:JA,CloudInstance:zA,Clouds:qA,ComputedAttribute:XA,Cone:WA,ContactShadows:jA,CubeCamera:ZA,CubeTexture:YI,CubicBezierLine:tf,CurveModifier:ef,CycleRaycast:sf,Cylinder:nf,Decal:rf,Detailed:af,DetectGPU:NS,DeviceOrientationControls:LI,Dodecahedron:of,DragControls:r0,Edges:lf,Effects:hf,Environment:cf,EnvironmentCube:uf,EnvironmentMap:df,EnvironmentPortal:Af,Example:tT,Extrude:ff,FaceControls:BT,FaceLandmarker:gf,FaceLandmarkerDefaults:mf,Facemesh:rc,FacemeshDatas:pf,FacemeshEye:Ef,FacemeshEyeDefaults:If,Fbo:Cf,Fbx:VI,FirstPersonControls:OI,Fisheye:yf,Float:vf,FlyControls:bI,GizmoHelper:Bf,GizmoViewcube:Sf,GizmoViewport:Tf,Gltf:RI,GradientTexture:_f,GradientType:xf,Grid:Df,Helper:Rf,Html:Lf,Hud:bf,Icosahedron:wf,Image:Pf,Instance:Mf,InstancedAttribute:Ff,Instances:kf,IsObject:zr,KeyboardControls:cE,Ktx2:JI,Lathe:Of,Lightformer:Qf,Line:Uf,Loader:n0,MapControls:wI,MarchingCube:Gf,MarchingCubes:Nf,MarchingPlane:Hf,Mask:Kf,MatcapTexture:rT,Merged:$f,MeshDiscardMaterial:Yf,MeshDistortMaterial:Vf,MeshPortalMaterial:Jf,MeshReflectorMaterial:zf,MeshRefractionMaterial:qf,MeshTransmissionMaterial:Xf,MeshWobbleMaterial:Wf,MotionPathControls:$I,MultiMaterial:eT,NormalTexture:lT,Octahedron:jf,OrbitControls:Zf,OrthographicCamera:tg,Outlines:eg,PerformanceMonitor:ig,PerspectiveCamera:sg,PivotControls:ng,Plane:rg,Point:ag,PointMaterial:og,PointMaterialImpl:lg,PointerLockControls:kI,Points:hg,PointsBuffer:cg,Polyhedron:ug,PositionMesh:dg,PositionPoint:Ag,PositionalAudio:fg,Preload:gg,PresentationControls:oE,Progress:i0,QuadraticBezierLine:mg,RandomizedLight:pg,RenderCubeTexture:Eg,RenderTexture:Ig,Resize:Cg,Ring:yg,RoundedBox:vg,Sampler:Bg,ScreenQuad:Sg,ScreenSizer:DI,ScreenSpace:Tg,ScreenVideoTexture:vT,Scroll:aE,ScrollControls:sE,Segment:_g,SegmentObject:xg,Segments:Dg,Select:Rg,Shadow:Lg,ShadowAlpha:CT,Shape:bg,Sky:wg,SoftShadows:Pg,Sparkles:Mg,Sphere:Fg,Splat:kg,SpotLight:Og,SpotLightShadow:Qg,SpriteAnimator:Ug,Stage:Gg,Stars:Ng,Stats:RS,StatsGl:wS,Svg:Hg,Tetrahedron:Kg,Text:$g,Text3D:ec,Texture:Yg,Torus:Vg,TorusKnot:Jg,TrackballControls:PI,Trail:zg,TrailTexture:ZS,TransformControls:FI,Tube:qg,VideoTexture:Yn,View:Xg,WebcamVideoTexture:Fd,Wireframe:IT,accumulativeContext:Wg,calcPosFromAngles:jg,calculateScaleFactor:Jh,checkIfFrameIsEmpty:Zg,createInstances:tm,getFirstFrame:em,isWebGL2Available:im,meshBounds:yT,shaderMaterial:ic,useAnimations:KS,useAspect:MS,useBVH:sm,useBounds:nm,useBoxProjectedEnv:qS,useCamera:FS,useContextBridge:HS,useCubeCamera:rm,useCubeTexture:Oa,useCursor:e0,useDepthBuffer:PS,useDetectGPU:Rd,useEnvironment:am,useFBO:jh,useFBX:kn,useFaceControls:ST,useFaceLandmarker:nc,useFont:om,useGLTF:Ls,useGizmoContext:lm,useHelper:hm,useIntersect:cm,useKTX2:On,useKeyboardControls:uE,useMask:um,useMatcapTexture:bd,useMotion:Yc,useNormalTexture:wd,usePerformanceMonitor:dm,useProgress:ba,useScroll:Pa,useSelect:Am,useSpriteAnimator:fm,useSpriteLoader:gm,useSurfaceSampler:mm,useTexture:xa,useTrail:pm,useTrailTexture:Ld,useVideoTexture:Td},Symbol.toStringTag,{value:"Module"}));function Od(a,t,e,i){const s=q(n=>n.camera);Qt(()=>{a.current!=null&&t(Em(s,a.current,e,i))})}function TT({children:a,direction:t,angle:e=Math.PI/2}){const i=S.useRef(null);return Od(i,s=>{i.current!=null&&(i.current.visible=s)},t,e),Ve.jsx("group",{ref:i,children:a})}function _T({children:a,direction:t,angle:e=Math.PI/2}){const i=S.useRef(null),[s,n]=S.useState(!1);return Od(i,n,t,e),s?Ve.jsx(Ve.Fragment,{children:a}):null}function xT({children:a,mode:t}){const e=Da(t);return Ve.jsx("group",{visible:e,children:a})}function DT({children:a,mode:t}){return Da(t)?Ve.jsx(Ve.Fragment,{children:a}):null}function RT({children:a}){const t=Ra();return Ve.jsx("group",{visible:t==null||t==="visible",children:a})}function LT({children:a}){const t=Ra();return t!="visible"&&t!=null?null:Ve.jsx(Ve.Fragment,{children:a})}function bT(){const a=Fn();return S.useMemo(()=>La.bind(null,a),[a])}function wT(){const[a,t]=S.useState(void 0),e=S.useRef(()=>{}),i=Fn(),s=S.useCallback(async n=>{var l;(l=e.current)==null||l.call(e),e.current=void 0;let r=!1;e.current=()=>r=!0;const o=await La(i,n);if(r){o==null||o.delete();return}return e.current=()=>o==null?void 0:o.delete(),t(o),o},[i]);return S.useEffect(()=>()=>{var n;return void((n=e.current)==null?void 0:n.call(e))},[]),[a,s]}function PT(a,t={},e={},i="left"){const s=Fn(),n=S.useMemo(()=>Im(),[]);Qt((r,o,l)=>n(typeof a=="function"?a:a.current,s,r.camera,o,t,e,i,o,r,l))}function MT({batchEvents:a,clickThesholdMs:t,clickThresholdMs:e,contextMenuButton:i,customSort:s,dblClickThresholdMs:n,filter:r,forwardPointerCapture:o,intersectEveryFrame:l,pointerTypePrefix:h}){const u=q(f=>f.gl.domElement),c=q(f=>f.frameloop==="always"),d=q(f=>f.camera),A=q(f=>f.scene);return S.useEffect(()=>{const{destroy:f,update:g}=Cm(u,()=>d,A,{batchEvents:a??c,clickThesholdMs:t,clickThresholdMs:e,contextMenuButton:i,customSort:s,dblClickThresholdMs:n,filter:r,forwardPointerCapture:o,intersectEveryFrame:l,pointerTypePrefix:h}),m=Xh(g);return()=>{m(),f()}},[u,d,A,c,a,e,t,i,s,n,r,o,l,h]),null}const FT=()=>({enabled:!1,priority:0}),XT=Object.freeze(Object.defineProperty({__proto__:null,ARButton:ym,CombinedPointer:vm,DefaultXRController:Bm,DefaultXRControllerGrabPointer:Sm,DefaultXRGaze:Tm,DefaultXRHand:_m,DefaultXRHandGrabPointer:xm,DefaultXRHandTouchPointer:Dm,DefaultXRInputSourceRayPointer:Rm,DefaultXRInputSourceTeleportPointer:Lm,DefaultXRScreenInput:bm,DefaultXRTransientPointer:wm,FallbackXRLayerImplementation:Pm,IfFacingCamera:_T,IfInSessionMode:Mm,IfSessionModeSupported:DT,IfSessionVisible:LT,Interactive:Fm,NotInXR:km,PointerCursorModel:Om,PointerEvents:MT,PointerRayModel:Qm,RayGrab:Um,RootCombinedPointer:Gm,ShowIfFacingCamera:TT,ShowIfInSessionMode:Nm,ShowIfSessionModeSupported:xT,ShowIfSessionVisible:RT,TeleportPointerRayModel:Hm,TeleportTarget:Km,VRButton:$m,XR:Ym,XRButton:Vm,XRControllerComponent:Jm,XRControllerModel:zm,XRDomOverlay:qm,XRHandJoint:Xm,XRHandModel:Wm,XRHitTest:jm,XRLayer:Zm,XRLayerImplementation:tp,XRMeshModel:ep,XROrigin:ip,XRPlaneModel:sp,XRSpace:np,createXRHitTestSource:rp,createXRStore:ap,defaultGrabPointerOpacity:op,defaultRayPointerOpacity:lp,defaultTouchPointerOpacity:hp,isAppleVisionPro:cp,isXRInputSourceState:up,noEvents:FT,privateKeys:dp,requestXRAnchor:La,requestXRHitTest:Ap,useApplyXRSpaceMatrix:fp,useGetXRSpaceMatrix:gp,useGrabPointer:mp,useHover:pp,useInitRoomCapture:Ep,useInteraction:Ip,useLayerStore:Cp,useLinesPointer:yp,useLoadXRControllerLayout:vp,useLoadXRControllerModel:Bp,usePointerXRInputSourceEvents:Sp,useRayPointer:Tp,useRequestXRAnchor:bT,useSessionFeatureEnabled:_p,useSessionModeSupported:xp,useTouchPointer:Dp,useXR:Rp,useXRAnchor:wT,useXRControllerButtonEvent:Lp,useXRControllerLocomotion:PT,useXRControllerState:bp,useXREvent:wp,useXRGazeState:Pp,useXRHandState:Mp,useXRHitTest:Fp,useXRHitTestSource:kp,useXRInputSourceEvent:Op,useXRInputSourceState:Qp,useXRInputSourceStateContext:Up,useXRInputSourceStates:Gp,useXRMeshGeometry:Np,useXRMeshes:Hp,useXRPlaneGeometry:Kp,useXRPlanes:$p,useXRReferenceSpace:Yp,useXRRequestHitTest:Vp,useXRScreenInputState:Jp,useXRSessionFeatureEnabled:zp,useXRSessionModeSupported:Da,useXRSessionVisibilityState:Ra,useXRSpace:qp,useXRStore:Fn,useXRTransientPointerState:Xp},Symbol.toStringTag,{value:"Module"}));export{qT as D,XT as X};
|
|
283
|
+
//# sourceMappingURL=chunk-DG0_h2Gk.js.map
|