vuer 0.0.67__py3-none-any.whl → 0.0.68__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vuer might be problematic. Click here for more details.

Files changed (58) hide show
  1. vuer/__pycache__/events.cpython-311.pyc +0 -0
  2. vuer/__pycache__/server.cpython-311.pyc +0 -0
  3. vuer/client_build/404.html +4 -4
  4. vuer/client_build/assets/chunks/chunk-BAlAa4Lb.js +3 -0
  5. vuer/client_build/assets/chunks/chunk-BAlAa4Lb.js.map +1 -0
  6. vuer/client_build/assets/chunks/chunk-BPjIPZ-5.js +11201 -0
  7. vuer/client_build/assets/chunks/chunk-BPjIPZ-5.js.map +1 -0
  8. vuer/client_build/assets/chunks/chunk-BUjbjpZo.js +3 -0
  9. vuer/client_build/assets/chunks/chunk-BUjbjpZo.js.map +1 -0
  10. vuer/client_build/assets/chunks/chunk-BhBOHBDA.js +281 -0
  11. vuer/client_build/assets/chunks/chunk-BhBOHBDA.js.map +1 -0
  12. vuer/client_build/assets/chunks/chunk-CKREfZ-q.js +8555 -0
  13. vuer/client_build/assets/chunks/chunk-CKREfZ-q.js.map +1 -0
  14. vuer/client_build/assets/chunks/chunk-CQIL0Xd9.js +53 -0
  15. vuer/client_build/assets/chunks/chunk-CQIL0Xd9.js.map +1 -0
  16. vuer/client_build/assets/chunks/chunk-CcVTpo0V.js +14934 -0
  17. vuer/client_build/assets/chunks/chunk-CcVTpo0V.js.map +1 -0
  18. vuer/client_build/assets/chunks/chunk-CxXHyfhp.js +2 -0
  19. vuer/client_build/assets/chunks/chunk-CxXHyfhp.js.map +1 -0
  20. vuer/client_build/assets/chunks/chunk-CyJGVc6_.js +2 -0
  21. vuer/client_build/assets/chunks/chunk-CyJGVc6_.js.map +1 -0
  22. vuer/client_build/assets/chunks/chunk-rdAuxDM1.js +102 -0
  23. vuer/client_build/assets/chunks/chunk-rdAuxDM1.js.map +1 -0
  24. vuer/client_build/assets/entries/entry-client-routing.BSaUS4Zk.js +5 -0
  25. vuer/client_build/assets/entries/entry-client-routing.BSaUS4Zk.js.map +1 -0
  26. vuer/client_build/assets/entries/pages_editor.C0a9TsP6.js +2 -0
  27. vuer/client_build/assets/entries/pages_editor.C0a9TsP6.js.map +1 -0
  28. vuer/client_build/assets/entries/pages_error.CI4fTdMq.js +2 -0
  29. vuer/client_build/assets/entries/pages_error.CI4fTdMq.js.map +1 -0
  30. vuer/client_build/assets/entries/pages_index.BasHwMRM.js +2 -0
  31. vuer/client_build/assets/entries/pages_index.BasHwMRM.js.map +1 -0
  32. vuer/client_build/assets/entries/pages_simple.BMpy5Em5.js +2 -0
  33. vuer/client_build/assets/entries/pages_simple.BMpy5Em5.js.map +1 -0
  34. vuer/client_build/assets/entries/pages_studio.qAQVW6ug.js +150 -0
  35. vuer/client_build/assets/entries/pages_studio.qAQVW6ug.js.map +1 -0
  36. vuer/client_build/assets/static/onRenderClient.BJHLNmZB.css +1 -0
  37. vuer/client_build/editor/index.html +6 -6
  38. vuer/client_build/index.html +6 -6
  39. vuer/client_build/pages/editor/icons/cursor.d.ts +2 -0
  40. vuer/client_build/simple/index.html +5 -5
  41. vuer/client_build/src/components/ControlLayout/ControlLayout.d.ts +1 -0
  42. vuer/client_build/src/components/ControlLayout/LayoutBottom/LayoutBottom.d.ts +1 -0
  43. vuer/client_build/src/components/ControlLayout/LayoutLeft/LayoutLeft.d.ts +1 -0
  44. vuer/client_build/src/components/ControlLayout/LayoutRight/LayoutRight.d.ts +1 -0
  45. vuer/client_build/src/components/ControlLayout/LayoutTop/LayoutTop.d.ts +1 -0
  46. vuer/client_build/studio/index.html +6 -6
  47. vuer/schemas/__pycache__/__init__.cpython-311.pyc +0 -0
  48. vuer/schemas/__pycache__/html_components.cpython-311.pyc +0 -0
  49. vuer/schemas/__pycache__/material_components.cpython-311.pyc +0 -0
  50. vuer/schemas/__pycache__/scene_components.cpython-311.pyc +0 -0
  51. vuer/schemas/scene_components.py +39 -0
  52. vuer/server.py +12 -5
  53. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/METADATA +1 -1
  54. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/RECORD +58 -19
  55. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/WHEEL +0 -0
  56. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/entry_points.txt +0 -0
  57. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/licenses/LICENSE +0 -0
  58. {vuer-0.0.67.dist-info → vuer-0.0.68.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,281 @@
1
+ import{s as dh,D as Cs,t as Q,v as fh,w as wt,x as Kt,y as k,z as zu,B as mt,Q as yt,E as hs,I as Zr,J as ze,K as kt,N as $e,O as Ut,U as Ga,X as ot,Y as $i,$ as qt,a0 as xn,a1 as ta,a2 as _s,a3 as cs,a4 as Ee,a5 as ni,a6 as Pe,a7 as Ge,a8 as nt,a9 as Et,aa as ui,ab as ri,ac as mh,ad as bs,ae as Un,af as br,ag as ph,ah as ea,ai as Nn,aj as Ht,ak as ne,al as Yu,am as Xu,an as ju,ao as Wu,ap as Ju,aq as Qu,ar as qu,as as gh,at as Ir,au as Ha,av as Lr,aw as Gn,ax as Zu,ay as td,az as $a,aA as cn,aB as Ka,aC as ed,aD as id,aE as sd,aF as nd,aG as rd,aH as ad,aI as od,aJ as ld,aK as hd,aL as cd,aM as ud,aN as Eh,aO as Se,aP as ia,aQ as sa,aR as dd,aS as fd,aT as yh,aU as md,aV as pd,aW as gd,aX as vh,aY as Rr,aZ as na,a_ as Ki,a$ as Ed,b0 as Ah,b1 as Th,b2 as yd,b3 as vd,b4 as Ad,b5 as _h,b6 as Sh,b7 as Td,b8 as _d,b9 as Sd,ba as xh,bb as Ch,bc as ra,bd as bh,be as xd,bf as Cd,bg as bd,bh as Ih,bi as Lh,bj as Id,bk as Rh,bl as Ld,bm as Rd,bn as Dd,bo as Pd,bp as wd,bq as Md,br as Bd,bs as Od,bt as Fd,bu as kd,bv as Ud,bw as Nd,bx as Gd,by as Hd,bz as $d,bA as Kd,bB as Vd,bC as zd,bD as Yd,bE as Xd,bF as jd,bG as Wd,bH as Jd,bI as Qd,bJ as qd,bK as Zd,bL as tf,bM as ef,bN as sf,bO as nf,bP as rf,bQ as af,bR as of,bS as lf,bT as hf,bU as cf,bV as uf,bW as df,bX as ff,bY as mf,bZ as pf,b_ as gf,b$ as Ef,c0 as yf,c1 as vf,c2 as Af,c3 as Tf,c4 as _f,c5 as Sf,c6 as xf,c7 as Cf,c8 as bf,c9 as If,ca as Lf,cb as Rf,cc as Df,cd as Pf,ce as wf,cf as Mf,cg as Bf,ch as Of,ci as Ff,cj as kf,ck as Uf,cl as Nf,cm as Gf,cn as Hf,co as $f,cp as Kf,cq as Vf,cr as zf,cs as Yf,ct as Xf,cu as jf,cv as Wf,cw as Jf,cx as Qf,cy as qf,cz as Zf,cA as tm,cB as em,cC as im,cD as sm,cE as nm,cF as rm,cG as am,cH as om,cI as lm,cJ as hm,cK as cm,cL as um,cM as dm,cN as fm,cO as mm,cP as pm,cQ as gm,cR as Em,cS as ym,cT as vm,cU as Am,cV as Tm,cW as _m,cX as Sm,cY as xm,cZ as Cm,c_ as bm,c$ as Im,d0 as Lm,d1 as Rm,d2 as Dm,d3 as Pm,d4 as wm,d5 as Mm,d6 as Bm,d7 as Om,d8 as Fm,d9 as km,da as Um,db as Nm,dc as Gm,dd as Hm,de as $m,df as Km,dg as Vm,dh as zm,di as Ym,dj as Xm,dk as jm,dl as Wm,dm as Jm,dn as Qm,dp as qm,dq as Zm,dr as tp,ds as ep,dt as ip,du as sp,dv as np,dw as rp,dx as ap,dy as op,dz as lp,dA as hp,dB as cp,dC as up,dD as dp,dE as fp,dF as mp,dG as pp,dH as aa,dI as oa,dJ as Cn,dK as la,dL as gp,dM as Ep,dN as yp,dO as vp,dP as Ap,dQ as Tp,dR as _p,dS as Sp,dT as xp,dU as Cp,dV as bp,dW as Ip,dX as Lp,dY as Rp,dZ as Dp,d_ as Pp,d$ as wp,e0 as Mp,e1 as Bp,e2 as Op,e3 as Fp,e4 as kp,e5 as Up,e6 as Np,e7 as Gp,e8 as Hp,e9 as $p,ea as Kp,eb as Vp,ec as zp,ed as Yp,ee as Xp,ef as jp,eg as Wp,eh as Jp,ei as Qp,ej as qp,ek as Zp,el as tg,em as eg,en as ig,eo as sg,ep as ng,eq as rg,er as ag,es as og,et as lg,eu as hg,ev as cg,ew as ug,ex as dg,ey as fg,ez as mg,eA as pg,eB as gg,eC as Eg,eD as yg,eE as vg,eF as Ag,eG as Tg,eH as _g,eI as Sg,eJ as xg,eK as Cg,eL as bg,eM as Ig,eN as Lg,eO as Rg,eP as Dg,eQ as Pg,eR as wg,eS as Mg,eT as Bg,eU as Og,eV as Fg,eW as kg,eX as Ug,eY as Ng,eZ as Gg,e_ as Hg,e$ as $g,f0 as Kg,f1 as Vg,f2 as zg,f3 as Yg,f4 as Xg,f5 as jg}from"./chunk-BPjIPZ-5.js";import{r as x,k as Wg,l as Jg,m as Qg,j as Ke}from"./chunk-CQIL0Xd9.js";import{_ as qg}from"./chunk-D7HrI6pR.js";function Zg(a,t="pointer",e="auto",i=document.body){x.useEffect(()=>{if(a)return i.style.cursor=t,()=>void(i.style.cursor=e)},[a])}let Xi=0;const ha=dh(a=>(Cs.onStart=(t,e,i)=>{a({active:!0,item:t,loaded:e,total:i,progress:(e-Xi)/(i-Xi)*100})},Cs.onLoad=()=>{a({active:!1})},Cs.onError=t=>a(e=>({errors:[...e.errors,t]})),Cs.onProgress=(t,e,i)=>{e===i&&(Xi=i),a({active:!0,item:t,loaded:e,total:i,progress:(e-Xi)/(i-Xi)*100||100})},{errors:[],active:!1,progress:0,item:"",loaded:0,total:0}));function t0({children:a}){const t=ha();return x.createElement(x.Fragment,null,a==null?void 0:a(t))}const e0=a=>`Loading ${a.toFixed(2)}%`;function i0({containerStyles:a,innerStyles:t,barStyles:e,dataStyles:i,dataInterpolation:s=e0,initialState:n=r=>r}){const{active:r,progress:o}=ha(),h=x.useRef(0),l=x.useRef(0),c=x.useRef(null),[u,d]=x.useState(n(r));x.useEffect(()=>{let m;return r!==u&&(m=setTimeout(()=>d(r),300)),()=>clearTimeout(m)},[u,r]);const f=x.useCallback(()=>{c.current&&(h.current+=(o-h.current)/2,(h.current>.95*o||o===100)&&(h.current=o),c.current.innerText=s(h.current),h.current<o&&(l.current=requestAnimationFrame(f)))},[s,o]);return x.useEffect(()=>(f(),()=>cancelAnimationFrame(l.current)),[f]),u?x.createElement("div",{style:{...Is.container,opacity:r?1:0,...a}},x.createElement("div",null,x.createElement("div",{style:{...Is.inner,...t}},x.createElement("div",{style:{...Is.bar,transform:`scaleX(${o/100})`,...e}}),x.createElement("span",{ref:c,style:{...Is.data,...i}})))):null}const Is={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"}},Hn=new k,Va=new Kt,ai=new k,Ls=new k,ji=new k,za=new zu,s0=x.forwardRef(({autoTransform:a=!0,matrix:t,axisLock:e,dragLimits:i,onHover:s,onDragStart:n,onDrag:r,onDragEnd:o,children:h,dragConfig:l,...c},u)=>{const d=Q(y=>y.controls),{camera:f,size:m,raycaster:p,invalidate:g}=Q(),E=x.useRef(null),A=fh({onHover:({hovering:y})=>s&&s(y??!1),onDragStart:({event:y})=>{d&&(d.enabled=!1);const{point:T}=y;E.current.matrix.decompose(Hn,new yt,new k),ai.copy(T),Ls.copy(ai).sub(Hn),n&&n(Hn),g()},onDrag:({xy:[y,T],intentional:_})=>{if(!_)return;const C=(y-m.left)/m.width*2-1,S=-((T-m.top)/m.height)*2+1;if(Va.set(C,S),p.setFromCamera(Va,f),!e)f.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}za.setFromNormalAndCoplanarPoint(ji,ai),p.ray.intersectPlane(za,ai);const I=E.current.matrix.clone(),L=E.current.matrixWorld.clone(),b=new k(ai.x-Ls.x,ai.y-Ls.y,ai.z-Ls.z);if(i&&(b.x=i[0]?Math.max(Math.min(b.x,i[0][1]),i[0][0]):b.x,b.y=i[1]?Math.max(Math.min(b.y,i[1][1]),i[1][0]):b.y,b.z=i[2]?Math.max(Math.min(b.z,i[2][1]),i[2][0]):b.z),a){E.current.matrix.setPosition(b);const w=E.current.matrix.clone().multiply(I.invert()),O=E.current.matrix.clone().multiply(L.invert());r&&r(E.current.matrix,w,E.current.matrixWorld,O)}else{const w=new mt().copy(E.current.matrix);w.setPosition(b);const O=w.clone().multiply(I.invert()),H=w.clone().multiply(L.invert());r&&r(w,O,E.current.matrixWorld,H)}g()},onDragEnd:()=>{d&&(d.enabled=!0),o&&o(),g()}},{drag:{filterTaps:!0,threshold:1,...typeof l=="object"?l:{}}});return x.useImperativeHandle(u,()=>E.current,[]),x.useLayoutEffect(()=>{t&&(E.current.matrix=t)},[t]),x.createElement("group",wt({ref:E},A(),{matrix:t,matrixAutoUpdate:!1},c),h)});function us(a,t,e){return t in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Dr(a,t){return Dr=Object.setPrototypeOf||function(i,s){return i.__proto__=s,i},Dr(a,t)}function n0(){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 r0(){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],h=t[5],l=t[6],c=t[7],u=t[8];return i*o*u+s*h*l+n*r*c-n*o*l-s*r*u-i*h*c}function Ya(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 hs().fromArray(e)}function a0(a){if(Array.isArray(a))return a}function o0(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(h){n=!0,o=h}finally{try{!s&&e.return!=null&&e.return()}finally{if(n)throw o}}return i}}function Pr(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 Dh(a,t){if(a){if(typeof a=="string")return Pr(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 Pr(a,t)}}function l0(){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 a0(a)||o0(a,t)||Dh(a,t)||l0()}function h0(a){if(Array.isArray(a))return Pr(a)}function c0(a){if(typeof Symbol<"u"&&a[Symbol.iterator]!=null||a["@@iterator"]!=null)return Array.from(a)}function u0(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function un(a){return h0(a)||c0(a)||Dh(a)||u0()}function Zs(a,t,e){return n0()?Zs=Reflect.construct:Zs=function(s,n,r){var o=[null];o.push.apply(o,n);var h=Function.bind.apply(s,o),l=new h;return r&&Dr(l,r.prototype),l},Zs.apply(null,arguments)}function d0(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),h=o[0],l=o[1];return r0(e,i,1,n,r,1,h,l,1)}function f0(a){return d0(a)===0}var m0=new Kt,p0=new Kt;function Xa(a){var t=a.map(function(l){return Array.isArray(l)?Zs(Kt,un(l)):l}),e=Me(t,3),i=e[0],s=e[1],n=e[2];if(f0(a))return!1;var r=m0.subVectors(s,i),o=p0.subVectors(n,i),h=o.cross(r);return h>0}function Ph(a,t,e){return Math.max(t,Math.min(e,a))}function wh(a,t){return Ph(a-Math.floor(a/t)*t,0,t)}function Mh(a,t){var e=wh(t-a,Math.PI*2);return e>Math.PI&&(e-=Math.PI*2),e}function g0(a){return a/180*Math.PI}function E0(a){return a*180/Math.PI}function y0(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 h=o*n-1+n/2,l=Math.sqrt(1-Math.pow(h,2)),c=o%s*r,u=Math.cos(c)*l,d=Math.sin(c)*l;a[o]=u*i,a[o+1]=h*i,a[o+2]=d*i}}function v0(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 Bh(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 A0(a){for(var t=a.sort(Bh),e=[t[0],t[1]],i=2;i<t.length;i++)for(e.push(t[i]);e.length>2&&Xa(un(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&&Xa(un(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 T0(a,t,e){var i=Me(t,2),s=i[0],n=i[1],r=Me(e,2),o=r[0],h=r[1];return o+(a-s)*(h-o)/(n-s)}function _0(a){return a*a*a*(a*(a*6-15)+10)}function S0(a,t,e){return a*(1-e)+t*e}function Oh(a,t,e){return(e-a)/(t-a)}function x0(a,t,e){var i=Math.sqrt(a*a+t*t+e*e);return[a/i,t/i,e/i]}function C0(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),h=e*Math.sqrt(1-(i+s)/2+i*s/3);return[r,o,h]}function Fh(a,t){var e=new k().crossVectors(a,t),i=a.dot(t),s=new hs().identity(),n=new hs().set(0,-e.z,e.y,e.z,0,-e.x,-e.y,e.x,0),r=new hs().multiplyMatrices(n,n).multiplyScalar(1/(1+i)),o=Ya(Ya(s,n),r);return o}function b0(a,t,e){var i=Math.asin(t),s=Math.atan2(a,-e);return[i,s]}function I0(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=Fh(a.normal,new k(0,1,0)),r=Oh(i.clone().applyMatrix3(n).y,s.clone().applyMatrix3(n).y,0);return new k().lerpVectors(i,s,r)}function R0(a,t){var e=t.normal.dot(a);return e}function D0(a,t){var e=Me(a,3),i=e[0],s=e[1],n=e[2],r=Me(t,2),o=r[0],h=r[1];return n*o*h+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,h=o/i,l=o%i;return[l,h,r]}function w0(a,t){return a[0]+t[0]*a[1]}function M0(a,t){var e=a%t,i=Math.floor(a/t);return[e,i]}var Rs=Object.freeze({__proto__:null,clamp:Ph,repeat:wh,deltaAngle:Mh,degToRad:g0,radToDeg:E0,fibonacciOnSphere:y0,vectorEquals:v0,lexicographic:Bh,convexHull:A0,remap:T0,fade:_0,lerp:S0,inverseLerp:Oh,normalize:x0,pointOnCubeToPointOnSphere:C0,rotateVectorOnVector:Fh,pointToCoordinate:b0,coordinateToPoint:I0,planeSegmentIntersection:L0,pointToPlaneDistance:R0,getIndexFrom3D:D0,get3DFromIndex:P0,getIndexFrom2D:w0,get2DFromIndex:M0});function kh(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;kh(this,a),us(this,"dot2",function(n,r){return s.x*n+s.y*r}),us(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},B0=[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)],ja=[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],Wa=new Array(512),Ja=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=ja[e]^t&255:i=ja[e]^t>>8&255,Wa[e]=Wa[e+256]=i,Ja[e]=Ja[e+256]=B0[i%12]}};O0(0);function F0(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 Qa(a){var t=F0(a);return function(){var e=t*48271%2147483647;return t=e,e/2147483647}}var k0=function a(t){var e=this;kh(this,a),us(this,"seed",0),us(this,"init",function(i){e.seed=i,e.value=Qa(i)}),us(this,"value",Qa(this.seed)),this.init(t)};new k0(Math.random());var U0=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)},Uh=function(t){return 1/(1+t+.48*t*t+.235*t*t*t)},N0=function(t){return t},G0={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}},H0={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}},K0={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}},z0={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 zt(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]:Uh,o=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,h="velocity_"+t;if(a.__damp===void 0&&(a.__damp={}),a.__damp[h]===void 0&&(a.__damp[h]=0),Math.abs(a[t]-e)<=o)return a[t]=e,!1;i=Math.max(1e-4,i);var l=2/i,c=r(l*s),u=a[t]-e,d=e,f=n*i;u=Math.min(Math.max(u,-f),f),e=a[t]-u;var m=(a.__damp[h]+l*u)*s;a.__damp[h]=(a.__damp[h]-l*m)*c;var p=e+(u+m)*c;return d-a[t]>0==p>d&&(p=d,a.__damp[h]=(p-d)/s),a[t]=p,!0}var Y0=function(t){return t&&t.isCamera},X0=function(t){return t&&t.isLight},Wi=new k,qa=new yt,Za=new yt,Ji=new mt,$n=new k;function j0(a,t,e,i,s,n,r){typeof t=="number"?Wi.setScalar(t):Array.isArray(t)?Wi.set(t[0],t[1],t[2]):Wi.copy(t);var o=a.parent;a.updateWorldMatrix(!0,!1),$n.setFromMatrixPosition(a.matrixWorld),Y0(a)||X0(a)?Ji.lookAt($n,Wi,a.up):Ji.lookAt(Wi,$n,a.up),dn(a.quaternion,Za.setFromRotationMatrix(Ji),e,i,s,n,r),o&&(Ji.extractRotation(o.matrixWorld),qa.setFromRotationMatrix(Ji),dn(a.quaternion,Za.copy(a.quaternion).premultiply(qa.invert()),e,i,s,n,r))}function Bi(a,t,e,i,s,n,r,o){return zt(a,t,a[t]+Mh(a[t],e),i,s,n,r,o)}var Qi=new Kt,to,eo;function W0(a,t,e,i,s,n,r){return typeof t=="number"?Qi.setScalar(t):Array.isArray(t)?Qi.set(t[0],t[1]):Qi.copy(t),to=zt(a,"x",Qi.x,e,i,s,n,r),eo=zt(a,"y",Qi.y,e,i,s,n,r),to||eo}var Ei=new k,io,so,no;function wr(a,t,e,i,s,n,r){return typeof t=="number"?Ei.setScalar(t):Array.isArray(t)?Ei.set(t[0],t[1],t[2]):Ei.copy(t),io=zt(a,"x",Ei.x,e,i,s,n,r),so=zt(a,"y",Ei.y,e,i,s,n,r),no=zt(a,"z",Ei.z,e,i,s,n,r),io||so||no}var oi=new ze,ro,ao,oo,lo;function J0(a,t,e,i,s,n,r){return typeof t=="number"?oi.setScalar(t):Array.isArray(t)?oi.set(t[0],t[1],t[2],t[3]):oi.copy(t),ro=zt(a,"x",oi.x,e,i,s,n,r),ao=zt(a,"y",oi.y,e,i,s,n,r),oo=zt(a,"z",oi.z,e,i,s,n,r),lo=zt(a,"w",oi.w,e,i,s,n,r),ro||ao||oo||lo}var qi=new $e,ho,co,uo;function Q0(a,t,e,i,s,n,r){return Array.isArray(t)?qi.set(t[0],t[1],t[2],t[3]):qi.copy(t),ho=Bi(a,"x",qi.x,e,i,s,n,r),co=Bi(a,"y",qi.y,e,i,s,n,r),uo=Bi(a,"z",qi.z,e,i,s,n,r),ho||co||uo}var yi=new kt,fo,mo,po;function q0(a,t,e,i,s,n,r){return t instanceof kt?yi.copy(t):Array.isArray(t)?yi.setRGB(t[0],t[1],t[2]):yi.set(t),fo=zt(a,"r",yi.r,e,i,s,n,r),mo=zt(a,"g",yi.g,e,i,s,n,r),po=zt(a,"b",yi.b,e,i,s,n,r),fo||mo||po}var ye=new yt,Oe=new ze,go=new ze,Zi=new ze,Eo,yo,vo,Ao;function dn(a,t,e,i,s,n,r){var o=a;Array.isArray(t)?ye.set(t[0],t[1],t[2],t[3]):ye.copy(t);var h=a.dot(ye)>0?1:-1;return ye.x*=h,ye.y*=h,ye.z*=h,ye.w*=h,Eo=zt(a,"x",ye.x,e,i,s,n,r),yo=zt(a,"y",ye.y,e,i,s,n,r),vo=zt(a,"z",ye.z,e,i,s,n,r),Ao=zt(a,"w",ye.w,e,i,s,n,r),Oe.set(a.x,a.y,a.z,a.w).normalize(),go.set(o.__damp.velocity_x,o.__damp.velocity_y,o.__damp.velocity_z,o.__damp.velocity_w),Zi.copy(Oe).multiplyScalar(go.dot(Oe)/Oe.dot(Oe)),o.__damp.velocity_x-=Zi.x,o.__damp.velocity_y-=Zi.y,o.__damp.velocity_z-=Zi.z,o.__damp.velocity_w-=Zi.w,a.set(Oe.x,Oe.y,Oe.z,Oe.w),Eo||yo||vo||Ao}var ts=new Zr,To,_o,So;function Z0(a,t,e,i,s,n,r){return Array.isArray(t)?ts.set(t[0],t[1],t[2]):ts.copy(t),To=zt(a,"radius",ts.radius,e,i,s,n,r),_o=Bi(a,"phi",ts.phi,e,i,s,n,r),So=Bi(a,"theta",ts.theta,e,i,s,n,r),To||_o||So}var Ds=new mt,xo=new k,Co=new yt,bo=new k,Io,Lo,Ro;function tE(a,t,e,i,s,n,r){var o=a;return o.__damp===void 0&&(o.__damp={position:new k,rotation:new yt,scale:new k},a.decompose(o.__damp.position,o.__damp.rotation,o.__damp.scale)),Array.isArray(t)?Ds.set.apply(Ds,un(t)):Ds.copy(t),Ds.decompose(xo,Co,bo),Io=wr(o.__damp.position,xo,e,i,s,n,r),Lo=dn(o.__damp.rotation,Co,e,i,s,n,r),Ro=wr(o.__damp.scale,bo,e,i,s,n,r),a.compose(o.__damp.position,o.__damp.rotation,o.__damp.scale),Io||Lo||Ro}var ti=Object.freeze({__proto__:null,rsqw:U0,exp:Uh,linear:N0,sine:G0,cubic:H0,quint:$0,circ:K0,quart:V0,expo:z0,damp:zt,dampLookAt:j0,dampAngle:Bi,damp2:W0,damp3:wr,damp4:J0,dampE:Q0,dampC:q0,dampQ:dn,dampS:Z0,dampM:tE});const ca=x.createContext(null);function ua(){return x.useContext(ca)}function eE({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:h=!1,style:l={},children:c}){const{get:u,setEvents:d,gl:f,size:m,invalidate:p,events:g}=Q(),[E]=x.useState(()=>document.createElement("div")),[A]=x.useState(()=>document.createElement("div")),[y]=x.useState(()=>document.createElement("div")),T=f.domElement.parentNode,_=x.useRef(0),C=x.useMemo(()=>({el:E,eps:a,fill:A,fixed:y,horizontal:i,damping:r,offset:0,delta:0,scroll:_,pages:s,range(L,b,w=0){const O=L-w,H=O+b+w*2;return this.offset<O?0:this.offset>H?1:(this.offset-O)/(H-O)},curve(L,b,w=0){return Math.sin(this.range(L,b,w)*Math.PI)},visible(L,b,w=0){const O=L-w,H=O+b+w*2;return this.offset>=O&&this.offset<=H}}),[a,r,i,s]);x.useEffect(()=>{E.style.position="absolute",E.style.width="100%",E.style.height="100%",E.style[i?"overflowX":"overflowY"]="auto",E.style[i?"overflowY":"overflowX"]="hidden",E.style.top="0px",E.style.left="0px";for(const b in l)E.style[b]=l[b];y.style.position="sticky",y.style.top="0px",y.style.left="0px",y.style.width="100%",y.style.height="100%",y.style.overflow="hidden",E.appendChild(y),A.style.height=i?"100%":`${s*n*100}%`,A.style.width=i?`${s*n*100}%`:"100%",A.style.pointerEvents="none",E.appendChild(A),h?T.prepend(E):T.appendChild(E),E[i?"scrollLeft":"scrollTop"]=1;const I=g.connected||f.domElement;requestAnimationFrame(()=>g.connect==null?void 0:g.connect(E));const L=u().events.compute;return d({compute(b,w){const{left:O,top:H}=T.getBoundingClientRect(),Y=b.clientX-O,$=b.clientY-H;w.pointer.set(Y/w.size.width*2-1,-($/w.size.height)*2+1),w.raycaster.setFromCamera(w.pointer,w.camera)}}),()=>{T.removeChild(E),d({compute:L}),g.connect==null||g.connect(I)}},[s,n,i,E,A,y,T]),x.useEffect(()=>{if(g.connected===E){const I=m[i?"width":"height"],L=E[i?"scrollWidth":"scrollHeight"],b=L-I;let w=0,O=!0,H=!0;const Y=()=>{if(!(!t||H)&&(p(),w=E[i?"scrollLeft":"scrollTop"],_.current=w/b,e)){if(!O){if(w>=b){const z=1-C.offset;E[i?"scrollLeft":"scrollTop"]=1,_.current=C.offset=-z,O=!0}else if(w<=0){const z=1+C.offset;E[i?"scrollLeft":"scrollTop"]=L,_.current=C.offset=z,O=!0}}O&&setTimeout(()=>O=!1,40)}};E.addEventListener("scroll",Y,{passive:!0}),requestAnimationFrame(()=>H=!1);const $=z=>E.scrollLeft+=z.deltaY/2;return i&&E.addEventListener("wheel",$,{passive:!0}),()=>{E.removeEventListener("scroll",Y),i&&E.removeEventListener("wheel",$)}}},[E,g,m,e,C,p,i,t]);let S=0;return Ut((I,L)=>{S=C.offset,ti.damp(C,"offset",_.current,r,L,o,void 0,a),ti.damp(C,"delta",Math.abs(S-C.offset),r,L,o,void 0,a),C.delta>a&&p()}),x.createElement(ca.Provider,{value:C},c)}const iE=x.forwardRef(({children:a},t)=>{const e=x.useRef(null);x.useImperativeHandle(t,()=>e.current,[]);const i=ua(),{width:s,height:n}=Q(r=>r.viewport);return Ut(()=>{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}),x.createElement("group",{ref:e},a)}),sE=x.forwardRef(({children:a,style:t,...e},i)=>{const s=ua(),n=x.useRef(null);x.useImperativeHandle(i,()=>n.current,[]);const{width:r,height:o}=Q(c=>c.size),h=x.useContext(Ga),l=x.useMemo(()=>Wg(s.fixed),[s.fixed]);return Ut(()=>{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)`)}),l.render(x.createElement("div",wt({ref:n,style:{...t,position:"absolute",top:0,left:0,willChange:"transform"}},e),x.createElement(ca.Provider,{value:s},x.createElement(Ga.Provider,{value:h},a)))),null}),nE=x.forwardRef(({html:a,...t},e)=>{const i=a?sE:iE;return x.createElement(i,wt({ref:e},t))});function rE({enabled:a=!0,snap:t,global:e,domElement:i,cursor:s=!0,children:n,speed:r=1,rotation:o=[0,0,0],zoom:h=1,polar:l=[0,Math.PI/2],azimuth:c=[-1/0,1/0],damping:u=.25}){const d=Q(C=>C.events),f=Q(C=>C.gl),m=i||d.connected||f.domElement,{size:p}=Q(),g=x.useMemo(()=>[o[0]+l[0],o[0]+l[1]],[o[0],l[0],l[1]]),E=x.useMemo(()=>[o[1]+c[0],o[1]+c[1]],[o[1],c[0],c[1]]),A=x.useMemo(()=>[ot.clamp(o[0],...g),ot.clamp(o[1],...E),o[2]],[o[0],o[1],o[2],g,E]);x.useEffect(()=>{if(e&&s&&a)return m.style.cursor="grab",f.domElement.style.cursor="",()=>{m.style.cursor="default",f.domElement.style.cursor="default"}},[e,s,m,a]);const[y]=x.useState({scale:1,rotation:A,damping:u}),T=x.useRef(null);Ut((C,S)=>{ti.damp3(T.current.scale,y.scale,y.damping,S),ti.dampE(T.current.rotation,y.rotation,y.damping,S)});const _=fh({onHover:({last:C})=>{s&&!e&&a&&(m.style.cursor=C?"auto":"grab")},onDrag:({down:C,delta:[S,I],memo:[L,b]=y.rotation||A})=>a?(s&&(m.style.cursor=C?"grabbing":"grab"),S=ot.clamp(b+S/p.width*Math.PI*r,...E),I=ot.clamp(L+I/p.height*Math.PI*r,...g),y.scale=C&&I>g[1]/2?h:1,y.rotation=t&&!C?A:[I,S,0],y.damping=t&&!C&&typeof t!="boolean"?t:u,[I,S]):[I,S]},{target:e?m:void 0});return x.createElement("group",wt({ref:T},_==null?void 0:_()),n)}const aE=a=>(t,e,i)=>{const s=i.subscribe;return i.subscribe=(r,o,h)=>{let l=r;if(o){const c=(h==null?void 0:h.equalityFn)||Object.is;let u=r(i.getState());l=d=>{const f=r(d);if(!c(u,f)){const m=u;o(u=f,m)}},h!=null&&h.fireImmediately&&o(u,u)}return s(l)},a(t,e,i)},oE=aE,Nh=x.createContext(null);function lE({map:a,children:t,onChange:e,domElement:i}){const s=a.map(h=>h.name+h.keys).join("-"),n=x.useMemo(()=>dh(oE(()=>a.reduce((h,l)=>({...h,[l.name]:!1}),{}))),[s]),r=x.useMemo(()=>[n.subscribe,n.getState,n],[s]),o=n.setState;return x.useEffect(()=>{const l=a.map(({name:f,keys:m,up:p})=>({keys:m,up:p,fn:g=>{o({[f]:g}),e&&e(f,g,r[1]())}})).reduce((f,{keys:m,fn:p,up:g=!0})=>(m.forEach(E=>f[E]={fn:p,pressed:!1,up:g}),f),{}),c=({key:f,code:m})=>{const p=l[f]||l[m];if(!p)return;const{fn:g,pressed:E,up:A}=p;p.pressed=!0,(A||!E)&&g(!0)},u=({key:f,code:m})=>{const p=l[f]||l[m];if(!p)return;const{fn:g,up:E}=p;p.pressed=!1,E&&g(!1)},d=i||window;return d.addEventListener("keydown",c,{passive:!0}),d.addEventListener("keyup",u,{passive:!0}),()=>{d.removeEventListener("keydown",c),d.removeEventListener("keyup",u)}},[i,s]),x.createElement(Nh.Provider,{value:r,children:t})}function hE(a){const[t,e,i]=x.useContext(Nh);return a?i(a):[t,e]}var cE=Object.defineProperty,uE=(a,t,e)=>t in a?cE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,ct=(a,t,e)=>(uE(a,typeof t!="symbol"?t+"":t,e),e);const Do=new k;let dE=class extends $i{constructor(t,e){super(),ct(this,"object"),ct(this,"domElement"),ct(this,"enabled",!0),ct(this,"movementSpeed",1),ct(this,"lookSpeed",.005),ct(this,"lookVertical",!0),ct(this,"autoForward",!1),ct(this,"activeLook",!0),ct(this,"heightSpeed",!1),ct(this,"heightCoef",1),ct(this,"heightMin",0),ct(this,"heightMax",1),ct(this,"constrainVertical",!1),ct(this,"verticalMin",0),ct(this,"verticalMax",Math.PI),ct(this,"mouseDragOn",!1),ct(this,"autoSpeedFactor",0),ct(this,"mouseX",0),ct(this,"mouseY",0),ct(this,"moveForward",!1),ct(this,"moveBackward",!1),ct(this,"moveLeft",!1),ct(this,"moveRight",!1),ct(this,"moveUp",!1),ct(this,"moveDown",!1),ct(this,"viewHalfX",0),ct(this,"viewHalfY",0),ct(this,"lat",0),ct(this,"lon",0),ct(this,"lookDirection",new k),ct(this,"spherical",new Zr),ct(this,"target",new k),ct(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()}),ct(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)}),ct(this,"handleResize",()=>{this.domElement&&(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}),ct(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}),ct(this,"onMouseUp",i=>{if(this.activeLook)switch(i.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}),ct(this,"onMouseMove",i=>{this.domElement&&(this.mouseX=i.pageX-this.domElement.offsetLeft-this.viewHalfX,this.mouseY=i.pageY-this.domElement.offsetTop-this.viewHalfY)}),ct(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}}),ct(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}}),ct(this,"lookAt",(i,s,n)=>(i instanceof k?this.target.copy(i):s&&n&&this.target.set(i,s,n),this.object.lookAt(this.target),this.setOrientation(),this)),ct(this,"update",i=>{if(!this.enabled)return;if(this.heightSpeed){const u=ot.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=i*(u*this.heightCoef)}else this.autoSpeedFactor=0;const s=i*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(s+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(s),this.moveLeft&&this.object.translateX(-s),this.moveRight&&this.object.translateX(s),this.moveUp&&this.object.translateY(s),this.moveDown&&this.object.translateY(-s);let 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 h=ot.degToRad(this.lon);this.constrainVertical&&(o=ot.mapLinear(o,0,Math.PI,this.verticalMin,this.verticalMax));const l=this.object.position;Do.setFromSphericalCoords(1,o,h).add(l),this.object.lookAt(Do)}),ct(this,"contextmenu",i=>i.preventDefault()),ct(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 fE=Object.defineProperty,mE=(a,t,e)=>t in a?fE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,F=(a,t,e)=>(mE(a,typeof t!="symbol"?t+"":t,e),e);let pE=class extends qt{constructor(t,e){super(),F(this,"isTransformControls",!0),F(this,"visible",!1),F(this,"domElement"),F(this,"raycaster",new xn),F(this,"gizmo"),F(this,"plane"),F(this,"tempVector",new k),F(this,"tempVector2",new k),F(this,"tempQuaternion",new yt),F(this,"unit",{X:new k(1,0,0),Y:new k(0,1,0),Z:new k(0,0,1)}),F(this,"pointStart",new k),F(this,"pointEnd",new k),F(this,"offset",new k),F(this,"rotationAxis",new k),F(this,"startNorm",new k),F(this,"endNorm",new k),F(this,"rotationAngle",0),F(this,"cameraPosition",new k),F(this,"cameraQuaternion",new yt),F(this,"cameraScale",new k),F(this,"parentPosition",new k),F(this,"parentQuaternion",new yt),F(this,"parentQuaternionInv",new yt),F(this,"parentScale",new k),F(this,"worldPositionStart",new k),F(this,"worldQuaternionStart",new yt),F(this,"worldScaleStart",new k),F(this,"worldPosition",new k),F(this,"worldQuaternion",new yt),F(this,"worldQuaternionInv",new yt),F(this,"worldScale",new k),F(this,"eye",new k),F(this,"positionStart",new k),F(this,"quaternionStart",new yt),F(this,"scaleStart",new k),F(this,"camera"),F(this,"object"),F(this,"enabled",!0),F(this,"axis",null),F(this,"mode","translate"),F(this,"translationSnap",null),F(this,"rotationSnap",null),F(this,"scaleSnap",null),F(this,"space","world"),F(this,"size",1),F(this,"dragging",!1),F(this,"showX",!0),F(this,"showY",!0),F(this,"showZ",!0),F(this,"changeEvent",{type:"change"}),F(this,"mouseDownEvent",{type:"mouseDown",mode:this.mode}),F(this,"mouseUpEvent",{type:"mouseUp",mode:this.mode}),F(this,"objectChangeEvent",{type:"objectChange"}),F(this,"intersectObjectWithRay",(s,n,r)=>{const o=n.intersectObject(s,!0);for(let h=0;h<o.length;h++)if(o[h].object.visible||r)return o[h];return!1}),F(this,"attach",s=>(this.object=s,this.visible=!0,this)),F(this,"detach",()=>(this.object=void 0,this.visible=!1,this.axis=null,this)),F(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),F(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()}),F(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}),F(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)}}),F(this,"pointerMove",s=>{const n=this.axis,r=this.mode,o=this.object;let h=this.space;if(r==="scale"?h="local":(n==="E"||n==="XYZE"||n==="XYZ")&&(h="world"),o===void 0||n===null||this.dragging===!1||s.button!==-1)return;this.raycaster.setFromCamera(s,this.camera);const l=this.intersectObjectWithRay(this.plane,this.raycaster,!0);if(l){if(this.pointEnd.copy(l.point).sub(this.worldPositionStart),r==="translate")this.offset.copy(this.pointEnd).sub(this.pointStart),h==="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),h==="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&&(h==="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)),h==="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 c=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(c*=-1),this.tempVector2.set(c,c,c)}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 c=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))*c):(n==="X"||n==="Y"||n==="Z")&&(this.rotationAxis.copy(this.unit[n]),this.tempVector.copy(this.unit[n]),h==="local"&&this.tempVector.applyQuaternion(this.worldQuaternion),this.rotationAngle=this.offset.dot(this.tempVector.cross(this.eye).normalize())*c),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),h==="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)}}),F(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)}),F(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}}}),F(this,"onPointerHover",s=>{if(this.enabled)switch(s.pointerType){case"mouse":case"pen":this.pointerHover(this.getPointer(s));break}}),F(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)))}),F(this,"onPointerMove",s=>{this.enabled&&this.pointerMove(this.getPointer(s))}),F(this,"onPointerUp",s=>{!this.enabled||!this.domElement||(this.domElement.style.touchAction="",this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.pointerUp(this.getPointer(s)))}),F(this,"getMode",()=>this.mode),F(this,"setMode",s=>{this.mode=s}),F(this,"setTranslationSnap",s=>{this.translationSnap=s}),F(this,"setRotationSnap",s=>{this.rotationSnap=s}),F(this,"setScaleSnap",s=>{this.scaleSnap=s}),F(this,"setSize",s=>{this.size=s}),F(this,"setSpace",s=>{this.space=s}),F(this,"update",()=>{console.warn("THREE.TransformControls: update function has no more functionality and therefore has been deprecated.")}),F(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)}),F(this,"dispose",()=>{var s,n,r,o,h,l;(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),(l=(h=this.domElement)==null?void 0:h.ownerDocument)==null||l.removeEventListener("pointerup",this.onPointerUp),this.traverse(c=>{const u=c;u.geometry&&u.geometry.dispose(),u.material&&u.material.dispose()})}),this.domElement=e,this.camera=t,this.gizmo=new gE,this.add(this.gizmo),this.plane=new EE,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 gE extends qt{constructor(){super(),F(this,"isTransformControlsGizmo",!0),F(this,"type","TransformControlsGizmo"),F(this,"tempVector",new k(0,0,0)),F(this,"tempEuler",new $e),F(this,"alignVector",new k(0,1,0)),F(this,"zeroVector",new k(0,0,0)),F(this,"lookAtMatrix",new mt),F(this,"tempQuaternion",new yt),F(this,"tempQuaternion2",new yt),F(this,"identityQuaternion",new yt),F(this,"unitX",new k(1,0,0)),F(this,"unitY",new k(0,1,0)),F(this,"unitZ",new k(0,0,1)),F(this,"gizmo"),F(this,"picker"),F(this,"helper"),F(this,"rotationAxis",new k),F(this,"cameraPosition",new k),F(this,"worldPositionStart",new k),F(this,"worldQuaternionStart",new yt),F(this,"worldPosition",new k),F(this,"worldQuaternion",new yt),F(this,"eye",new k),F(this,"camera",null),F(this,"enabled",!0),F(this,"axis",null),F(this,"mode","translate"),F(this,"space","world"),F(this,"size",1),F(this,"dragging",!1),F(this,"showX",!0),F(this,"showY",!0),F(this,"showZ",!0),F(this,"updateMatrixWorld",()=>{let U=this.space;this.mode==="scale"&&(U="local");const K=U==="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 V=[];V=V.concat(this.picker[this.mode].children),V=V.concat(this.gizmo[this.mode].children),V=V.concat(this.helper[this.mode].children);for(let X=0;X<V.length;X++){const R=V[X];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(K).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(K).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Y"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,0,Math.PI/2)),R.quaternion.copy(K).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(K).dot(this.eye))>.9&&(R.visible=!1)),this.axis==="Z"&&(this.tempQuaternion.setFromEuler(this.tempEuler.set(0,Math.PI/2,0)),R.quaternion.copy(K).multiply(this.tempQuaternion),Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(K).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(K),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(K),this.mode==="translate"||this.mode==="scale"?((R.name==="X"||R.name==="XYZX")&&Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(K).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(K).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(K).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(K).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(K).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(K).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(K).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(K).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(K).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(K),this.alignVector.copy(this.eye).applyQuaternion(this.tempQuaternion.copy(K).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 kt(1,1,1),.5)):this.axis.split("").some(function(it){return R.name===it})?(R.material.opacity=1,R.material.color.lerp(new kt(1,1,1),.5)):(R.material.opacity*=.25,R.material.color.lerp(new kt(1,1,1),.5))):(R.material.opacity*=.5,R.material.color.lerp(new kt(1,1,1),.5))}super.updateMatrixWorld()});const t=new ta({depthTest:!1,depthWrite:!1,transparent:!0,side:_s,fog:!1,toneMapped:!1}),e=new cs({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 h=t.clone();h.opacity=.25;const l=h.clone();l.color.set(16776960);const c=h.clone();c.color.set(65535);const u=h.clone();u.color.set(16711935),t.clone().color.set(16776960);const f=e.clone();f.color.set(16711680);const m=e.clone();m.color.set(65280);const p=e.clone();p.color.set(255);const g=e.clone();g.color.set(65535);const E=e.clone();E.color.set(16711935);const A=e.clone();A.color.set(16776960);const y=e.clone();y.color.set(7895160);const T=A.clone();T.opacity=.25;const _=new Ee(0,.05,.2,12,1,!1),C=new ni(.125,.125,.125),S=new Pe;S.setAttribute("position",new Ge([0,0,0,1,0,0],3));const I=(U,K)=>{const V=new Pe,X=[];for(let R=0;R<=64*K;++R)X.push(0,Math.cos(R/32*Math.PI)*U,Math.sin(R/32*Math.PI)*U);return V.setAttribute("position",new Ge(X,3)),V},L=()=>{const U=new Pe;return U.setAttribute("position",new Ge([0,0,0,1,1,1],3)),U},b={X:[[new nt(_,n),[1,0,0],[0,0,-Math.PI/2],null,"fwd"],[new nt(_,n),[1,0,0],[0,0,Math.PI/2],null,"bwd"],[new Et(S,f)]],Y:[[new nt(_,r),[0,1,0],null,null,"fwd"],[new nt(_,r),[0,1,0],[Math.PI,0,0],null,"bwd"],[new Et(S,m),null,[0,0,Math.PI/2]]],Z:[[new nt(_,o),[0,0,1],[Math.PI/2,0,0],null,"fwd"],[new nt(_,o),[0,0,1],[-Math.PI/2,0,0],null,"bwd"],[new Et(S,p),null,[0,-Math.PI/2,0]]],XYZ:[[new nt(new ri(.1,0),h.clone()),[0,0,0],[0,0,0]]],XY:[[new nt(new ui(.295,.295),l.clone()),[.15,.15,0]],[new Et(S,A),[.18,.3,0],null,[.125,1,1]],[new Et(S,A),[.3,.18,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new nt(new ui(.295,.295),c.clone()),[0,.15,.15],[0,Math.PI/2,0]],[new Et(S,g),[0,.18,.3],[0,0,Math.PI/2],[.125,1,1]],[new Et(S,g),[0,.3,.18],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new nt(new ui(.295,.295),u.clone()),[.15,0,.15],[-Math.PI/2,0,0]],[new Et(S,E),[.18,0,.3],null,[.125,1,1]],[new Et(S,E),[.3,0,.18],[0,-Math.PI/2,0],[.125,1,1]]]},w={X:[[new nt(new Ee(.2,0,1,4,1,!1),i),[.6,0,0],[0,0,-Math.PI/2]]],Y:[[new nt(new Ee(.2,0,1,4,1,!1),i),[0,.6,0]]],Z:[[new nt(new Ee(.2,0,1,4,1,!1),i),[0,0,.6],[Math.PI/2,0,0]]],XYZ:[[new nt(new ri(.2,0),i)]],XY:[[new nt(new ui(.4,.4),i),[.2,.2,0]]],YZ:[[new nt(new ui(.4,.4),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new nt(new ui(.4,.4),i),[.2,0,.2],[-Math.PI/2,0,0]]]},O={START:[[new nt(new ri(.01,2),s),null,null,null,"helper"]],END:[[new nt(new ri(.01,2),s),null,null,null,"helper"]],DELTA:[[new Et(L(),s),null,null,null,"helper"]],X:[[new Et(S,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Et(S,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Et(S,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},H={X:[[new Et(I(1,.5),f)],[new nt(new ri(.04,0),n),[0,0,.99],null,[1,3,1]]],Y:[[new Et(I(1,.5),m),null,[0,0,-Math.PI/2]],[new nt(new ri(.04,0),r),[0,0,.99],null,[3,1,1]]],Z:[[new Et(I(1,.5),p),null,[0,Math.PI/2,0]],[new nt(new ri(.04,0),o),[.99,0,0],null,[1,3,1]]],E:[[new Et(I(1.25,1),T),null,[0,Math.PI/2,0]],[new nt(new Ee(.03,0,.15,4,1,!1),T),[1.17,0,0],[0,0,-Math.PI/2],[1,1,.001]],[new nt(new Ee(.03,0,.15,4,1,!1),T),[-1.17,0,0],[0,0,Math.PI/2],[1,1,.001]],[new nt(new Ee(.03,0,.15,4,1,!1),T),[0,-1.17,0],[Math.PI,0,0],[1,1,.001]],[new nt(new Ee(.03,0,.15,4,1,!1),T),[0,1.17,0],[0,0,0],[1,1,.001]]],XYZE:[[new Et(I(1,1),y),null,[0,Math.PI/2,0]]]},Y={AXIS:[[new Et(S,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},$={X:[[new nt(new bs(1,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new nt(new bs(1,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new nt(new bs(1,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new nt(new bs(1.25,.1,2,24),i)]],XYZE:[[new nt(new mh(.7,10,8),i)]]},z={X:[[new nt(C,n),[.8,0,0],[0,0,-Math.PI/2]],[new Et(S,f),null,null,[.8,1,1]]],Y:[[new nt(C,r),[0,.8,0]],[new Et(S,m),null,[0,0,Math.PI/2],[.8,1,1]]],Z:[[new nt(C,o),[0,0,.8],[Math.PI/2,0,0]],[new Et(S,p),null,[0,-Math.PI/2,0],[.8,1,1]]],XY:[[new nt(C,l),[.85,.85,0],null,[2,2,.2]],[new Et(S,A),[.855,.98,0],null,[.125,1,1]],[new Et(S,A),[.98,.855,0],[0,0,Math.PI/2],[.125,1,1]]],YZ:[[new nt(C,c),[0,.85,.85],null,[.2,2,2]],[new Et(S,g),[0,.855,.98],[0,0,Math.PI/2],[.125,1,1]],[new Et(S,g),[0,.98,.855],[0,-Math.PI/2,0],[.125,1,1]]],XZ:[[new nt(C,u),[.85,0,.85],null,[2,.2,2]],[new Et(S,E),[.855,0,.98],null,[.125,1,1]],[new Et(S,E),[.98,0,.855],[0,-Math.PI/2,0],[.125,1,1]]],XYZX:[[new nt(new ni(.125,.125,.125),h.clone()),[1.1,0,0]]],XYZY:[[new nt(new ni(.125,.125,.125),h.clone()),[0,1.1,0]]],XYZZ:[[new nt(new ni(.125,.125,.125),h.clone()),[0,0,1.1]]]},W={X:[[new nt(new Ee(.2,0,.8,4,1,!1),i),[.5,0,0],[0,0,-Math.PI/2]]],Y:[[new nt(new Ee(.2,0,.8,4,1,!1),i),[0,.5,0]]],Z:[[new nt(new Ee(.2,0,.8,4,1,!1),i),[0,0,.5],[Math.PI/2,0,0]]],XY:[[new nt(C,i),[.85,.85,0],null,[3,3,.2]]],YZ:[[new nt(C,i),[0,.85,.85],null,[.2,3,3]]],XZ:[[new nt(C,i),[.85,0,.85],null,[3,.2,3]]],XYZX:[[new nt(new ni(.2,.2,.2),i),[1.1,0,0]]],XYZY:[[new nt(new ni(.2,.2,.2),i),[0,1.1,0]]],XYZZ:[[new nt(new ni(.2,.2,.2),i),[0,0,1.1]]]},J={X:[[new Et(S,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Et(S,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Et(S,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},G=U=>{const K=new qt;for(let V in U)for(let X=U[V].length;X--;){const R=U[V][X][0].clone(),tt=U[V][X][1],it=U[V][X][2],lt=U[V][X][3],It=U[V][X][4];R.name=V,R.tag=It,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 Wt=R.geometry.clone();Wt.applyMatrix4(R.matrix),R.geometry=Wt,R.renderOrder=1/0,R.position.set(0,0,0),R.rotation.set(0,0,0),R.scale.set(1,1,1),K.add(R)}return K};this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=G(b)),this.add(this.gizmo.rotate=G(H)),this.add(this.gizmo.scale=G(z)),this.add(this.picker.translate=G(w)),this.add(this.picker.rotate=G($)),this.add(this.picker.scale=G(W)),this.add(this.helper.translate=G(O)),this.add(this.helper.rotate=G(Y)),this.add(this.helper.scale=G(J)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}}class EE extends nt{constructor(){super(new ui(1e5,1e5,2,2),new ta({visible:!1,wireframe:!0,side:_s,transparent:!0,opacity:.1,toneMapped:!1})),F(this,"isTransformControlsPlane",!0),F(this,"type","TransformControlsPlane"),F(this,"unitX",new k(1,0,0)),F(this,"unitY",new k(0,1,0)),F(this,"unitZ",new k(0,0,1)),F(this,"tempVector",new k),F(this,"dirVector",new k),F(this,"alignVector",new k),F(this,"tempMatrix",new mt),F(this,"identityQuaternion",new yt),F(this,"cameraQuaternion",new yt),F(this,"worldPosition",new k),F(this,"worldQuaternion",new yt),F(this,"eye",new k),F(this,"axis",null),F(this,"mode","translate"),F(this,"space","world"),F(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 yE=Object.defineProperty,vE=(a,t,e)=>t in a?yE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Nt=(a,t,e)=>(vE(a,typeof t!="symbol"?t+"":t,e),e);const vi=new $e(0,0,0,"YXZ"),Ai=new k,AE={type:"change"},TE={type:"lock"},_E={type:"unlock"},Po=.002,wo=Math.PI/2;let SE=class extends $i{constructor(t,e){super(),Nt(this,"camera"),Nt(this,"domElement"),Nt(this,"isLocked"),Nt(this,"minPolarAngle"),Nt(this,"maxPolarAngle"),Nt(this,"pointerSpeed"),Nt(this,"onMouseMove",i=>{!this.domElement||this.isLocked===!1||(vi.setFromQuaternion(this.camera.quaternion),vi.y-=i.movementX*Po*this.pointerSpeed,vi.x-=i.movementY*Po*this.pointerSpeed,vi.x=Math.max(wo-this.maxPolarAngle,Math.min(wo-this.minPolarAngle,vi.x)),this.camera.quaternion.setFromEuler(vi),this.dispatchEvent(AE))}),Nt(this,"onPointerlockChange",()=>{this.domElement&&(this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(TE),this.isLocked=!0):(this.dispatchEvent(_E),this.isLocked=!1))}),Nt(this,"onPointerlockError",()=>{console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}),Nt(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))}),Nt(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))}),Nt(this,"dispose",()=>{this.disconnect()}),Nt(this,"getObject",()=>this.camera),Nt(this,"direction",new k(0,0,-1)),Nt(this,"getDirection",i=>i.copy(this.direction).applyQuaternion(this.camera.quaternion)),Nt(this,"moveForward",i=>{Ai.setFromMatrixColumn(this.camera.matrix,0),Ai.crossVectors(this.camera.up,Ai),this.camera.position.addScaledVector(Ai,i)}),Nt(this,"moveRight",i=>{Ai.setFromMatrixColumn(this.camera.matrix,0),this.camera.position.addScaledVector(Ai,i)}),Nt(this,"lock",()=>{this.domElement&&this.domElement.requestPointerLock()}),Nt(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 xE=Object.defineProperty,CE=(a,t,e)=>t in a?xE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Gt=(a,t,e)=>(CE(a,typeof t!="symbol"?t+"":t,e),e);let bE=class extends $i{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 k(0,0,1)),Gt(this,"euler",new $e),Gt(this,"q0",new yt),Gt(this,"q1",new yt(-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 yt),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 IE=Object.defineProperty,LE=(a,t,e)=>t in a?IE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,j=(a,t,e)=>(LE(a,typeof t!="symbol"?t+"":t,e),e);let RE=class extends $i{constructor(t,e){super(),j(this,"enabled",!0),j(this,"screen",{left:0,top:0,width:0,height:0}),j(this,"rotateSpeed",1),j(this,"zoomSpeed",1.2),j(this,"panSpeed",.3),j(this,"noRotate",!1),j(this,"noZoom",!1),j(this,"noPan",!1),j(this,"staticMoving",!1),j(this,"dynamicDampingFactor",.2),j(this,"minDistance",0),j(this,"maxDistance",1/0),j(this,"keys",["KeyA","KeyS","KeyD"]),j(this,"mouseButtons",{LEFT:Un.ROTATE,MIDDLE:Un.DOLLY,RIGHT:Un.PAN}),j(this,"object"),j(this,"domElement"),j(this,"cursorZoom",!1),j(this,"target",new k),j(this,"mousePosition",new Kt),j(this,"STATE",{NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4}),j(this,"EPS",1e-6),j(this,"lastZoom",1),j(this,"lastPosition",new k),j(this,"cursorVector",new k),j(this,"targetVector",new k),j(this,"_state",this.STATE.NONE),j(this,"_keyState",this.STATE.NONE),j(this,"_eye",new k),j(this,"_movePrev",new Kt),j(this,"_moveCurr",new Kt),j(this,"_lastAxis",new k),j(this,"_lastAngle",0),j(this,"_zoomStart",new Kt),j(this,"_zoomEnd",new Kt),j(this,"_touchZoomDistanceStart",0),j(this,"_touchZoomDistanceEnd",0),j(this,"_panStart",new Kt),j(this,"_panEnd",new Kt),j(this,"target0"),j(this,"position0"),j(this,"up0"),j(this,"zoom0"),j(this,"changeEvent",{type:"change"}),j(this,"startEvent",{type:"start"}),j(this,"endEvent",{type:"end"}),j(this,"onScreenVector",new Kt),j(this,"getMouseOnScreen",(i,s)=>(this.onScreenVector.set((i-this.screen.left)/this.screen.width,(s-this.screen.top)/this.screen.height),this.onScreenVector)),j(this,"onCircleVector",new Kt),j(this,"getMouseOnCircle",(i,s)=>(this.onCircleVector.set((i-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-s))/this.screen.width),this.onCircleVector)),j(this,"axis",new k),j(this,"quaternion",new yt),j(this,"eyeDirection",new k),j(this,"objectUpDirection",new k),j(this,"objectSidewaysDirection",new k),j(this,"moveDirection",new k),j(this,"angle",0),j(this,"rotateCamera",()=>{this.moveDirection.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0),this.angle=this.moveDirection.length(),this.angle?(this._eye.copy(this.object.position).sub(this.target),this.eyeDirection.copy(this._eye).normalize(),this.objectUpDirection.copy(this.object.up).normalize(),this.objectSidewaysDirection.crossVectors(this.objectUpDirection,this.eyeDirection).normalize(),this.objectUpDirection.setLength(this._moveCurr.y-this._movePrev.y),this.objectSidewaysDirection.setLength(this._moveCurr.x-this._movePrev.x),this.moveDirection.copy(this.objectUpDirection.add(this.objectSidewaysDirection)),this.axis.crossVectors(this.moveDirection,this._eye).normalize(),this.angle*=this.rotateSpeed,this.quaternion.setFromAxisAngle(this.axis,this.angle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion),this._lastAxis.copy(this.axis),this._lastAngle=this.angle):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),this.quaternion.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(this.quaternion),this.object.up.applyQuaternion(this.quaternion)),this._movePrev.copy(this._moveCurr)}),j(this,"zoomCamera",()=>{let i;if(this._state===this.STATE.TOUCH_ZOOM_PAN)i=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(i):this.object.isOrthographicCamera?(this.object.zoom/=i,this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type");else{if(i=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,Math.abs(i-1)>this.EPS&&i>0&&(this.object.isPerspectiveCamera?(i>1&&this._eye.length()>=this.maxDistance-this.EPS&&(i=1),this._eye.multiplyScalar(i)):this.object.isOrthographicCamera?(i>1&&this.object.zoom<this.maxDistance*this.maxDistance&&(i=1),this.object.zoom/=i):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor,this.cursorZoom){this.targetVector.copy(this.target).project(this.object);let s=this.cursorVector.set(this.mousePosition.x,this.mousePosition.y,this.targetVector.z).unproject(this.object);this.target.lerpVectors(s,this.target,i)}this.object.isOrthographicCamera&&this.object.updateProjectionMatrix()}}),j(this,"mouseChange",new Kt),j(this,"objectUp",new k),j(this,"pan",new k),j(this,"panCamera",()=>{if(this.domElement&&(this.mouseChange.copy(this._panEnd).sub(this._panStart),this.mouseChange.lengthSq()>this.EPS)){if(this.object.isOrthographicCamera){const i=this.object,s=(i.right-i.left)/this.object.zoom,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))}}),j(this,"checkDistances",()=>{(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}),j(this,"handleResize",()=>{if(!this.domElement)return;const i=this.domElement.getBoundingClientRect(),s=this.domElement.ownerDocument.documentElement;this.screen.left=i.left+window.pageXOffset-s.clientLeft,this.screen.top=i.top+window.pageYOffset-s.clientTop,this.screen.width=i.width,this.screen.height=i.height}),j(this,"update",()=>{this._eye.subVectors(this.object.position,this.target),this.noRotate||this.rotateCamera(),this.noZoom||this.zoomCamera(),this.noPan||this.panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this.checkDistances(),this.object.lookAt(this.target),this.lastPosition.distanceToSquared(this.object.position)>this.EPS&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this.lastPosition.distanceToSquared(this.object.position)>this.EPS||this.lastZoom!==this.object.zoom)&&(this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type")}),j(this,"reset",()=>{this._state=this.STATE.NONE,this._keyState=this.STATE.NONE,this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.up.copy(this.up0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(this.changeEvent),this.lastPosition.copy(this.object.position),this.lastZoom=this.object.zoom}),j(this,"keydown",i=>{this.enabled!==!1&&(window.removeEventListener("keydown",this.keydown),this._keyState===this.STATE.NONE&&(i.code===this.keys[this.STATE.ROTATE]&&!this.noRotate?this._keyState=this.STATE.ROTATE:i.code===this.keys[this.STATE.ZOOM]&&!this.noZoom?this._keyState=this.STATE.ZOOM:i.code===this.keys[this.STATE.PAN]&&!this.noPan&&(this._keyState=this.STATE.PAN)))}),j(this,"onPointerDown",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseDown(i);break}}),j(this,"onPointerMove",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseMove(i);break}}),j(this,"onPointerUp",i=>{if(this.enabled!==!1)switch(i.pointerType){case"mouse":case"pen":this.onMouseUp();break}}),j(this,"keyup",()=>{this.enabled!==!1&&(this._keyState=this.STATE.NONE,window.addEventListener("keydown",this.keydown))}),j(this,"onMouseDown",i=>{if(!this.domElement)return;if(this._state===this.STATE.NONE)switch(i.button){case this.mouseButtons.LEFT:this._state=this.STATE.ROTATE;break;case this.mouseButtons.MIDDLE:this._state=this.STATE.ZOOM;break;case this.mouseButtons.RIGHT:this._state=this.STATE.PAN;break}const s=this._keyState!==this.STATE.NONE?this._keyState:this._state;s===this.STATE.ROTATE&&!this.noRotate?(this._moveCurr.copy(this.getMouseOnCircle(i.pageX,i.pageY)),this._movePrev.copy(this._moveCurr)):s===this.STATE.ZOOM&&!this.noZoom?(this._zoomStart.copy(this.getMouseOnScreen(i.pageX,i.pageY)),this._zoomEnd.copy(this._zoomStart)):s===this.STATE.PAN&&!this.noPan&&(this._panStart.copy(this.getMouseOnScreen(i.pageX,i.pageY)),this._panEnd.copy(this._panStart)),this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.startEvent)}),j(this,"onMouseMove",i=>{if(this.enabled===!1)return;const s=this._keyState!==this.STATE.NONE?this._keyState:this._state;s===this.STATE.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(i.pageX,i.pageY))):s===this.STATE.ZOOM&&!this.noZoom?this._zoomEnd.copy(this.getMouseOnScreen(i.pageX,i.pageY)):s===this.STATE.PAN&&!this.noPan&&this._panEnd.copy(this.getMouseOnScreen(i.pageX,i.pageY))}),j(this,"onMouseUp",()=>{this.domElement&&this.enabled!==!1&&(this._state=this.STATE.NONE,this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),this.dispatchEvent(this.endEvent))}),j(this,"mousewheel",i=>{if(this.enabled!==!1&&this.noZoom!==!0){switch(i.preventDefault(),i.deltaMode){case 2:this._zoomStart.y-=i.deltaY*.025;break;case 1:this._zoomStart.y-=i.deltaY*.01;break;default:this._zoomStart.y-=i.deltaY*25e-5;break}this.mousePosition.x=i.offsetX/this.screen.width*2-1,this.mousePosition.y=-(i.offsetY/this.screen.height)*2+1,this.dispatchEvent(this.startEvent),this.dispatchEvent(this.endEvent)}}),j(this,"touchstart",i=>{if(this.enabled!==!1){switch(i.preventDefault(),i.touches.length){case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this._state=this.STATE.TOUCH_ZOOM_PAN;const s=i.touches[0].pageX-i.touches[1].pageX,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)}}),j(this,"touchmove",i=>{if(this.enabled!==!1)switch(i.preventDefault(),i.touches.length){case 1:this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY));break;default:const s=i.touches[0].pageX-i.touches[1].pageX,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}}),j(this,"touchend",i=>{if(this.enabled!==!1){switch(i.touches.length){case 0:this._state=this.STATE.NONE;break;case 1:this._state=this.STATE.TOUCH_ROTATE,this._moveCurr.copy(this.getMouseOnCircle(i.touches[0].pageX,i.touches[0].pageY)),this._movePrev.copy(this._moveCurr);break}this.dispatchEvent(this.endEvent)}}),j(this,"contextmenu",i=>{this.enabled!==!1&&i.preventDefault()}),j(this,"connect",i=>{i===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.domElement=i,this.domElement.addEventListener("contextmenu",this.contextmenu),this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("wheel",this.mousewheel),this.domElement.addEventListener("touchstart",this.touchstart),this.domElement.addEventListener("touchend",this.touchend),this.domElement.addEventListener("touchmove",this.touchmove),this.domElement.ownerDocument.addEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.keydown),window.addEventListener("keyup",this.keyup),this.handleResize()}),j(this,"dispose",()=>{this.domElement&&(this.domElement.removeEventListener("contextmenu",this.contextmenu),this.domElement.removeEventListener("pointerdown",this.onPointerDown),this.domElement.removeEventListener("wheel",this.mousewheel),this.domElement.removeEventListener("touchstart",this.touchstart),this.domElement.removeEventListener("touchend",this.touchend),this.domElement.removeEventListener("touchmove",this.touchmove),this.domElement.ownerDocument.removeEventListener("pointermove",this.onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.keydown),window.removeEventListener("keyup",this.keyup))}),this.object=t,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.up0=this.object.up.clone(),this.zoom0=this.object.zoom,e!==void 0&&this.connect(e),this.update()}};var DE=Object.defineProperty,PE=(a,t,e)=>t in a?DE(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,M=(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()},Ct={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()},ut={x:0,y:0},se={camera:new mt,gizmos:new mt},Pt={type:"change"},ve={type:"start"},he={type:"end"};let wE=class extends $i{constructor(t,e=null,i=null){super(),M(this,"camera"),M(this,"domElement"),M(this,"scene"),M(this,"mouseActions"),M(this,"_mouseOp"),M(this,"_v2_1"),M(this,"_v3_1"),M(this,"_v3_2"),M(this,"_m4_1"),M(this,"_m4_2"),M(this,"_quat"),M(this,"_translationMatrix"),M(this,"_rotationMatrix"),M(this,"_scaleMatrix"),M(this,"_rotationAxis"),M(this,"_cameraMatrixState"),M(this,"_cameraProjectionState"),M(this,"_fovState"),M(this,"_upState"),M(this,"_zoomState"),M(this,"_nearPos"),M(this,"_farPos"),M(this,"_gizmoMatrixState"),M(this,"_up0"),M(this,"_zoom0"),M(this,"_fov0"),M(this,"_initialNear"),M(this,"_nearPos0"),M(this,"_initialFar"),M(this,"_farPos0"),M(this,"_cameraMatrixState0"),M(this,"_gizmoMatrixState0"),M(this,"_button"),M(this,"_touchStart"),M(this,"_touchCurrent"),M(this,"_input"),M(this,"_switchSensibility"),M(this,"_startFingerDistance"),M(this,"_currentFingerDistance"),M(this,"_startFingerRotation"),M(this,"_currentFingerRotation"),M(this,"_devPxRatio"),M(this,"_downValid"),M(this,"_nclicks"),M(this,"_downEvents"),M(this,"_clickStart"),M(this,"_maxDownTime"),M(this,"_maxInterval"),M(this,"_posThreshold"),M(this,"_movementThreshold"),M(this,"_currentCursorPosition"),M(this,"_startCursorPosition"),M(this,"_grid"),M(this,"_gridPosition"),M(this,"_gizmos"),M(this,"_curvePts"),M(this,"_timeStart"),M(this,"_animationId"),M(this,"focusAnimationTime"),M(this,"_timePrev"),M(this,"_timeCurrent"),M(this,"_anglePrev"),M(this,"_angleCurrent"),M(this,"_cursorPosPrev"),M(this,"_cursorPosCurr"),M(this,"_wPrev"),M(this,"_wCurr"),M(this,"adjustNearFar"),M(this,"scaleFactor"),M(this,"dampingFactor"),M(this,"wMax"),M(this,"enableAnimations"),M(this,"enableGrid"),M(this,"cursorZoom"),M(this,"minFov"),M(this,"maxFov"),M(this,"enabled"),M(this,"enablePan"),M(this,"enableRotate"),M(this,"enableZoom"),M(this,"minDistance"),M(this,"maxDistance"),M(this,"minZoom"),M(this,"maxZoom"),M(this,"target"),M(this,"_currentTarget"),M(this,"_tbRadius"),M(this,"_state"),M(this,"onWindowResize",()=>{const s=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3;if(this.camera){const l=this.calculateTbRadius(this.camera);l!==void 0&&(this._tbRadius=l)}const n=this._tbRadius/s,o=new Nn(0,0,n,n).getPoints(this._curvePts),h=new Pe().setFromPoints(o);for(const l in this._gizmos.children){const c=this._gizmos.children[l];c.geometry=h}this.dispatchEvent(Pt)}),M(this,"onContextMenu",s=>{if(this.enabled){for(let n=0;n<this.mouseActions.length;n++)if(this.mouseActions[n].mouse==2){s.preventDefault();break}}}),M(this,"onPointerCancel",()=>{this._touchStart.splice(0,this._touchStart.length),this._touchCurrent.splice(0,this._touchCurrent.length),this._input=Ct.NONE}),M(this,"onPointerDown",s=>{if(s.button==0&&s.isPrimary?(this._downValid=!0,this._downEvents.push(s)):this._downValid=!1,s.pointerType=="touch"&&this._input!=Ct.CURSOR)switch(this._touchStart.push(s),this._touchCurrent.push(s),this._input){case Ct.NONE:this._input=Ct.ONE_FINGER,this.onSinglePanStart(s,"ROTATE"),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp);break;case Ct.ONE_FINGER:case Ct.ONE_FINGER_SWITCHED:this._input=Ct.TWO_FINGER,this.onRotateStart(),this.onPinchStart(),this.onDoublePanStart();break;case Ct.TWO_FINGER:this._input=Ct.MULT_FINGER,this.onTriplePanStart();break}else if(s.pointerType!="touch"&&this._input==Ct.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=Ct.CURSOR,this._button=s.button,this.onSinglePanStart(s,this._mouseOp))}}),M(this,"onPointerMove",s=>{if(s.pointerType=="touch"&&this._input!=Ct.CURSOR)switch(this._input){case Ct.ONE_FINGER:this.updateTouchEvent(s),this.onSinglePanMove(s,st.ROTATE);break;case Ct.ONE_FINGER_SWITCHED:if(this.calculatePointersDistance(this._touchCurrent[0],s)*this._devPxRatio>=this._switchSensibility){this._input=Ct.ONE_FINGER,this.updateTouchEvent(s),this.onSinglePanStart(s,"ROTATE");break}break;case Ct.TWO_FINGER:this.updateTouchEvent(s),this.onRotateMove(),this.onPinchMove(),this.onDoublePanMove();break;case Ct.MULT_FINGER:this.updateTouchEvent(s),this.onTriplePanMove();break}else if(s.pointerType!="touch"&&this._input==Ct.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)}),M(this,"onPointerUp",s=>{if(s.pointerType=="touch"&&this._input!=Ct.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 Ct.ONE_FINGER:case Ct.ONE_FINGER_SWITCHED:window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Ct.NONE,this.onSinglePanEnd();break;case Ct.TWO_FINGER:this.onDoublePanEnd(),this.onPinchEnd(),this.onRotateEnd(),this._input=Ct.ONE_FINGER_SWITCHED;break;case Ct.MULT_FINGER:this._touchCurrent.length==0&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Ct.NONE,this.onTriplePanEnd());break}}else s.pointerType!="touch"&&this._input==Ct.CURSOR&&(window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),this._input=Ct.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)}),M(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 h=this.getOpFromAction("WHEEL",o);if(h){s.preventDefault(),this.dispatchEvent(ve);const l=125;let c=s.deltaY/l,u=1;switch(c>0?u=1/this.scaleFactor:c<0&&(u=this.scaleFactor),h){case"ZOOM":if(this.updateTbState(st.SCALE,!0),c>0?u=1/Math.pow(this.scaleFactor,c):c<0&&(u=Math.pow(this.scaleFactor,-c)),this.cursorZoom&&this.enablePan){let d;this.camera instanceof ne&&(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 Ht&&(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(u,d))}else this.applyTransformMatrix(this.applyScale(u,this._gizmos.position));this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(st.IDLE,!1),this.dispatchEvent(Pt),this.dispatchEvent(he);break;case"FOV":if(this.camera instanceof Ht){this.updateTbState(st.FOV,!0),s.deltaX!=0&&(c=s.deltaX/l,u=1,c>0?u=1/Math.pow(this.scaleFactor,c):c<0&&(u=Math.pow(this.scaleFactor,-c))),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const d=this._v3_1.distanceTo(this._gizmos.position);let f=d/u;f=ot.clamp(f,this.minDistance,this.maxDistance);const m=d*Math.tan(ot.DEG2RAD*this.camera.fov*.5);let p=ot.RAD2DEG*(Math.atan(m/f)*2);p>this.maxFov?p=this.maxFov:p<this.minFov&&(p=this.minFov);const g=m/Math.tan(ot.DEG2RAD*(p/2));u=d/g,this.setFov(p),this.applyTransformMatrix(this.applyScale(u,this._gizmos.position,!1))}this._grid&&(this.disposeGrid(),this.drawGrid()),this.updateTbState(st.IDLE,!1),this.dispatchEvent(Pt),this.dispatchEvent(he);break}}}}),M(this,"onSinglePanStart",(s,n)=>{if(this.enabled&&this.domElement)switch(this.dispatchEvent(ve),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(Pt)),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(Pt))}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(Pt);break;case"FOV":if(!this.enableZoom)return;this.camera instanceof Ht&&(this._animationId!=-1&&(cancelAnimationFrame(this._animationId),this._animationId=-1,this._timeStart=-1,this.activateGizmos(!1),this.dispatchEvent(Pt)),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(Pt)),this.updateTbState(st.SCALE,!0),this._startCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5),this._currentCursorPosition.copy(this._startCursorPosition);break}}),M(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(ve),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(ve),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 h=this._startCursorPosition.distanceTo(this._currentCursorPosition),l=this._startCursorPosition.angleTo(this._currentCursorPosition),c=Math.max(h/this._tbRadius,l);this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition,this._currentCursorPosition),c)),this.enableAnimations&&(this._timePrev=this._timeCurrent,this._timeCurrent=performance.now(),this._anglePrev=this._angleCurrent,this._angleCurrent=c,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(ve),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 h=this._currentCursorPosition.y-this._startCursorPosition.y;let l=1;h<0?l=1/Math.pow(this.scaleFactor,-h*8):h>0&&(l=Math.pow(this.scaleFactor,h*8)),this.applyTransformMatrix(this.applyScale(l,this._gizmos.position))}break;case st.FOV:if(this.enableZoom&&this.camera instanceof Ht)if(r)this.dispatchEvent(he),this.dispatchEvent(ve),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 h=this._currentCursorPosition.y-this._startCursorPosition.y;let l=1;h<0?l=1/Math.pow(this.scaleFactor,-h*8):h>0&&(l=Math.pow(this.scaleFactor,h*8)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const c=this._v3_1.distanceTo(this._gizmos.position);let u=c/l;u=ot.clamp(u,this.minDistance,this.maxDistance);const d=c*Math.tan(ot.DEG2RAD*this._fovState*.5);let f=ot.RAD2DEG*(Math.atan(d/u)*2);f=ot.clamp(f,this.minFov,this.maxFov);const m=d/Math.tan(ot.DEG2RAD*(f/2));l=c/m,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(f),this.applyTransformMatrix(this.applyScale(l,this._v3_2,!1));const p=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(m/c);this._m4_1.makeTranslation(p.x,p.y,p.z)}break}this.dispatchEvent(Pt)}}),M(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 h=r.calculateRotationAxis(r._cursorPosPrev,r._cursorPosCurr);r.onRotationAnim(o,h,Math.min(n,r.wMax))})}else this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Pt);else this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Pt)}else(this._state==st.PAN||this._state==st.IDLE)&&(this.updateTbState(st.IDLE,!1),this.enableGrid&&this.disposeGrid(),this.activateGizmos(!1),this.dispatchEvent(Pt));this.dispatchEvent(he)}),M(this,"onDoubleTap",s=>{if(this.enabled&&this.enablePan&&this.scene&&this.camera&&this.domElement){this.dispatchEvent(ve),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(Pt))}this.dispatchEvent(he)}),M(this,"onDoublePanStart",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.dispatchEvent(ve),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)}}),M(this,"onDoublePanMove",()=>{if(this.enabled&&this.enablePan&&this.camera&&this.domElement){this.setCenter((this._touchCurrent[0].clientX+this._touchCurrent[1].clientX)/2,(this._touchCurrent[0].clientY+this._touchCurrent[1].clientY)/2),this._state!=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(Pt)}}),M(this,"onDoublePanEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),M(this,"onRotateStart",()=>{var s;this.enabled&&this.enableRotate&&(this.dispatchEvent(ve),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))}),M(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 k().setFromMatrixPosition(this._gizmoMatrixState);const r=ot.DEG2RAD*(this._startFingerRotation-this._currentFingerRotation);n!==void 0&&this.applyTransformMatrix(this.zRotate(n,r)),this.dispatchEvent(Pt)}}),M(this,"onRotateEnd",()=>{this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(he)}),M(this,"onPinchStart",()=>{this.enabled&&this.enableZoom&&(this.dispatchEvent(ve),this.updateTbState(st.SCALE,!0),this._startFingerDistance=this.calculatePointersDistance(this._touchCurrent[0],this._touchCurrent[1]),this._currentFingerDistance=this._startFingerDistance,this.activateGizmos(!1))}),M(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 h;this.enablePan?this.camera instanceof ne?h=(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 Ht&&(h=(n=this.unprojectOnTbPlane(this.camera,ut.x,ut.y,this.domElement))==null?void 0:n.applyQuaternion(this.camera.quaternion).add(this._gizmos.position)):h=this._gizmos.position,h!==void 0&&this.applyTransformMatrix(this.applyScale(o,h)),this.dispatchEvent(Pt)}}),M(this,"onPinchEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),M(this,"onTriplePanStart",()=>{if(this.enabled&&this.enableZoom&&this.domElement){this.dispatchEvent(ve),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)}}),M(this,"onTriplePanMove",()=>{if(this.enabled&&this.enableZoom&&this.camera&&this.domElement){let s=0,n=0;const r=this._touchCurrent.length;for(let g=0;g<r;g++)s+=this._touchCurrent[g].clientX,n+=this._touchCurrent[g].clientY;this.setCenter(s/r,n/r);const o=8;this._currentCursorPosition.setY(this.getCursorNDC(ut.x,ut.y,this.domElement).y*.5);const h=this._currentCursorPosition.y-this._startCursorPosition.y;let l=1;h<0?l=1/Math.pow(this.scaleFactor,-h*o):h>0&&(l=Math.pow(this.scaleFactor,h*o)),this._v3_1.setFromMatrixPosition(this._cameraMatrixState);const c=this._v3_1.distanceTo(this._gizmos.position);let u=c/l;u=ot.clamp(u,this.minDistance,this.maxDistance);const d=c*Math.tan(ot.DEG2RAD*this._fovState*.5);let f=ot.RAD2DEG*(Math.atan(d/u)*2);f=ot.clamp(f,this.minFov,this.maxFov);const m=d/Math.tan(ot.DEG2RAD*(f/2));l=c/m,this._v3_2.setFromMatrixPosition(this._gizmoMatrixState),this.setFov(f),this.applyTransformMatrix(this.applyScale(l,this._v3_2,!1));const p=this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(m/c);this._m4_1.makeTranslation(p.x,p.y,p.z),this.dispatchEvent(Pt)}}),M(this,"onTriplePanEnd",()=>{this.updateTbState(st.IDLE,!1),this.dispatchEvent(he)}),M(this,"setCenter",(s,n)=>{ut.x=s,ut.y=n}),M(this,"initializeMouseActions",()=>{this.setMouseAction("PAN",0,"CTRL"),this.setMouseAction("PAN",2),this.setMouseAction("ROTATE",0),this.setMouseAction("ZOOM","WHEEL"),this.setMouseAction("ZOOM",1),this.setMouseAction("FOV","WHEEL","SHIFT"),this.setMouseAction("FOV",1,"SHIFT")}),M(this,"setMouseAction",(s,n,r=null)=>{const o=["PAN","ROTATE","ZOOM","FOV"],h=[0,1,2,"WHEEL"],l=["CTRL","SHIFT",null];let c;if(!o.includes(s)||!h.includes(n)||!l.includes(r)||n=="WHEEL"&&s!="ZOOM"&&s!="FOV")return!1;switch(s){case"PAN":c=st.PAN;break;case"ROTATE":c=st.ROTATE;break;case"ZOOM":c=st.SCALE;break;case"FOV":c=st.FOV;break}const u={operation:s,mouse:n,key:r,state:c};for(let d=0;d<this.mouseActions.length;d++)if(this.mouseActions[d].mouse==u.mouse&&this.mouseActions[d].key==u.key)return this.mouseActions.splice(d,1,u),!0;return this.mouseActions.push(u),!0}),M(this,"getOpFromAction",(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}),M(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}),M(this,"getAngle",(s,n)=>Math.atan2(n.clientY-s.clientY,n.clientX-s.clientX)*180/Math.PI),M(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}}),M(this,"calculateAngularSpeed",(s,n,r,o)=>{const h=n-s,l=(o-r)/1e3;return l==0?0:h/l}),M(this,"calculatePointersDistance",(s,n)=>Math.sqrt(Math.pow(n.clientX-s.clientX,2)+Math.pow(n.clientY-s.clientY,2))),M(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())),M(this,"calculateTbRadius",s=>{const r=s.position.distanceTo(this._gizmos.position);if(s instanceof Ht){const o=ot.DEG2RAD*s.fov*.5,h=Math.atan(s.aspect*Math.tan(o));return Math.tan(Math.min(o,h))*r*.67}else if(s instanceof ne)return Math.min(s.top,s.right)*.67}),M(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 h=this._gizmoMatrixState.clone();this._gizmoMatrixState.premultiply(this._translationMatrix),this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale);const l=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(h),this._cameraMatrixState.copy(l)}}),M(this,"drawGrid",()=>{if(this.scene){let r,o,h,l;if(this.camera instanceof ne){const c=this.camera.right-this.camera.left,u=this.camera.bottom-this.camera.top;h=Math.max(c,u),l=h/20,r=h/this.camera.zoom*3,o=r/l*this.camera.zoom}else if(this.camera instanceof Ht){const c=this.camera.position.distanceTo(this._gizmos.position),u=ot.DEG2RAD*this.camera.fov*.5,d=Math.atan(this.camera.aspect*Math.tan(u));h=Math.tan(Math.max(u,d))*c*2,l=h/20,r=h*3,o=r/l}this._grid==null&&this.camera&&(this._grid=new Yu(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))}}),M(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)}),M(this,"dispose",()=>{var s,n,r,o,h;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),(h=this.scene)==null||h.remove(this._gizmos),this.disposeGrid()}),M(this,"disposeGrid",()=>{this._grid&&this.scene&&(this.scene.remove(this._grid),this._grid=null)}),M(this,"easeOutCubic",s=>1-Math.pow(1-s,3)),M(this,"activateGizmos",s=>{for(const n of this._gizmos.children)n.material.setValues({opacity:s?1:.6})}),M(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()}),M(this,"getCursorPosition",(s,n,r)=>(this._v2_1.copy(this.getCursorNDC(s,n,r)),this.camera instanceof ne&&(this._v2_1.x*=(this.camera.right-this.camera.left)*.5,this._v2_1.y*=(this.camera.top-this.camera.bottom)*.5),this._v2_1.clone())),M(this,"setCamera",s=>{if(s){s.lookAt(this.target),s.updateMatrix(),s instanceof Ht&&(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)}}),M(this,"makeGizmos",(s,n)=>{const o=new Nn(0,0,n,n).getPoints(this._curvePts),h=new Pe().setFromPoints(o),l=new cs({color:16744576,fog:!1,transparent:!0,opacity:.6}),c=new cs({color:8454016,fog:!1,transparent:!0,opacity:.6}),u=new cs({color:8421631,fog:!1,transparent:!0,opacity:.6}),d=new Et(h,l),f=new Et(h,c),m=new Et(h,u),p=Math.PI*.5;if(d.rotation.x=p,f.rotation.y=p,this._gizmoMatrixState0.identity().setPosition(s),this._gizmoMatrixState.copy(this._gizmoMatrixState0),this.camera&&this.camera.zoom!=1){const g=1/this.camera.zoom;this._scaleMatrix.makeScale(g,g,g),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(f),this._gizmos.add(m)}),M(this,"onFocusAnim",(s,n,r,o)=>{if(this._timeStart==-1&&(this._timeStart=s),this._state==st.ANIMATION_FOCUS){const l=(s-this._timeStart)/this.focusAnimationTime;if(this._gizmoMatrixState.copy(o),l>=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(Pt);else{const c=this.easeOutCubic(l),u=1-c+this.scaleFactor*c;this._gizmoMatrixState.decompose(this._gizmos.position,this._gizmos.quaternion,this._gizmos.scale),this.focus(n,u,c),this.dispatchEvent(Pt);const d=this;this._animationId=window.requestAnimationFrame(function(f){d.onFocusAnim(f,n,r,o.clone())})}}else this._animationId=-1,this._timeStart=-1}),M(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(Pt);const l=this;this._animationId=window.requestAnimationFrame(function(c){l.onRotationAnim(c,n,r)})}else this._animationId=-1,this._timeStart=-1,this.updateTbState(st.IDLE,!1),this.activateGizmos(!1),this.dispatchEvent(Pt)}else this._animationId=-1,this._timeStart=-1,this._state!=st.ROTATE&&(this.activateGizmos(!1),this.dispatchEvent(Pt))}),M(this,"pan",(s,n,r=!1)=>{if(this.camera){const o=s.clone().sub(n);if(this.camera instanceof ne&&o.multiplyScalar(1/this.camera.zoom),this.camera instanceof Ht&&r){this._v3_1.setFromMatrixPosition(this._cameraMatrixState0),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0);const h=this._v3_1.distanceTo(this._v3_2)/this.camera.position.distanceTo(this._gizmos.position);o.multiplyScalar(1/h)}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 se}),M(this,"reset",()=>{if(this.camera){this.camera.zoom=this._zoom0,this.camera instanceof Ht&&(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(Pt)}}),M(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),se}),M(this,"copyState",()=>{if(this.camera){const s=JSON.stringify(this.camera instanceof ne?{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)}}),M(this,"pasteState",()=>{const s=this;navigator.clipboard.readText().then(function(r){s.setStateFromJSON(r)})}),M(this,"saveState",()=>{this.camera&&(this._cameraMatrixState0.copy(this.camera.matrix),this._gizmoMatrixState0.copy(this._gizmos.matrix),this._nearPos=this.camera.near,this._farPos=this.camera.far,this._zoom0=this.camera.zoom,this._up0.copy(this.camera.up),this.camera instanceof Ht&&(this._fov0=this.camera.fov))}),M(this,"applyScale",(s,n,r=!0)=>{if(!this.camera)return;const o=n.clone();let h=1/s;if(this.camera instanceof ne){this.camera.zoom=this._zoomState,this.camera.zoom*=s,this.camera.zoom>this.maxZoom?(this.camera.zoom=this.maxZoom,h=this._zoomState/this.maxZoom):this.camera.zoom<this.minZoom&&(this.camera.zoom=this.minZoom,h=this._zoomState/this.minZoom),this.camera.updateProjectionMatrix(),this._v3_1.setFromMatrixPosition(this._gizmoMatrixState),this._scaleMatrix.makeScale(h,h,h),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 l=o.clone().multiplyScalar(h);return o.sub(l),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),se}if(this.camera instanceof Ht){this._v3_1.setFromMatrixPosition(this._cameraMatrixState),this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);let l=this._v3_1.distanceTo(o),c=l-l*h;const u=l-c;u<this.minDistance?(h=this.minDistance/l,c=l-l*h):u>this.maxDistance&&(h=this.maxDistance/l,c=l-l*h);let d=o.clone().sub(this._v3_1).normalize().multiplyScalar(c);if(this._m4_1.makeTranslation(d.x,d.y,d.z),r){const f=this._v3_2;l=f.distanceTo(o),c=l-l*h,d=o.clone().sub(this._v3_2).normalize().multiplyScalar(c),this._translationMatrix.makeTranslation(f.x,f.y,f.z),this._scaleMatrix.makeScale(h,h,h),this._m4_2.makeTranslation(d.x,d.y,d.z).multiply(this._translationMatrix),this._m4_2.multiply(this._scaleMatrix),this._translationMatrix.makeTranslation(-f.x,-f.y,-f.z),this._m4_2.multiply(this._translationMatrix),this.setTransformationMatrices(this._m4_1,this._m4_2)}else this.setTransformationMatrices(this._m4_1);return se}}),M(this,"setFov",s=>{this.camera instanceof Ht&&(this.camera.fov=ot.clamp(s,this.minFov,this.maxFov),this.camera.updateProjectionMatrix())}),M(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)}}),M(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),se)),M(this,"unprojectOnObj",(s,n)=>{if(!this.scene)return null;const r=new xn;r.near=n.near,r.far=n.far,r.setFromCamera(s,n);const o=r.intersectObjects(this.scene.children,!0);for(let h=0;h<o.length;h++)if(o[h].object.uuid!=this._gizmos.uuid&&o[h].face)return o[h].point.clone();return null}),M(this,"unprojectOnTbSurface",(s,n,r,o,h)=>{if(s instanceof ne){this._v2_1.copy(this.getCursorPosition(n,r,o)),this._v3_1.set(this._v2_1.x,this._v2_1.y,0);const l=Math.pow(this._v2_1.x,2),c=Math.pow(this._v2_1.y,2),u=Math.pow(this._tbRadius,2);return l+c<=u*.5?this._v3_1.setZ(Math.sqrt(u-(l+c))):this._v3_1.setZ(u*.5/Math.sqrt(l+c)),this._v3_1}if(s instanceof Ht){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 l=this._v3_1.clone().normalize(),c=s.position.distanceTo(this._gizmos.position),u=Math.pow(h,2),d=this._v3_1.z,f=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));if(f==0)return l.set(this._v3_1.x,this._v3_1.y,h),l;const m=d/f,p=c;let g=Math.pow(m,2)+1,E=2*m*p,A=Math.pow(p,2)-u,y=Math.pow(E,2)-4*g*A;if(y>=0&&(this._v2_1.setX((-E-Math.sqrt(y))/(2*g)),this._v2_1.setY(m*this._v2_1.x+p),ot.RAD2DEG*this._v2_1.angle()>=45)){const C=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(c-this._v2_1.y,2));return l.multiplyScalar(C),l.z+=c,l}g=m,E=p,A=-u*.5,y=Math.pow(E,2)-4*g*A,this._v2_1.setX((-E-Math.sqrt(y))/(2*g)),this._v2_1.setY(m*this._v2_1.x+p);const T=Math.sqrt(Math.pow(this._v2_1.x,2)+Math.pow(c-this._v2_1.y,2));return l.multiplyScalar(T),l.z+=c,l}}),M(this,"unprojectOnTbPlane",(s,n,r,o,h=!1)=>{if(s instanceof ne)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 Ht){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 l=this._v3_1.clone().normalize(),c=this._v3_1.z,u=Math.sqrt(Math.pow(this._v3_1.x,2)+Math.pow(this._v3_1.y,2));let d;if(h?d=this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)):d=s.position.distanceTo(this._gizmos.position),u==0)return l.set(0,0,0),l;const f=c/u,m=d,p=-m/f,g=Math.sqrt(Math.pow(m,2)+Math.pow(p,2));return l.multiplyScalar(g),l.z=0,l}}),M(this,"updateMatrixState",()=>{this.camera&&(this._cameraMatrixState.copy(this.camera.matrix),this._gizmoMatrixState.copy(this._gizmos.matrix),this.camera instanceof ne&&(this._cameraProjectionState.copy(this.camera.projectionMatrix),this.camera.updateProjectionMatrix(),this._zoomState=this.camera.zoom),this.camera instanceof Ht&&(this._fovState=this.camera.fov))}),M(this,"updateTbState",(s,n)=>{this._state=s,n&&this.updateMatrixState()}),M(this,"update",()=>{if(!this.target.equals(this._currentTarget)&&this.camera){this._gizmos.position.set(this.target.x,this.target.y,this.target.z);const 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 ne&&(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 Ht){const n=this.camera.position.distanceTo(this._gizmos.position);if(n>this.maxDistance+1e-6||n<this.minDistance-1e-6){const h=ot.clamp(n,this.minDistance,this.maxDistance);this.applyTransformMatrix(this.applyScale(h/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 h=(this._gizmos.scale.x+this._gizmos.scale.y+this._gizmos.scale.z)/3,l=this._tbRadius/h,u=new Nn(0,0,l,l).getPoints(this._curvePts),d=new Pe().setFromPoints(u);for(const f in this._gizmos.children){const m=this._gizmos.children[f];m.geometry=d}}}this.camera.lookAt(this._gizmos.position)}}),M(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 Ht&&(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 mt().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(Pt)}}),this.camera=null,this.domElement=e,this.scene=i,this.mouseActions=[],this._mouseOp=null,this._v2_1=new Kt,this._v3_1=new k,this._v3_2=new k,this._m4_1=new mt,this._m4_2=new mt,this._quat=new yt,this._translationMatrix=new mt,this._rotationMatrix=new mt,this._scaleMatrix=new mt,this._rotationAxis=new k,this._cameraMatrixState=new mt,this._cameraProjectionState=new mt,this._fovState=1,this._upState=new k,this._zoomState=1,this._nearPos=0,this._farPos=0,this._gizmoMatrixState=new mt,this._up0=new k,this._zoom0=1,this._fov0=0,this._initialNear=0,this._nearPos0=0,this._initialFar=0,this._farPos0=0,this._cameraMatrixState0=new mt,this._gizmoMatrixState0=new mt,this._button=-1,this._touchStart=[],this._touchCurrent=[],this._input=Ct.NONE,this._switchSensibility=32,this._startFingerDistance=0,this._currentFingerDistance=0,this._startFingerRotation=0,this._currentFingerRotation=0,this._devPxRatio=0,this._downValid=!0,this._nclicks=0,this._downEvents=[],this._clickStart=0,this._maxDownTime=250,this._maxInterval=300,this._posThreshold=24,this._movementThreshold=24,this._currentCursorPosition=new k,this._startCursorPosition=new k,this._grid=null,this._gridPosition=new k,this._gizmos=new br,this._curvePts=128,this._timeStart=-1,this._animationId=-1,this.focusAnimationTime=500,this._timePrev=0,this._timeCurrent=0,this._anglePrev=0,this._angleCurrent=0,this._cursorPosPrev=new k,this._cursorPosCurr=new k,this._wPrev=0,this._wCurr=0,this.adjustNearFar=!1,this.scaleFactor=1.1,this.dampingFactor=25,this.wMax=20,this.enableAnimations=!0,this.enableGrid=!1,this.cursorZoom=!1,this.minFov=5,this.maxFov=90,this.enabled=!0,this.enablePan=!0,this.enableRotate=!0,this.enableZoom=!0,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.target=new k(0,0,0),this._currentTarget=new k(0,0,0),this._tbRadius=1,this._state=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 ph;s.setFromObject(this._gizmos);const n=new ea;s.getBoundingSphere(n);const r=Math.max(this._nearPos0,n.radius+n.center.length()),o=i-this._initialNear,h=Math.min(r,o);this.camera.near=i-h;const l=Math.min(this._farPos0,-n.radius+n.center.length()),c=i-this._initialFar,u=Math.min(l,c);this.camera.far=i-u,this.camera.updateProjectionMatrix()}else{let i=!1;this.camera.near!=this._initialNear&&(this.camera.near=this._initialNear,i=!0),this.camera.far!=this._initialFar&&(this.camera.far=this._initialFar,i=!0),i&&this.camera.updateProjectionMatrix()}}}setGizmosVisible(t){this._gizmos.visible=t,this.dispatchEvent(Pt)}setTransformationMatrices(t=null,e=null){t?se.camera?se.camera.copy(t):se.camera=t.clone():se.camera=null,e?se.gizmos?se.gizmos.copy(e):se.gizmos=e.clone():se.gizmos=null}};var ME=Object.defineProperty,BE=(a,t,e)=>t in a?ME(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,Lt=(a,t,e)=>(BE(a,typeof t!="symbol"?t+"":t,e),e);function Mo(a){a.preventDefault()}let OE=class extends $i{constructor(t,e){super(),Lt(this,"object"),Lt(this,"domElement",null),Lt(this,"movementSpeed",1),Lt(this,"rollSpeed",.005),Lt(this,"dragToLook",!1),Lt(this,"autoForward",!1),Lt(this,"changeEvent",{type:"change"}),Lt(this,"EPS",1e-6),Lt(this,"tmpQuaternion",new yt),Lt(this,"mouseStatus",0),Lt(this,"movementSpeedMultiplier",1),Lt(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}),Lt(this,"moveVector",new k(0,0,0)),Lt(this,"rotationVector",new k(0,0,0)),Lt(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()}}),Lt(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()}),Lt(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()}}),Lt(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()}}),Lt(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()}),Lt(this,"lastQuaternion",new yt),Lt(this,"lastPosition",new k),Lt(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))}),Lt(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}),Lt(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}),Lt(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]}),Lt(this,"connect",i=>{this.domElement=i,i instanceof Document||i.setAttribute("tabindex",-1),this.domElement.addEventListener("contextmenu",Mo),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)}),Lt(this,"dispose",()=>{this.domElement.removeEventListener("contextmenu",Mo),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 Gh(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 FE(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 h=0;for(let l=0;l<o;++l){const c=r[l+1],u=n[o-l],d=s[l]/(c+u);s[l]=h+c*d,h=u*d}s[o]=h}return s}function kE(a,t,e,i){const s=Gh(a,i,t),n=FE(s,i,a,t),r=new ze(0,0,0,0);for(let o=0;o<=a;++o){const h=e[s-a+o],l=n[o],c=h.w*l;r.x+=h.x*c,r.y+=h.y*c,r.z+=h.z*c,r.w+=h.w*l}return r}function UE(a,t,e,i,s){const n=[];for(let u=0;u<=e;++u)n[u]=0;const r=[];for(let u=0;u<=i;++u)r[u]=n.slice(0);const o=[];for(let u=0;u<=e;++u)o[u]=n.slice(0);o[0][0]=1;const h=n.slice(0),l=n.slice(0);for(let u=1;u<=e;++u){h[u]=t-s[a+1-u],l[u]=s[a+u]-t;let d=0;for(let f=0;f<u;++f){const m=l[f+1],p=h[u-f];o[u][f]=m+p;const g=o[f][u-1]/o[u][f];o[f][u]=d+m*g,d=p*g}o[u][u]=d}for(let u=0;u<=e;++u)r[0][u]=o[u][e];for(let u=0;u<=e;++u){let d=0,f=1;const m=[];for(let p=0;p<=e;++p)m[p]=n.slice(0);m[0][0]=1;for(let p=1;p<=i;++p){let g=0;const E=u-p,A=e-p;u>=p&&(m[f][0]=m[d][0]/o[A+1][E],g=m[f][0]*o[E][A]);const y=E>=-1?1:-E,T=u-1<=A?p-1:e-u;for(let C=y;C<=T;++C)m[f][C]=(m[d][C]-m[d][C-1])/o[A+1][E+C],g+=m[f][C]*o[E+C][A];u<=A&&(m[f][p]=-m[d][p-1]/o[A+1][u],g+=m[f][p]*o[u][A]),r[p][u]=g;const _=d;d=f,f=_}}let c=e;for(let u=1;u<=i;++u){for(let d=0;d<=e;++d)r[u][d]*=c;c*=e-u}return r}function NE(a,t,e,i,s){const n=s<a?s:a,r=[],o=Gh(a,i,t),h=UE(o,i,a,n,t),l=[];for(let c=0;c<e.length;++c){const u=e[c].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,l[c]=u}for(let c=0;c<=n;++c){const u=l[o-a].clone().multiplyScalar(h[c][0]);for(let d=1;d<=a;++d)u.add(l[o-a+d].clone().multiplyScalar(h[c][d]));r[c]=u}for(let c=n+1;c<=s+1;++c)r[c]=new ze(0,0,0);return r}function GE(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 HE(a){const t=a.length,e=[],i=[];for(let n=0;n<t;++n){const r=a[n];e[n]=new k(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(GE(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 HE(n)}class Bo extends Xu{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 k,s=this.knots[this.startKnot]+t*(this.knots[this.endKnot]-this.knots[this.startKnot]),n=kE(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 k,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 gt,Ft,ee;class da extends ju{constructor(t){super(t)}load(t,e,i,s){const n=this,r=n.path===""?Wu.extractUrlBase(t):n.path,o=new Ju(this.manager);o.setPath(n.path),o.setResponseType("arraybuffer"),o.setRequestHeader(n.requestHeader),o.setWithCredentials(n.withCredentials),o.load(t,function(h){try{e(n.parse(h,r))}catch(l){s?s(l):console.error(l),n.manager.itemError(t)}},i,s)}parse(t,e){if(jE(t))gt=new XE().parse(t);else{const s=Vh(t);if(!WE(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Fo(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Fo(s));gt=new YE().parse(s)}const i=new Qu(this.manager).setPath(this.resourcePath||e).setCrossOrigin(this.crossOrigin);return new KE(i,this.manager).parse(gt)}}class KE{constructor(t,e){this.textureLoader=t,this.manager=e}parse(){Ft=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),ee}parseConnections(){const t=new Map;return"Connections"in gt&&gt.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 h={ID:s,relationship:r};t.get(n).children.push(h)}),t}parseImages(){const t={},e={};if("Video"in gt.Objects){const i=gt.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,h=typeof n.Content=="string"&&n.Content!=="";if(o||h){const l=this.parseImage(i[s]);e[n.RelativeFilename||n.Filename]=l}}}}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 gt.Objects){const i=gt.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?Ir:Ha,i.wrapT=o===0?Ir:Ha,"Scaling"in t){const h=t.Scaling.value;i.repeat.x=h[0],i.repeat.y=h[1]}return i}loadTexture(t,e){let i;const s=this.textureLoader.path,n=Ft.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 h=this.manager.getHandler(".tga");h===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",t.RelativeFilename),r=new Lr):(h.setPath(this.textureLoader.path),r=h.load(i))}else o==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",t.RelativeFilename),r=new Lr):r=this.textureLoader.load(i);return this.textureLoader.setPath(s),r}parseMaterials(t){const e=new Map;if("Material"in gt.Objects){const i=gt.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),!Ft.has(i))return null;const r=this.parseParameters(t,e,i);let o;switch(n.toLowerCase()){case"phong":o=new Gn;break;case"lambert":o=new Zu;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',n),o=new Gn;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 kt().fromArray(t.Diffuse.value):t.DiffuseColor&&(t.DiffuseColor.type==="Color"||t.DiffuseColor.type==="ColorRGB")&&(s.color=new kt().fromArray(t.DiffuseColor.value)),t.DisplacementFactor&&(s.displacementScale=t.DisplacementFactor.value),t.Emissive?s.emissive=new kt().fromArray(t.Emissive.value):t.EmissiveColor&&(t.EmissiveColor.type==="Color"||t.EmissiveColor.type==="ColorRGB")&&(s.emissive=new kt().fromArray(t.EmissiveColor.value)),t.EmissiveFactor&&(s.emissiveIntensity=parseFloat(t.EmissiveFactor.value)),t.Opacity&&(s.opacity=parseFloat(t.Opacity.value)),s.opacity<1&&(s.transparent=!0),t.ReflectionFactor&&(s.reflectivity=t.ReflectionFactor.value),t.Shininess&&(s.shininess=t.Shininess.value),t.Specular?s.specular=new kt().fromArray(t.Specular.value):t.SpecularColor&&t.SpecularColor.type==="Color"&&(s.specular=new kt().fromArray(t.SpecularColor.value));const n=this;return Ft.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=td,"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 gt.Objects&&e in gt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),e=Ft.get(e).children[0].ID),t.get(e)}parseDeformers(){const t={},e={};if("Deformer"in gt.Objects){const i=gt.Objects.Deformer;for(const s in i){const n=i[s],r=Ft.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 mt().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=Ft.get(parseInt(n.ID)).children.filter(function(h){return h.relationship===void 0})[0].ID,i.push(o)}return i}parseScene(t,e,i){ee=new br;const s=this.parseModels(t.skeletons,e,i),n=gt.Objects.Model,r=this;s.forEach(function(h){const l=n[h.ID];r.setLookAtProperties(h,l),Ft.get(h.ID).parents.forEach(function(u){const d=s.get(u.ID);d!==void 0&&d.add(h)}),h.parent===null&&ee.add(h)}),this.bindSkeleton(t.skeletons,e,s),this.createAmbientLight(),ee.traverse(function(h){if(h.userData.transformData){h.parent&&(h.userData.transformData.parentMatrix=h.parent.matrix,h.userData.transformData.parentMatrixWorld=h.parent.matrixWorld);const l=$h(h.userData.transformData);h.applyMatrix4(l),h.updateWorldMatrix()}});const o=new zE().parse();ee.children.length===1&&ee.children[0].isGroup&&(ee.children[0].animations=o,ee=ee.children[0]),ee.animations=o}parseModels(t,e,i){const s=new Map,n=gt.Objects.Model;for(const r in n){const o=parseInt(r),h=n[r],l=Ft.get(o);let c=this.buildSkeleton(l,t,o,h.attrName);if(!c){switch(h.attrType){case"Camera":c=this.createCamera(l);break;case"Light":c=this.createLight(l);break;case"Mesh":c=this.createMesh(l,e,i);break;case"NurbsCurve":c=this.createCurve(l,e);break;case"LimbNode":case"Root":c=new $a;break;case"Null":default:c=new br;break}c.name=h.attrName?cn.sanitizeNodeName(h.attrName):"",c.ID=o}this.getTransformData(c,h),s.set(o,c)}return s}buildSkeleton(t,e,i,s){let n=null;return t.parents.forEach(function(r){for(const o in e){const h=e[o];h.rawBones.forEach(function(l,c){if(l.ID===r.ID){const u=n;n=new $a,n.matrixWorld.copy(l.transformLink),n.name=s?cn.sanitizeNodeName(s):"",n.ID=i,h.bones[c]=n,u!==null&&n.add(u)}})}}),n}createCamera(t){let e,i;if(t.children.forEach(function(s){const n=gt.Objects.NodeAttribute[s.ID];n!==void 0&&(i=n)}),i===void 0)e=new qt;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,h=window.innerHeight;i.AspectWidth!==void 0&&i.AspectHeight!==void 0&&(o=i.AspectWidth.value,h=i.AspectHeight.value);const l=o/h;let c=45;i.FieldOfView!==void 0&&(c=i.FieldOfView.value);const u=i.FocalLength?i.FocalLength.value:null;switch(s){case 0:e=new Ht(c,l,n,r),u!==null&&e.setFocalLength(u);break;case 1:e=new ne(-o/2,o/2,h/2,-h/2,n,r);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+s+"."),e=new qt;break}}return e}createLight(t){let e,i;if(t.children.forEach(function(s){const n=gt.Objects.NodeAttribute[s.ID];n!==void 0&&(i=n)}),i===void 0)e=new qt;else{let s;i.LightType===void 0?s=0:s=i.LightType.value;let n=16777215;i.Color!==void 0&&(n=new kt().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 h=1;switch(s){case 0:e=new Ka(n,r,o,h);break;case 1:e=new id(n,r);break;case 2:let l=Math.PI/3;i.InnerAngle!==void 0&&(l=ot.degToRad(i.InnerAngle.value));let c=0;i.OuterAngle!==void 0&&(c=ot.degToRad(i.OuterAngle.value),c=Math.max(c,1)),e=new ed(n,r,o,l,c,h);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),e=new Ka(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(h){e.has(h.ID)&&(n=e.get(h.ID)),i.has(h.ID)&&o.push(i.get(h.ID))}),o.length>1?r=o:o.length>0?r=o[0]:(r=new Gn({color:13421772}),o.push(r)),"color"in n.attributes&&o.forEach(function(h){h.vertexColors=!0}),n.FBX_Deformer?(s=new sd(n,r),s.normalizeSkinWeights()):s=new nt(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 cs({color:3342591,linewidth:1});return new Et(i,s)}getTransformData(t,e){const i={};"InheritType"in e&&(i.inheritType=parseInt(e.InheritType.value)),"RotationOrder"in e?i.eulerOrder=Kh(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&&Ft.get(t.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const n=gt.Objects.Model[s.ID];if("Lcl_Translation"in n){const r=n.Lcl_Translation.value;t.target!==void 0?(t.target.position.fromArray(r),ee.add(t.target)):t.lookAt(new k().fromArray(r))}}})}bindSkeleton(t,e,i){const s=this.parsePoseNodes();for(const n in t){const r=t[n];Ft.get(parseInt(r.ID)).parents.forEach(function(h){if(e.has(h.ID)){const l=h.ID;Ft.get(l).parents.forEach(function(u){i.has(u.ID)&&i.get(u.ID).bind(new nd(r.bones),s[u.ID])})}})}}parsePoseNodes(){const t={};if("Pose"in gt.Objects){const e=gt.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 mt().fromArray(n.Matrix.a)}):t[s.Node]=new mt().fromArray(s.Matrix.a)}}return t}createAmbientLight(){if("GlobalSettings"in gt&&"AmbientColor"in gt.GlobalSettings){const t=gt.GlobalSettings.AmbientColor.value,e=t[0],i=t[1],s=t[2];if(e!==0||i!==0||s!==0){const n=new kt(e,i,s);ee.add(new rd(n,1))}}}}class VE{parse(t){const e=new Map;if("Geometry"in gt.Objects){const i=gt.Objects.Geometry;for(const s in i){const n=Ft.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(u){return gt.Objects.Model[u.ID]});if(r.length===0)return;const o=t.children.reduce(function(u,d){return s[d.ID]!==void 0&&(u=s[d.ID]),u},null);t.children.forEach(function(u){i.morphTargets[u.ID]!==void 0&&n.push(i.morphTargets[u.ID])});const h=r[0],l={};"RotationOrder"in h&&(l.eulerOrder=Kh(h.RotationOrder.value)),"InheritType"in h&&(l.inheritType=parseInt(h.InheritType.value)),"GeometricTranslation"in h&&(l.translation=h.GeometricTranslation.value),"GeometricRotation"in h&&(l.rotation=h.GeometricRotation.value),"GeometricScaling"in h&&(l.scale=h.GeometricScaling.value);const c=$h(l);return this.genGeometry(e,o,n,c)}genGeometry(t,e,i,s){const n=new Pe;t.attrName&&(n.name=t.attrName);const r=this.parseGeoNode(t,e),o=this.genBuffers(r),h=new Ge(o.vertex,3);if(h.applyMatrix4(s),n.setAttribute("position",h),o.colors.length>0&&n.setAttribute("color",new Ge(o.colors,3)),e&&(n.setAttribute("skinIndex",new ad(o.weightsIndices,4)),n.setAttribute("skinWeight",new Ge(o.vertexWeights,4)),n.FBX_Deformer=e),o.normal.length>0){const l=new hs().getNormalMatrix(s),c=new Ge(o.normal,3);c.applyNormalMatrix(l),n.setAttribute("normal",c)}if(o.uvs.forEach(function(l,c){ud==="uv2"&&c++;const u=c===0?"uv":`uv${c}`;n.setAttribute(u,new Ge(o.uvs[c],2))}),r.material&&r.material.mappingType!=="AllSame"){let l=o.materialIndex[0],c=0;if(o.materialIndex.forEach(function(u,d){u!==l&&(n.addGroup(c,d-c,l),l=u,c=d)}),n.groups.length>0){const u=n.groups[n.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&n.addGroup(d,o.materialIndex.length-d,l)}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=[],h=[],l=[],c=[],u=[];const d=this;return t.vertexIndices.forEach(function(f,m){let p,g=!1;f<0&&(f=f^-1,g=!0);let E=[],A=[];if(r.push(f*3,f*3+1,f*3+2),t.color){const y=Ps(m,i,f,t.color);h.push(y[0],y[1],y[2])}if(t.skeleton){if(t.weightTable[f]!==void 0&&t.weightTable[f].forEach(function(y){A.push(y.weight),E.push(y.id)}),A.length>4){n||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),n=!0);const y=[0,0,0,0],T=[0,0,0,0];A.forEach(function(_,C){let S=_,I=E[C];T.forEach(function(L,b,w){if(S>L){w[b]=S,S=L;const O=y[b];y[b]=I,I=O}})}),E=y,A=T}for(;A.length<4;)A.push(0),E.push(0);for(let y=0;y<4;++y)c.push(A[y]),u.push(E[y])}if(t.normal){const y=Ps(m,i,f,t.normal);o.push(y[0],y[1],y[2])}t.material&&t.material.mappingType!=="AllSame"&&(p=Ps(m,i,f,t.material)[0]),t.uv&&t.uv.forEach(function(y,T){const _=Ps(m,i,f,y);l[T]===void 0&&(l[T]=[]),l[T].push(_[0]),l[T].push(_[1])}),s++,g&&(d.genFace(e,t,r,p,o,h,l,c,u,s),i++,s=0,r=[],o=[],h=[],l=[],c=[],u=[])}),e}genFace(t,e,i,s,n,r,o,h,l,c){for(let u=2;u<c;u++)t.vertex.push(e.vertexPositions[i[0]]),t.vertex.push(e.vertexPositions[i[1]]),t.vertex.push(e.vertexPositions[i[2]]),t.vertex.push(e.vertexPositions[i[(u-1)*3]]),t.vertex.push(e.vertexPositions[i[(u-1)*3+1]]),t.vertex.push(e.vertexPositions[i[(u-1)*3+2]]),t.vertex.push(e.vertexPositions[i[u*3]]),t.vertex.push(e.vertexPositions[i[u*3+1]]),t.vertex.push(e.vertexPositions[i[u*3+2]]),e.skeleton&&(t.vertexWeights.push(h[0]),t.vertexWeights.push(h[1]),t.vertexWeights.push(h[2]),t.vertexWeights.push(h[3]),t.vertexWeights.push(h[(u-1)*4]),t.vertexWeights.push(h[(u-1)*4+1]),t.vertexWeights.push(h[(u-1)*4+2]),t.vertexWeights.push(h[(u-1)*4+3]),t.vertexWeights.push(h[u*4]),t.vertexWeights.push(h[u*4+1]),t.vertexWeights.push(h[u*4+2]),t.vertexWeights.push(h[u*4+3]),t.weightsIndices.push(l[0]),t.weightsIndices.push(l[1]),t.weightsIndices.push(l[2]),t.weightsIndices.push(l[3]),t.weightsIndices.push(l[(u-1)*4]),t.weightsIndices.push(l[(u-1)*4+1]),t.weightsIndices.push(l[(u-1)*4+2]),t.weightsIndices.push(l[(u-1)*4+3]),t.weightsIndices.push(l[u*4]),t.weightsIndices.push(l[u*4+1]),t.weightsIndices.push(l[u*4+2]),t.weightsIndices.push(l[u*4+3])),e.color&&(t.colors.push(r[0]),t.colors.push(r[1]),t.colors.push(r[2]),t.colors.push(r[(u-1)*3]),t.colors.push(r[(u-1)*3+1]),t.colors.push(r[(u-1)*3+2]),t.colors.push(r[u*3]),t.colors.push(r[u*3+1]),t.colors.push(r[u*3+2])),e.material&&e.material.mappingType!=="AllSame"&&(t.materialIndex.push(s),t.materialIndex.push(s),t.materialIndex.push(s)),e.normal&&(t.normal.push(n[0]),t.normal.push(n[1]),t.normal.push(n[2]),t.normal.push(n[(u-1)*3]),t.normal.push(n[(u-1)*3+1]),t.normal.push(n[(u-1)*3+2]),t.normal.push(n[u*3]),t.normal.push(n[u*3+1]),t.normal.push(n[u*3+2])),e.uv&&e.uv.forEach(function(d,f){t.uvs[f]===void 0&&(t.uvs[f]=[]),t.uvs[f].push(o[f][0]),t.uvs[f].push(o[f][1]),t.uvs[f].push(o[f][(u-1)*2]),t.uvs[f].push(o[f][(u-1)*2+1]),t.uvs[f].push(o[f][u*2]),t.uvs[f].push(o[f][u*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 h=gt.Objects.Geometry[o.geoID];h!==void 0&&n.genMorphGeometry(t,e,h,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:[],h=i.Indexes!==void 0?i.Indexes.a:[],l=t.attributes.position.count*3,c=new Float32Array(l);for(let m=0;m<h.length;m++){const p=h[m]*3;c[p]=o[m*3],c[p+1]=o[m*3+1],c[p+2]=o[m*3+2]}const u={vertexIndices:r,vertexPositions:c},d=this.genBuffers(u),f=new Ge(d.vertex,3);f.name=n||i.attrName,f.applyMatrix4(s),t.morphAttributes.position.push(f)}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(Bo===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 Pe;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 Pe;const i=e-1,s=t.KnotVector.a,n=[],r=t.Points.a;for(let u=0,d=r.length;u<d;u+=4)n.push(new ze().fromArray(r,u));let o,h;if(t.Form==="Closed")n.push(n[0]);else if(t.Form==="Periodic"){o=i,h=s.length-1-o;for(let u=0;u<i;++u)n.push(n[u])}const c=new Bo(i,s,n,o,h).getPoints(n.length*12);return new Pe().setFromPoints(c)}}class zE{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(gt.Objects.AnimationCurve===void 0)return;const t=this.parseAnimationCurveNodes();this.parseAnimationCurves(t);const e=this.parseAnimationLayers(t);return this.parseAnimStacks(e)}parseAnimationCurveNodes(){const t=gt.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=gt.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=Ft.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=gt.Objects.AnimationLayer,i=new Map;for(const s in e){const n=[],r=Ft.get(parseInt(s));r!==void 0&&(r.children.forEach(function(h,l){if(t.has(h.ID)){const c=t.get(h.ID);if(c.curves.x!==void 0||c.curves.y!==void 0||c.curves.z!==void 0){if(n[l]===void 0){const u=Ft.get(h.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=gt.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",h);return}const f={modelName:d.attrName?cn.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ee.traverse(function(m){m.ID===d.id&&(f.transform=m.matrix,m.userData.transformData&&(f.eulerOrder=m.userData.transformData.eulerOrder))}),f.transform||(f.transform=new mt),"PreRotation"in d&&(f.preRotation=d.PreRotation.value),"PostRotation"in d&&(f.postRotation=d.PostRotation.value),n[l]=f}}n[l]&&(n[l][c.attr]=c)}else if(c.curves.morph!==void 0){if(n[l]===void 0){const u=Ft.get(h.ID).parents.filter(function(E){return E.relationship!==void 0})[0].ID,d=Ft.get(u).parents[0].ID,f=Ft.get(d).parents[0].ID,m=Ft.get(f).parents[0].ID,p=gt.Objects.Model[m],g={modelName:p.attrName?cn.sanitizeNodeName(p.attrName):"",morphName:gt.Objects.Deformer[u].attrName};n[l]=g}n[l][c.attr]=c}}}),i.set(parseInt(s),n))}return i}parseAnimStacks(t){const e=gt.Objects.AnimationStack,i={};for(const s in e){const n=Ft.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 od(t.name,-1,e)}generateTracks(t){const e=[];let i=new k,s=new yt,n=new k;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 ld(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),h=this.getKeyframeTrackValues(o,e,i);s!==void 0&&(s=s.map(ot.degToRad),s.push(r),s=new $e().fromArray(s),s=new yt().setFromEuler(s)),n!==void 0&&(n=n.map(ot.degToRad),n.push(r),n=new $e().fromArray(n),n=new yt().setFromEuler(n).invert());const l=new yt,c=new $e,u=[];for(let d=0;d<h.length;d+=3)c.set(h[d],h[d+1],h[d+2],r),l.setFromEuler(c),s!==void 0&&l.premultiply(s),n!==void 0&&l.multiply(n),l.toArray(u,d/3*4);return new hd(t+".quaternion",o,u)}generateMorphTrack(t){const e=t.DeformPercent.curves.morph,i=e.values.map(function(n){return n/100}),s=ee.getObjectByName(t.modelName).morphTargetDictionary[t.morphName];return new cd(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,h=-1;return t.forEach(function(l){if(e.x&&(r=e.x.times.indexOf(l)),e.y&&(o=e.y.times.indexOf(l)),e.z&&(h=e.z.times.indexOf(l)),r!==-1){const c=e.x.values[r];n.push(c),s[0]=c}else n.push(s[0]);if(o!==-1){const c=e.y.values[o];n.push(c),s[1]=c}else n.push(s[1]);if(h!==-1){const c=e.z.values[h];n.push(c),s[2]=c}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 h=i+o;const l=t.times[e-1],u=(t.times[e]-l)/r;let d=l+u;const f=[],m=[];for(;d<t.times[e];)f.push(d),d+=u,m.push(h),h+=o;t.times=ko(t.times,e,f),t.values=ko(t.values,e,m)}}}}class YE{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 Hh,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 h=s.match("^\\t{"+e.currentIndent+"}(\\w+):(.*){",""),l=s.match("^\\t{"+e.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),c=s.match("^\\t{"+(e.currentIndent-1)+"}}");h?e.parseNodeBegin(s,h):l?e.parseNodeProperty(s,l,i[++n]):c?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(h){return h.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 h=n.split(",").slice(1),l=parseInt(h[0]),c=parseInt(h[1]);let u=n.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),s="connections",n=[l,c],qE(n,u),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=Vn(n))}parseNodePropertyContinued(t){const e=this.getCurrentNode();e.a+=t,t.slice(-1)!==","&&(e.a=Vn(e.a))}parseNodeSpecialProperty(t,e,i){const s=i.split('",').map(function(c){return c.trim().replace(/^\"/,"").replace(/\s/,"_")}),n=s[0],r=s[1],o=s[2],h=s[3];let l=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":l=parseFloat(l);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":l=Vn(l);break}this.getPrevNode()[n]={type:r,type2:o,flag:h,value:l},this.setCurrentProp(this.getPrevNode(),n)}}class XE{parse(t){const e=new Oo(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 Hh;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 h=[];for(let d=0;d<n;d++)h.push(this.parseProperty(t));const l=h.length>0?h[0]:"",c=h.length>1?h[1]:"",u=h.length>2?h[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=h,typeof l=="number"&&(i.id=l),c!==""&&(i.attrName=c),u!==""&&(i.attrType=u),o!==""&&(i.name=o),i}parseSubNode(t,e,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(e[i.name]=i,i.a=s):e[i.name]=s}else if(t==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(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 h;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?h=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:h=i.propertyList[4],e[s]={type:n,type2:r,flag:o,value:h}}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=qu(new Uint8Array(t.getArrayBuffer(r))),h=new Oo(o.buffer);switch(e){case"b":case"c":return h.getBooleanArray(s);case"d":return h.getFloat64Array(s);case"f":return h.getFloat32Array(s);case"i":return h.getInt32Array(s);case"l":return h.getInt64Array(s)}default:throw new Error("THREE.FBXLoader: Unknown property type "+e)}}}class Oo{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)),gh(new Uint8Array(e))}}class Hh{add(t,e){this[t]=e}}function jE(a){const t="Kaydara FBX Binary \0";return a.byteLength>=t.length&&t===Vh(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 Fo(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 QE=[];function Ps(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 ZE(QE,i.buffer,n,r)}const Kn=new $e,Ti=new k;function $h(a){const t=new mt,e=new mt,i=new mt,s=new mt,n=new mt,r=new mt,o=new mt,h=new mt,l=new mt,c=new mt,u=new mt,d=new mt,f=a.inheritType?a.inheritType:0;if(a.translation&&t.setPosition(Ti.fromArray(a.translation)),a.preRotation){const b=a.preRotation.map(ot.degToRad);b.push(a.eulerOrder),e.makeRotationFromEuler(Kn.fromArray(b))}if(a.rotation){const b=a.rotation.map(ot.degToRad);b.push(a.eulerOrder),i.makeRotationFromEuler(Kn.fromArray(b))}if(a.postRotation){const b=a.postRotation.map(ot.degToRad);b.push(a.eulerOrder),s.makeRotationFromEuler(Kn.fromArray(b)),s.invert()}a.scale&&n.scale(Ti.fromArray(a.scale)),a.scalingOffset&&o.setPosition(Ti.fromArray(a.scalingOffset)),a.scalingPivot&&r.setPosition(Ti.fromArray(a.scalingPivot)),a.rotationOffset&&h.setPosition(Ti.fromArray(a.rotationOffset)),a.rotationPivot&&l.setPosition(Ti.fromArray(a.rotationPivot)),a.parentMatrixWorld&&(u.copy(a.parentMatrix),c.copy(a.parentMatrixWorld));const m=e.clone().multiply(i).multiply(s),p=new mt;p.extractRotation(c);const g=new mt;g.copyPosition(c);const E=g.clone().invert().multiply(c),A=p.clone().invert().multiply(E),y=n,T=new mt;if(f===0)T.copy(p).multiply(m).multiply(A).multiply(y);else if(f===1)T.copy(p).multiply(A).multiply(m).multiply(y);else{const w=new mt().scale(new k().setFromMatrixScale(u)).clone().invert(),O=A.clone().multiply(w);T.copy(p).multiply(m).multiply(O).multiply(y)}const _=l.clone().invert(),C=r.clone().invert();let S=t.clone().multiply(h).multiply(l).multiply(e).multiply(i).multiply(s).multiply(_).multiply(o).multiply(r).multiply(n).multiply(C);const I=new mt().copyPosition(S),L=c.clone().multiply(I);return d.copyPosition(L),S=d.clone().multiply(T),S.premultiply(c.invert()),S}function Kh(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 Vn(a){return a.split(",").map(function(e){return parseFloat(e)})}function Vh(a,t,e){return t===void 0&&(t=0),e===void 0&&(e=a.byteLength),gh(new Uint8Array(a,t,e))}function qE(a,t){for(let e=0,i=a.length,s=t.length;e<s;e++,i++)a[i]=t[e]}function ZE(a,t,e,i){for(let s=e,n=0;s<i;s++,n++)a[n]=t[s];return a}function ko(a,t,e){return a.slice(0,t).concat(e).concat(a.slice(t))}let ws;const zn=()=>{if(ws)return ws;const a="B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB",t="B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB",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(u=>{n=u.instance,n.exports.__wasm_call_ctors()});function o(u){const d=new Uint8Array(u.length);for(let m=0;m<u.length;++m){const p=u.charCodeAt(m);d[m]=p>96?p-71:p>64?p-65:p>47?p+4:p>46?63:62}let f=0;for(let m=0;m<u.length;++m)d[f++]=d[m]<60?i[d[m]]:(d[m]-60)*64+d[++m];return d.buffer.slice(0,f)}function h(u,d,f,m,p,g){const E=n.exports.sbrk,A=f+3&-4,y=E(A*m),T=E(p.length),_=new Uint8Array(n.exports.memory.buffer);_.set(p,T);const C=u(y,f,m,T,p.length);if(C===0&&g&&g(y,A,m),d.set(_.subarray(y,y+f*m)),E(y-E(0)),C!==0)throw new Error(`Malformed buffer data: ${C}`)}const l={0:"",1:"meshopt_decodeFilterOct",2:"meshopt_decodeFilterQuat",3:"meshopt_decodeFilterExp",NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},c={0:"meshopt_decodeVertexBuffer",1:"meshopt_decodeIndexBuffer",2:"meshopt_decodeIndexSequence",ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return ws={ready:r,supported:!0,decodeVertexBuffer(u,d,f,m,p){h(n.exports.meshopt_decodeVertexBuffer,u,d,f,m,n.exports[l[p]])},decodeIndexBuffer(u,d,f,m){h(n.exports.meshopt_decodeIndexBuffer,u,d,f,m)},decodeIndexSequence(u,d,f,m){h(n.exports.meshopt_decodeIndexSequence,u,d,f,m)},decodeGltfBuffer(u,d,f,m,p,g){h(n.exports[c[p]],u,d,f,m,n.exports[l[g]])}},ws},ty=new k,ey=x.forwardRef(({scale:a=1,...t},e)=>{const i=x.useRef(null);return x.useImperativeHandle(e,()=>i.current,[]),Ut(s=>{const n=i.current;if(!n)return;const r=Eh(n.getWorldPosition(ty),a,s.camera,s.size);n.scale.setScalar(r*a)}),x.createElement("object3D",wt({ref:i},t))});let Ms=null,zh="https://www.gstatic.com/draco/versioned/decoders/1.5.5/";function Yh(a=!0,t=!0,e){return i=>{e&&e(i),a&&(Ms||(Ms=new dd),Ms.setDecoderPath(typeof a=="string"?a:zh),i.setDRACOLoader(Ms)),t&&i.setMeshoptDecoder(typeof zn=="function"?zn():zn)}}const Ss=(a,t,e,i)=>Se(sa,a,Yh(t,e,i));Ss.preload=(a,t,e,i)=>Se.preload(sa,a,Yh(t,e,i));Ss.clear=a=>Se.clear(sa,a);Ss.setDecoderPath=a=>{zh=a};const iy=x.forwardRef(({src:a,useDraco:t,useMeshOpt:e,extendLoader:i,...s},n)=>{const{scene:r}=Ss(a,t,e,i);return x.createElement(ia,wt({ref:n},s,{object:r}))}),sy=x.forwardRef((a,t)=>{const{camera:e,onChange:i,makeDefault:s,...n}=a,r=Q(d=>d.camera),o=Q(d=>d.invalidate),h=Q(d=>d.get),l=Q(d=>d.set),c=e||r,u=x.useMemo(()=>new bE(c),[c]);return x.useEffect(()=>{const d=f=>{o(),i&&i(f)};return u==null||u.addEventListener==null||u.addEventListener("change",d),()=>u==null||u.removeEventListener==null?void 0:u.removeEventListener("change",d)},[i,u,o]),Ut(()=>u==null?void 0:u.update(),-1),x.useEffect(()=>{const d=u;return d==null||d.connect(),()=>d==null?void 0:d.dispose()},[u]),x.useEffect(()=>{if(s){const d=h().controls;return l({controls:u}),()=>l({controls:d})}},[s,u]),u?x.createElement("primitive",wt({ref:t,object:u},n)):null}),ny=x.forwardRef(({domElement:a,...t},e)=>{const{onChange:i,makeDefault:s,...n}=t,r=Q(m=>m.invalidate),o=Q(m=>m.camera),h=Q(m=>m.gl),l=Q(m=>m.events),c=Q(m=>m.get),u=Q(m=>m.set),d=a||l.connected||h.domElement,f=x.useMemo(()=>new OE(o),[o]);return x.useEffect(()=>(f.connect(d),()=>void f.dispose()),[d,f,r]),x.useEffect(()=>{const m=p=>{r(),i&&i(p)};return f.addEventListener==null||f.addEventListener("change",m),()=>f.removeEventListener==null?void 0:f.removeEventListener("change",m)},[i,r]),x.useEffect(()=>{if(s){const m=c().controls;return u({controls:f}),()=>u({controls:m})}},[s,f]),Ut((m,p)=>f.update(p)),x.createElement("primitive",wt({ref:e,object:f,args:[o,d]},n))}),ry=x.forwardRef((a={enableDamping:!0},t)=>{const{domElement:e,camera:i,makeDefault:s,onChange:n,onStart:r,onEnd:o,...h}=a,l=Q(A=>A.invalidate),c=Q(A=>A.camera),u=Q(A=>A.gl),d=Q(A=>A.events),f=Q(A=>A.set),m=Q(A=>A.get),p=e||d.connected||u.domElement,g=i||c,E=x.useMemo(()=>new fd(g),[g]);return x.useEffect(()=>{E.connect(p);const A=y=>{l(),n&&n(y)};return E.addEventListener("change",A),r&&E.addEventListener("start",r),o&&E.addEventListener("end",o),()=>{E.dispose(),E.removeEventListener("change",A),r&&E.removeEventListener("start",r),o&&E.removeEventListener("end",o)}},[n,r,o,E,l,p]),x.useEffect(()=>{if(s){const A=m().controls;return f({controls:E}),()=>f({controls:A})}},[s,E]),Ut(()=>E.update(),-1),x.createElement("primitive",wt({ref:t,object:E,enableDamping:!0},h))}),ay=x.forwardRef(({makeDefault:a,camera:t,domElement:e,regress:i,onChange:s,onStart:n,onEnd:r,...o},h)=>{const{invalidate:l,camera:c,gl:u,events:d,set:f,get:m,performance:p,viewport:g}=Q(),E=t||c,A=e||d.connected||u.domElement,y=x.useMemo(()=>new RE(E),[E]);return Ut(()=>{y.enabled&&y.update()},-1),x.useEffect(()=>(y.connect(A),()=>void y.dispose()),[A,i,y,l]),x.useEffect(()=>{const T=_=>{l(),i&&p.regress(),s&&s(_)};return y.addEventListener("change",T),n&&y.addEventListener("start",n),r&&y.addEventListener("end",r),()=>{n&&y.removeEventListener("start",n),r&&y.removeEventListener("end",r),y.removeEventListener("change",T)}},[s,n,r,y,l]),x.useEffect(()=>{y.handleResize()},[g]),x.useEffect(()=>{if(a){const T=m().controls;return f({controls:y}),()=>f({controls:T})}},[a,y]),x.createElement("primitive",wt({ref:h,object:y},o))}),oy=x.forwardRef(({camera:a,makeDefault:t,regress:e,domElement:i,onChange:s,onStart:n,onEnd:r,...o},h)=>{const l=Q(y=>y.invalidate),c=Q(y=>y.camera),u=Q(y=>y.gl),d=Q(y=>y.events),f=Q(y=>y.set),m=Q(y=>y.get),p=Q(y=>y.performance),g=a||c,E=i||d.connected||u.domElement,A=x.useMemo(()=>new wE(g),[g]);return Ut(()=>{A.enabled&&A.update()},-1),x.useEffect(()=>(A.connect(E),()=>void A.dispose()),[E,e,A,l]),x.useEffect(()=>{const y=T=>{l(),e&&p.regress(),s&&s(T)};return A.addEventListener("change",y),n&&A.addEventListener("start",n),r&&A.addEventListener("end",r),()=>{A.removeEventListener("change",y),n&&A.removeEventListener("start",n),r&&A.removeEventListener("end",r)}},[s,n,r]),x.useEffect(()=>{if(t){const y=m().controls;return f({controls:A}),()=>f({controls:y})}},[t,A]),x.createElement("primitive",wt({ref:h,object:A},o))}),ly=x.forwardRef(({children:a,domElement:t,onChange:e,onMouseDown:i,onMouseUp:s,onObjectChange:n,object:r,makeDefault:o,camera:h,enabled:l,axis:c,mode:u,translationSnap:d,rotationSnap:f,scaleSnap:m,space:p,size:g,showX:E,showY:A,showZ:y,...T},_)=>{const C=Q(K=>K.controls),S=Q(K=>K.gl),I=Q(K=>K.events),L=Q(K=>K.camera),b=Q(K=>K.invalidate),w=Q(K=>K.get),O=Q(K=>K.set),H=h||L,Y=t||I.connected||S.domElement,$=x.useMemo(()=>new pE(H,Y),[H,Y]),z=x.useRef(null);x.useLayoutEffect(()=>(r?$.attach(r instanceof qt?r:r.current):z.current instanceof qt&&$.attach(z.current),()=>void $.detach()),[r,a,$]),x.useEffect(()=>{if(C){const K=V=>C.enabled=!V.value;return $.addEventListener("dragging-changed",K),()=>$.removeEventListener("dragging-changed",K)}},[$,C]);const W=x.useRef(void 0),J=x.useRef(void 0),G=x.useRef(void 0),U=x.useRef(void 0);return x.useLayoutEffect(()=>void(W.current=e),[e]),x.useLayoutEffect(()=>void(J.current=i),[i]),x.useLayoutEffect(()=>void(G.current=s),[s]),x.useLayoutEffect(()=>void(U.current=n),[n]),x.useEffect(()=>{const K=tt=>{b(),W.current==null||W.current(tt)},V=tt=>J.current==null?void 0:J.current(tt),X=tt=>G.current==null?void 0:G.current(tt),R=tt=>U.current==null?void 0:U.current(tt);return $.addEventListener("change",K),$.addEventListener("mouseDown",V),$.addEventListener("mouseUp",X),$.addEventListener("objectChange",R),()=>{$.removeEventListener("change",K),$.removeEventListener("mouseDown",V),$.removeEventListener("mouseUp",X),$.removeEventListener("objectChange",R)}},[b,$]),x.useEffect(()=>{if(o){const K=w().controls;return O({controls:$}),()=>O({controls:K})}},[o,$]),x.createElement(x.Fragment,null,x.createElement("primitive",{ref:_,object:$,enabled:l,axis:c,mode:u,translationSnap:d,rotationSnap:f,scaleSnap:m,space:p,size:g,showX:E,showY:A,showZ:y}),x.createElement("group",wt({ref:z},T),a))}),hy=x.forwardRef(({domElement:a,selector:t,onChange:e,onLock:i,onUnlock:s,enabled:n=!0,makeDefault:r,...o},h)=>{const{camera:l,...c}=o,u=Q(_=>_.setEvents),d=Q(_=>_.gl),f=Q(_=>_.camera),m=Q(_=>_.invalidate),p=Q(_=>_.events),g=Q(_=>_.get),E=Q(_=>_.set),A=l||f,y=a||p.connected||d.domElement,T=x.useMemo(()=>new SE(A),[A]);return x.useEffect(()=>{if(n){T.connect(y);const _=g().events.compute;return u({compute(C,S){const I=S.size.width/2,L=S.size.height/2;S.pointer.set(I/S.size.width*2-1,-(L/S.size.height)*2+1),S.raycaster.setFromCamera(S.pointer,S.camera)}}),()=>{T.disconnect(),u({compute:_})}}},[n,T]),x.useEffect(()=>{const _=I=>{m(),e&&e(I)};T.addEventListener("change",_),i&&T.addEventListener("lock",i),s&&T.addEventListener("unlock",s);const C=()=>T.lock(),S=t?Array.from(document.querySelectorAll(t)):[document];return S.forEach(I=>I&&I.addEventListener("click",C)),()=>{T.removeEventListener("change",_),i&&T.removeEventListener("lock",i),s&&T.removeEventListener("unlock",s),S.forEach(I=>I?I.removeEventListener("click",C):void 0)}},[e,i,s,t,T,m]),x.useEffect(()=>{if(r){const _=g().controls;return E({controls:T}),()=>E({controls:_})}},[r,T]),x.createElement("primitive",wt({ref:h,object:T},c))}),cy=x.forwardRef(({domElement:a,makeDefault:t,...e},i)=>{const s=Q(u=>u.camera),n=Q(u=>u.gl),r=Q(u=>u.events),o=Q(u=>u.get),h=Q(u=>u.set),l=a||r.connected||n.domElement,[c]=x.useState(()=>new dE(s,l));return x.useEffect(()=>{if(t){const u=o().controls;return h({controls:c}),()=>h({controls:u})}},[t,c]),Ut((u,d)=>{c.update(d)},-1),c?x.createElement("primitive",wt({ref:i,object:c},e)):null});/*!
4
+ * camera-controls
5
+ * https://github.com/yomotsu/camera-controls
6
+ * (c) 2017 @yomotsu
7
+ * Released under the MIT License.
8
+ */const Ot={LEFT:1,RIGHT:2,MIDDLE:4},B=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}),_i={NONE:0,IN:1,OUT:-1};function li(a){return a.isPerspectiveCamera}function Je(a){return a.isOrthographicCamera}const Si=Math.PI*2,Uo=Math.PI/2,Xh=1e-5,es=Math.PI/180;function Ae(a,t,e){return Math.max(t,Math.min(e,a))}function Dt(a,t=Xh){return Math.abs(a)<t}function St(a,t,e=Xh){return Dt(a-t,e)}function No(a,t){return Math.round(a/t)*t}function is(a){return isFinite(a)?a:a<0?-Number.MAX_VALUE:Number.MAX_VALUE}function ss(a){return Math.abs(a)<Number.MAX_VALUE?a:a*(1/0)}function Bs(a,t,e,i,s=1/0,n){i=Math.max(1e-4,i);const r=2/i,o=r*n,h=1/(1+o+.48*o*o+.235*o*o*o);let l=a-t;const c=t,u=s*i;l=Ae(l,-u,u),t=a-l;const d=(e.value+r*l)*n;e.value=(e.value-r*d)*h;let f=t+(l+d)*h;return c-a>0==f>c&&(f=c,e.value=(f-c)/n),f}function Go(a,t,e,i,s=1/0,n,r){i=Math.max(1e-4,i);const o=2/i,h=o*n,l=1/(1+h+.48*h*h+.235*h*h*h);let c=t.x,u=t.y,d=t.z,f=a.x-c,m=a.y-u,p=a.z-d;const g=c,E=u,A=d,y=s*i,T=y*y,_=f*f+m*m+p*p;if(_>T){const $=Math.sqrt(_);f=f/$*y,m=m/$*y,p=p/$*y}c=a.x-f,u=a.y-m,d=a.z-p;const C=(e.x+o*f)*n,S=(e.y+o*m)*n,I=(e.z+o*p)*n;e.x=(e.x-o*C)*l,e.y=(e.y-o*S)*l,e.z=(e.z-o*I)*l,r.x=c+(f+C)*l,r.y=u+(m+S)*l,r.z=d+(p+I)*l;const L=g-a.x,b=E-a.y,w=A-a.z,O=r.x-g,H=r.y-E,Y=r.z-A;return L*O+b*H+w*Y>0&&(r.x=g,r.y=E,r.z=A,e.x=(r.x-g)/n,e.y=(r.y-E)/n,e.z=(r.z-A)/n),r}function Yn(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 Xn(a,t){return Je(a)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}class uy{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 jn;const dy="2.10.1",Os=1/8,fy=/Mac/.test((jn=globalThis==null?void 0:globalThis.navigator)===null||jn===void 0?void 0:jn.platform);let at,Ho,Fs,Wn,Zt,ft,At,xi,ns,xe,Ce,hi,$o,Ko,ce,rs,Ci,Vo,Jn,zo,Qn,qn,ks,tn=class Mr extends uy{static install(t){at=t.THREE,Ho=Object.freeze(new at.Vector3(0,0,0)),Fs=Object.freeze(new at.Vector3(0,1,0)),Wn=Object.freeze(new at.Vector3(0,0,1)),Zt=new at.Vector2,ft=new at.Vector3,At=new at.Vector3,xi=new at.Vector3,ns=new at.Vector3,xe=new at.Vector3,Ce=new at.Vector3,hi=new at.Vector3,$o=new at.Vector3,Ko=new at.Vector3,ce=new at.Spherical,rs=new at.Spherical,Ci=new at.Box3,Vo=new at.Box3,Jn=new at.Sphere,zo=new at.Quaternion,Qn=new at.Quaternion,qn=new at.Matrix4,ks=new at.Raycaster}static get ACTION(){return B}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=B.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=_i.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=(E,A,y,T)=>{let _,C;if(li(this._camera)){const S=ft.copy(this._camera.position).sub(this._target),I=this._camera.getEffectiveFOV()*es,L=S.length()*Math.tan(I*.5);_=this.truckSpeed*E*L/this._elementRect.height,C=this.truckSpeed*A*L/this._elementRect.height}else if(Je(this._camera)){const S=this._camera;_=this.truckSpeed*E*(S.right-S.left)/S.zoom/this._elementRect.width,C=this.truckSpeed*A*(S.top-S.bottom)/S.zoom/this._elementRect.height}else return;T?(y?this.setFocalOffset(this._focalOffsetEnd.x+_,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(_,0,!0),this.forward(-C,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+_,this._focalOffsetEnd.y+C,this._focalOffsetEnd.z,!0):this.truck(_,C,!0)},this._rotateInternal=(E,A)=>{const y=Si*this.azimuthRotateSpeed*E/this._elementRect.height,T=Si*this.polarRotateSpeed*A/this._elementRect.height;this.rotate(y,T,!0)},this._dollyInternal=(E,A,y)=>{const T=Math.pow(.95,-E*this.dollySpeed),_=this._sphericalEnd.radius,C=this._sphericalEnd.radius*T,S=Ae(C,this.minDistance,this.maxDistance),I=S-C;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(C,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(I,!0),this._dollyToNoClamp(S,!0)):this._dollyToNoClamp(S,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?C:S)-_,this._dollyControlCoord.set(A,y)),this._lastDollyDirection=Math.sign(-E)},this._zoomInternal=(E,A,y)=>{const T=Math.pow(.95,E*this.dollySpeed),_=this._zoom,C=this._zoom*T;this.zoomTo(C,!0),this.dollyToCursor&&(this._changedZoom+=C-_,this._dollyControlCoord.set(A,y))},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,Fs),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=B.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(ft.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:B.ROTATE,middle:B.DOLLY,right:B.TRUCK,wheel:li(this._camera)?B.DOLLY:Je(this._camera)?B.ZOOM:B.NONE},this.touches={one:B.TOUCH_ROTATE,two:li(this._camera)?B.TOUCH_DOLLY_TRUCK:Je(this._camera)?B.TOUCH_ZOOM_TRUCK:B.NONE,three:B.TOUCH_TRUCK};const i=new at.Vector2,s=new at.Vector2,n=new at.Vector2,r=E=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const T=this._domElement.getBoundingClientRect(),_=E.clientX/T.width,C=E.clientY/T.height;if(_<this._interactiveArea.left||_>this._interactiveArea.right||C<this._interactiveArea.top||C>this._interactiveArea.bottom)return}const A=E.pointerType!=="mouse"?null:(E.buttons&Ot.LEFT)===Ot.LEFT?Ot.LEFT:(E.buttons&Ot.MIDDLE)===Ot.MIDDLE?Ot.MIDDLE:(E.buttons&Ot.RIGHT)===Ot.RIGHT?Ot.RIGHT:null;if(A!==null){const T=this._findPointerByMouseButton(A);T&&this._disposePointer(T)}if((E.buttons&Ot.LEFT)===Ot.LEFT&&this._lockedPointer)return;const y={pointerId:E.pointerId,clientX:E.clientX,clientY:E.clientY,deltaX:0,deltaY:0,mouseButton:A};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",h),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",h),this._isDragging=!0,d(E)},o=E=>{E.cancelable&&E.preventDefault();const A=E.pointerId,y=this._lockedPointer||this._findPointerById(A);if(y){if(y.clientX=E.clientX,y.clientY=E.clientY,y.deltaX=E.movementX,y.deltaY=E.movementY,this._state=0,E.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&&(E.buttons&Ot.LEFT)===Ot.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(E.buttons&Ot.MIDDLE)===Ot.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(E.buttons&Ot.RIGHT)===Ot.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},h=E=>{const A=this._findPointerById(E.pointerId);if(!(A&&A===this._lockedPointer)){if(A&&this._disposePointer(A),E.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=B.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=B.NONE;m()}};let l=-1;const c=E=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===B.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const C=this._domElement.getBoundingClientRect(),S=E.clientX/C.width,I=E.clientY/C.height;if(S<this._interactiveArea.left||S>this._interactiveArea.right||I<this._interactiveArea.top||I>this._interactiveArea.bottom)return}if(E.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===B.ROTATE||this.mouseButtons.wheel===B.TRUCK){const C=performance.now();l-C<1e3&&this._getClientRect(this._elementRect),l=C}const A=fy?-1:-3,y=E.deltaMode===1||E.ctrlKey?E.deltaY/A:E.deltaY/(A*10),T=this.dollyToCursor?(E.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,_=this.dollyToCursor?(E.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case B.ROTATE:{this._rotateInternal(E.deltaX,E.deltaY),this._isUserControllingRotate=!0;break}case B.TRUCK:{this._truckInternal(E.deltaX,E.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case B.SCREEN_PAN:{this._truckInternal(E.deltaX,E.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case B.OFFSET:{this._truckInternal(E.deltaX,E.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case B.DOLLY:{this._dollyInternal(-y,T,_),this._isUserControllingDolly=!0;break}case B.ZOOM:{this._zoomInternal(-y,T,_),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=E=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Mr.ACTION.NONE){const A=E instanceof PointerEvent?E.pointerId:0,y=this._findPointerById(A);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",h);return}E.preventDefault()}},d=E=>{if(!this._enabled)return;if(Yn(this._activePointers,Zt),this._getClientRect(this._elementRect),i.copy(Zt),s.copy(Zt),this._activePointers.length>=2){const y=Zt.x-this._activePointers[1].clientX,T=Zt.y-this._activePointers[1].clientY,_=Math.sqrt(y*y+T*T);n.set(0,_);const C=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,S=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(C,S)}if(this._state=0,!E)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in E&&E.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&&(E.buttons&Ot.LEFT)===Ot.LEFT&&(this._state=this._state|this.mouseButtons.left),(E.buttons&Ot.MIDDLE)===Ot.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(E.buttons&Ot.RIGHT)===Ot.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&B.ROTATE)===B.ROTATE||(this._state&B.TOUCH_ROTATE)===B.TOUCH_ROTATE||(this._state&B.TOUCH_DOLLY_ROTATE)===B.TOUCH_DOLLY_ROTATE||(this._state&B.TOUCH_ZOOM_ROTATE)===B.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&B.TRUCK)===B.TRUCK||(this._state&B.SCREEN_PAN)===B.SCREEN_PAN||(this._state&B.TOUCH_TRUCK)===B.TOUCH_TRUCK||(this._state&B.TOUCH_SCREEN_PAN)===B.TOUCH_SCREEN_PAN||(this._state&B.TOUCH_DOLLY_TRUCK)===B.TOUCH_DOLLY_TRUCK||(this._state&B.TOUCH_DOLLY_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN||(this._state&B.TOUCH_ZOOM_TRUCK)===B.TOUCH_ZOOM_TRUCK||(this._state&B.TOUCH_ZOOM_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&B.DOLLY)===B.DOLLY||(this._state&B.TOUCH_DOLLY)===B.TOUCH_DOLLY||(this._state&B.TOUCH_DOLLY_TRUCK)===B.TOUCH_DOLLY_TRUCK||(this._state&B.TOUCH_DOLLY_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN||(this._state&B.TOUCH_DOLLY_OFFSET)===B.TOUCH_DOLLY_OFFSET||(this._state&B.TOUCH_DOLLY_ROTATE)===B.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&B.ZOOM)===B.ZOOM||(this._state&B.TOUCH_ZOOM)===B.TOUCH_ZOOM||(this._state&B.TOUCH_ZOOM_TRUCK)===B.TOUCH_ZOOM_TRUCK||(this._state&B.TOUCH_ZOOM_SCREEN_PAN)===B.TOUCH_ZOOM_SCREEN_PAN||(this._state&B.TOUCH_ZOOM_OFFSET)===B.TOUCH_ZOOM_OFFSET||(this._state&B.TOUCH_ZOOM_ROTATE)===B.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&B.OFFSET)===B.OFFSET||(this._state&B.TOUCH_OFFSET)===B.TOUCH_OFFSET||(this._state&B.TOUCH_DOLLY_OFFSET)===B.TOUCH_DOLLY_OFFSET||(this._state&B.TOUCH_ZOOM_OFFSET)===B.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Yn(this._activePointers,Zt);const A=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=A?-A.deltaX:s.x-Zt.x,T=A?-A.deltaY:s.y-Zt.y;if(s.copy(Zt),((this._state&B.ROTATE)===B.ROTATE||(this._state&B.TOUCH_ROTATE)===B.TOUCH_ROTATE||(this._state&B.TOUCH_DOLLY_ROTATE)===B.TOUCH_DOLLY_ROTATE||(this._state&B.TOUCH_ZOOM_ROTATE)===B.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,T),this._isUserControllingRotate=!0),(this._state&B.DOLLY)===B.DOLLY||(this._state&B.ZOOM)===B.ZOOM){const _=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,C=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,S=this.dollyDragInverted?-1:1;(this._state&B.DOLLY)===B.DOLLY?(this._dollyInternal(S*T*Os,_,C),this._isUserControllingDolly=!0):(this._zoomInternal(S*T*Os,_,C),this._isUserControllingZoom=!0)}if((this._state&B.TOUCH_DOLLY)===B.TOUCH_DOLLY||(this._state&B.TOUCH_ZOOM)===B.TOUCH_ZOOM||(this._state&B.TOUCH_DOLLY_TRUCK)===B.TOUCH_DOLLY_TRUCK||(this._state&B.TOUCH_ZOOM_TRUCK)===B.TOUCH_ZOOM_TRUCK||(this._state&B.TOUCH_DOLLY_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN||(this._state&B.TOUCH_ZOOM_SCREEN_PAN)===B.TOUCH_ZOOM_SCREEN_PAN||(this._state&B.TOUCH_DOLLY_OFFSET)===B.TOUCH_DOLLY_OFFSET||(this._state&B.TOUCH_ZOOM_OFFSET)===B.TOUCH_ZOOM_OFFSET||(this._state&B.TOUCH_DOLLY_ROTATE)===B.TOUCH_DOLLY_ROTATE||(this._state&B.TOUCH_ZOOM_ROTATE)===B.TOUCH_ZOOM_ROTATE){const _=Zt.x-this._activePointers[1].clientX,C=Zt.y-this._activePointers[1].clientY,S=Math.sqrt(_*_+C*C),I=n.y-S;n.set(0,S);const L=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,b=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&B.TOUCH_DOLLY)===B.TOUCH_DOLLY||(this._state&B.TOUCH_DOLLY_ROTATE)===B.TOUCH_DOLLY_ROTATE||(this._state&B.TOUCH_DOLLY_TRUCK)===B.TOUCH_DOLLY_TRUCK||(this._state&B.TOUCH_DOLLY_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN||(this._state&B.TOUCH_DOLLY_OFFSET)===B.TOUCH_DOLLY_OFFSET?(this._dollyInternal(I*Os,L,b),this._isUserControllingDolly=!0):(this._zoomInternal(I*Os,L,b),this._isUserControllingZoom=!0)}((this._state&B.TRUCK)===B.TRUCK||(this._state&B.TOUCH_TRUCK)===B.TOUCH_TRUCK||(this._state&B.TOUCH_DOLLY_TRUCK)===B.TOUCH_DOLLY_TRUCK||(this._state&B.TOUCH_ZOOM_TRUCK)===B.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,T,!1,!1),this._isUserControllingTruck=!0),((this._state&B.SCREEN_PAN)===B.SCREEN_PAN||(this._state&B.TOUCH_SCREEN_PAN)===B.TOUCH_SCREEN_PAN||(this._state&B.TOUCH_DOLLY_SCREEN_PAN)===B.TOUCH_DOLLY_SCREEN_PAN||(this._state&B.TOUCH_ZOOM_SCREEN_PAN)===B.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,T,!1,!0),this._isUserControllingTruck=!0),((this._state&B.OFFSET)===B.OFFSET||(this._state&B.TOUCH_OFFSET)===B.TOUCH_OFFSET||(this._state&B.TOUCH_DOLLY_OFFSET)===B.TOUCH_DOLLY_OFFSET||(this._state&B.TOUCH_ZOOM_OFFSET)===B.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,T,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},m=()=>{Yn(this._activePointers,Zt),s.copy(Zt),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",h),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",h),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",p),this._domElement.ownerDocument.addEventListener("pointerlockerror",g),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",h),d())},this.unlockPointer=()=>{var E,A,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(E=this._domElement)===null||E===void 0||E.ownerDocument.exitPointerLock(),(A=this._domElement)===null||A===void 0||A.ownerDocument.removeEventListener("pointerlockchange",p),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",g),this.cancel()};const p=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},g=()=>{this.unlockPointer()};this._addAllEventListeners=E=>{this._domElement=E,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",h),this._domElement.addEventListener("wheel",c,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",h),this._domElement.removeEventListener("wheel",c,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",h),this._domElement.ownerDocument.removeEventListener("pointerlockchange",p),this._domElement.ownerDocument.removeEventListener("pointerlockerror",g))},this.cancel=()=>{this._state!==B.NONE&&(this._state=B.NONE,this._activePointers.length=0,m())},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=Ae(t.width,0,1),this._interactiveArea.height=Ae(t.height,0,1),this._interactiveArea.x=Ae(t.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ae(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=Ae(t,this.minAzimuthAngle,this.maxAzimuthAngle),n=Ae(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||St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(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=_i.NONE,this._changedDolly=0,this._dollyToNoClamp(Ae(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=St(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||St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(ns).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(t,e=!1){return this.zoomTo(this._zoomEnd+t,e)}zoomTo(t,e=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ae(t,this.minZoom,this.maxZoom),this._needsUpdate=!0,e||(this._zoom=this._zoomEnd);const i=!e||St(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(t,e,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(t,e,i)}truck(t,e,i=!1){this._camera.updateMatrix(),xe.setFromMatrixColumn(this._camera.matrix,0),Ce.setFromMatrixColumn(this._camera.matrix,1),xe.multiplyScalar(t),Ce.multiplyScalar(-e);const s=ft.copy(xe).add(Ce),n=At.copy(this._targetEnd).add(s);return this.moveTo(n.x,n.y,n.z,i)}forward(t,e=!1){ft.setFromMatrixColumn(this._camera.matrix,0),ft.crossVectors(this._camera.up,ft),ft.multiplyScalar(t);const i=At.copy(this._targetEnd).add(ft);return this.moveTo(i.x,i.y,i.z,e)}elevate(t,e=!1){return ft.copy(this._camera.up).multiplyScalar(t),this.moveTo(this._targetEnd.x+ft.x,this._targetEnd.y+ft.y,this._targetEnd.z+ft.z,e)}moveTo(t,e,i,s=!1){this._isUserControllingTruck=!1;const n=ft.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||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(t,e,i,s=!1){const o=ft.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 h=[],l=t.isBox3?Ci.copy(t):Ci.setFromObject(t);l.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const c=No(this._sphericalEnd.theta,Uo),u=No(this._sphericalEnd.phi,Uo);h.push(this.rotateTo(c,u,e));const d=ft.setFromSpherical(this._sphericalEnd).normalize(),f=zo.setFromUnitVectors(d,Wn),m=St(Math.abs(d.y),1);m&&f.multiply(Qn.setFromAxisAngle(Fs,c)),f.multiply(this._yAxisUpSpaceInverse);const p=Vo.makeEmpty();At.copy(l.min).applyQuaternion(f),p.expandByPoint(At),At.copy(l.min).setX(l.max.x).applyQuaternion(f),p.expandByPoint(At),At.copy(l.min).setY(l.max.y).applyQuaternion(f),p.expandByPoint(At),At.copy(l.max).setZ(l.min.z).applyQuaternion(f),p.expandByPoint(At),At.copy(l.min).setZ(l.max.z).applyQuaternion(f),p.expandByPoint(At),At.copy(l.max).setY(l.min.y).applyQuaternion(f),p.expandByPoint(At),At.copy(l.max).setX(l.min.x).applyQuaternion(f),p.expandByPoint(At),At.copy(l.max).applyQuaternion(f),p.expandByPoint(At),p.min.x-=s,p.min.y-=r,p.max.x+=n,p.max.y+=o,f.setFromUnitVectors(Wn,d),m&&f.premultiply(Qn.invert()),f.premultiply(this._yAxisUpSpace);const g=p.getSize(ft),E=p.getCenter(At).applyQuaternion(f);if(li(this._camera)){const A=this.getDistanceToFitBox(g.x,g.y,g.z,i);h.push(this.moveTo(E.x,E.y,E.z,e)),h.push(this.dollyTo(A,e)),h.push(this.setFocalOffset(0,0,0,e))}else if(Je(this._camera)){const A=this._camera,y=A.right-A.left,T=A.top-A.bottom,_=i?Math.max(y/g.x,T/g.y):Math.min(y/g.x,T/g.y);h.push(this.moveTo(E.x,E.y,E.z,e)),h.push(this.zoomTo(_,e)),h.push(this.setFocalOffset(0,0,0,e))}return Promise.all(h)}fitToSphere(t,e){const i=[],n="isObject3D"in t?Mr.createBoundingSphere(t,Jn):Jn.copy(t);if(i.push(this.moveTo(n.center.x,n.center.y,n.center.z,e)),li(this._camera)){const r=this.getDistanceToFitSphere(n.radius);i.push(this.dollyTo(r,e))}else if(Je(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,h=2*n.radius,l=Math.min(r/h,o/h);i.push(this.zoomTo(l,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=_i.NONE,this._changedDolly=0;const h=At.set(s,n,r),l=ft.set(t,e,i);this._targetEnd.copy(h),this._sphericalEnd.setFromVector3(l.sub(h).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const c=!o||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold)&&St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(c)}lerpLookAt(t,e,i,s,n,r,o,h,l,c,u,d,f,m=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=_i.NONE,this._changedDolly=0;const p=ft.set(s,n,r),g=At.set(t,e,i);ce.setFromVector3(g.sub(p).applyQuaternion(this._yAxisUpSpace));const E=xi.set(c,u,d),A=At.set(o,h,l);rs.setFromVector3(A.sub(E).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(p.lerp(E,f));const y=rs.theta-ce.theta,T=rs.phi-ce.phi,_=rs.radius-ce.radius;this._sphericalEnd.set(ce.radius+_*f,ce.phi+T*f,ce.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,m||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const C=!m||St(this._target.x,this._targetEnd.x,this.restThreshold)&&St(this._target.y,this._targetEnd.y,this.restThreshold)&&St(this._target.z,this._targetEnd.z,this.restThreshold)&&St(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&St(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&St(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(C)}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(ft),r=this.setLookAt(n.x,n.y,n.z,t,e,i,s);return this._sphericalEnd.phi=Ae(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||St(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&St(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&St(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(t,e,i){this._camera.updateMatrixWorld(),xe.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Ce.setFromMatrixColumn(this._camera.matrixWorldInverse,1),hi.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ft.set(t,e,i),n=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);xe.multiplyScalar(r.x),Ce.multiplyScalar(r.y),hi.multiplyScalar(r.z),ft.copy(xe).add(Ce).add(hi),ft.z=ft.z+n,this.dollyTo(n,!1),this.setFocalOffset(-ft.x,ft.y,-ft.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(Xn(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=t/e,r=this._camera.getEffectiveFOV()*es,o=this._camera.aspect;return((s?n>o:n<o)?e:t/o)*.5/Math.tan(r*.5)+i*.5}getDistanceToFitSphere(t){if(Xn(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*es,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%Si,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Si),this._spherical.theta+=Si*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Si)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!St(this._camera.up.x,this._cameraUp0.x)||!St(this._camera.up.y,this._cameraUp0.y)||!St(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const i=this.getPosition(ft);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,Fs),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const t=ft.subVectors(this._target,this._camera.position).normalize(),e=At.crossVectors(t,this._camera.up);this._camera.up.crossVectors(e,t).normalize(),this._camera.updateMatrixWorld();const i=this.getPosition(ft);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=$o.subVectors(this._targetEnd,this._target),r=Ko.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Dt(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Bs(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,t),this._needsUpdate=!0}if(Dt(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Bs(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,t),this._needsUpdate=!0}if(Dt(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Bs(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,t),this._needsUpdate=!0}if(Dt(n.x)&&Dt(n.y)&&Dt(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Go(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(Dt(r.x)&&Dt(r.y)&&Dt(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Go(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(Dt(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Bs(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,t)}if(this.dollyToCursor){if(li(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,d=this._camera,f=this._getCameraDirection(ns),m=ft.copy(f).cross(d.up).normalize();m.lengthSq()===0&&(m.x=1);const p=At.crossVectors(m,f),g=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*es*.5),A=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,y=xi.copy(this._targetEnd).add(m.multiplyScalar(this._dollyControlCoord.x*g*d.aspect)).add(p.multiplyScalar(this._dollyControlCoord.y*g)),T=ft.copy(this._targetEnd).lerp(y,A),_=this._lastDollyDirection===_i.IN&&this._spherical.radius<=this.minDistance,C=this._lastDollyDirection===_i.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(_||C)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const I=At.copy(f).multiplyScalar(-u);T.add(I)}this._boundary.clampPoint(T,T);const S=At.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(S),this._changedDolly-=u,Dt(this._changedDolly)&&(this._changedDolly=0)}else if(Je(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,d=this._camera,f=ft.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),m=At.set(0,0,-1).applyQuaternion(d.quaternion),p=xi.copy(f).add(m.multiplyScalar(-f.dot(d.up))),E=-(this._zoom-u-this._zoom)/this._zoom,A=this._getCameraDirection(ns),y=this._targetEnd.dot(A),T=ft.copy(this._targetEnd).lerp(p,E),_=T.dot(A),C=A.multiplyScalar(_-y);T.sub(C),this._boundary.clampPoint(T,T);const S=At.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(S),this._changedZoom-=u,Dt(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const h=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,h),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!Dt(this._focalOffset.x)||!Dt(this._focalOffset.y)||!Dt(this._focalOffset.z))&&(xe.setFromMatrixColumn(this._camera.matrix,0),Ce.setFromMatrixColumn(this._camera.matrix,1),hi.setFromMatrixColumn(this._camera.matrix,2),xe.multiplyScalar(this._focalOffset.x),Ce.multiplyScalar(-this._focalOffset.y),hi.multiplyScalar(this._focalOffset.z),ft.copy(xe).add(Ce).add(hi),this._camera.position.add(ft),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),ft.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const c=this._needsUpdate;return c&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):c?(this.dispatchEvent({type:"update"}),Dt(e,this.restThreshold)&&Dt(i,this.restThreshold)&&Dt(s,this.restThreshold)&&Dt(n.x,this.restThreshold)&&Dt(n.y,this.restThreshold)&&Dt(n.z,this.restThreshold)&&Dt(r.x,this.restThreshold)&&Dt(r.y,this.restThreshold)&&Dt(r.z,this.restThreshold)&&Dt(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!c&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=c,this._needsUpdate=!1,c}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:is(this.maxDistance),minZoom:this.minZoom,maxZoom:is(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:is(this.maxPolarAngle),minAzimuthAngle:is(this.minAzimuthAngle),maxAzimuthAngle:is(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:ft.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=ss(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=ss(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=ss(i.maxPolarAngle),this.minAzimuthAngle=ss(i.minAzimuthAngle),this.maxAzimuthAngle=ss(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(ft.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",dy),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=At.copy(e).add(t),o=this._boundary.clampPoint(n,xi).sub(n),h=o.lengthSq();if(h===0)return t.add(e);if(h===s)return t;if(i===0)return t.add(e).add(o);{const l=1+i*h/e.dot(o);return t.add(At.copy(e).multiplyScalar(l)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(li(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*es,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(Je(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)||Xn(this._camera,"_collisionTest"))return t;const i=this._getTargetDirection(ns);qn.lookAt(Ho,i,this._camera.up);for(let s=0;s<4;s++){const n=At.copy(this._nearPlaneCorners[s]);n.applyMatrix4(qn);const r=xi.addVectors(this._target,n);ks.set(r,i),ks.far=this._spherical.radius+1;const o=ks.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;Ci.makeEmpty(),t.traverseVisible(r=>{r.isMesh&&Ci.expandByObject(r)}),Ci.getCenter(s);let n=0;return t.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const h=o.geometry.clone();h.applyMatrix4(o.matrixWorld);const c=h.attributes.position;for(let u=0,d=c.count;u<d;u++)ft.fromBufferAttribute(c,u),n=Math.max(n,s.distanceToSquared(ft))}),i.radius=Math.sqrt(n),i}};const my=x.forwardRef((a,t)=>{x.useMemo(()=>{const H={Box3:ph,MathUtils:{clamp:ot.clamp},Matrix4:mt,Quaternion:yt,Raycaster:xn,Sphere:ea,Spherical:Zr,Vector2:Kt,Vector3:k,Vector4:ze};tn.install({THREE:H}),yh({CameraControlsImpl:tn})},[]);const{camera:e,domElement:i,makeDefault:s,onControlStart:n,onControl:r,onControlEnd:o,onTransitionStart:h,onUpdate:l,onWake:c,onRest:u,onSleep:d,onStart:f,onEnd:m,onChange:p,regress:g,...E}=a,A=Q(H=>H.camera),y=Q(H=>H.gl),T=Q(H=>H.invalidate),_=Q(H=>H.events),C=Q(H=>H.setEvents),S=Q(H=>H.set),I=Q(H=>H.get),L=Q(H=>H.performance),b=e||A,w=i||_.connected||y.domElement,O=x.useMemo(()=>new tn(b),[b]);return Ut((H,Y)=>{O.update(Y)},-1),x.useEffect(()=>(O.connect(w),()=>void O.disconnect()),[w,O]),x.useEffect(()=>{function H(){T(),g&&L.regress()}const Y=V=>{H(),n==null||n(V),f==null||f(V)},$=V=>{H(),r==null||r(V),p==null||p(V)},z=V=>{o==null||o(V),m==null||m(V)},W=V=>{H(),h==null||h(V),p==null||p(V)},J=V=>{H(),l==null||l(V),p==null||p(V)},G=V=>{H(),c==null||c(V),p==null||p(V)},U=V=>{u==null||u(V)},K=V=>{d==null||d(V)};return O.addEventListener("controlstart",Y),O.addEventListener("control",$),O.addEventListener("controlend",z),O.addEventListener("transitionstart",W),O.addEventListener("update",J),O.addEventListener("wake",G),O.addEventListener("rest",U),O.addEventListener("sleep",K),()=>{O.removeEventListener("controlstart",Y),O.removeEventListener("control",$),O.removeEventListener("controlend",z),O.removeEventListener("transitionstart",W),O.removeEventListener("update",J),O.removeEventListener("wake",G),O.removeEventListener("rest",U),O.removeEventListener("sleep",K)}},[O,T,C,g,L,n,r,o,h,l,c,u,d,p,f,m]),x.useEffect(()=>{if(s){const H=I().controls;return S({controls:O}),()=>S({controls:H})}},[s,O]),x.createElement("primitive",wt({ref:t,object:O},E))}),py=a=>(a==null?void 0:a.current)instanceof qt,jh=x.createContext(null);function Wh(){const a=x.useContext(jh);if(!a)throw new Error("useMotion hook must be used in a MotionPathControls component.");return a}function gy({points:a=50,color:t="black"}){const{path:e}=Wh(),[i,s]=x.useState([]),n=x.useMemo(()=>new ta({color:t}),[t]),r=x.useMemo(()=>new mh(.025,16,16),[]),o=x.useRef([]);return x.useEffect(()=>{e.curves!==o.current&&(s(e.getPoints(a)),o.current=e.curves)}),i.map((h,l)=>x.createElement("mesh",{key:l,material:n,geometry:r,position:[h.x,h.y,h.z]}))}const Ey=x.forwardRef(({children:a,curves:t=[],debug:e=!1,debugColor:i="black",object:s,focus:n,loop:r=!0,offset:o=void 0,smooth:h=!1,eps:l=1e-5,damping:c=.1,focusDamping:u=.1,maxSpeed:d=1/0,...f},m)=>{const{camera:p}=Q(),g=x.useRef(null),E=x.useRef(o??0),A=x.useMemo(()=>new md,[]),y=x.useMemo(()=>({focus:n,object:(s==null?void 0:s.current)instanceof qt?s:{current:p},path:A,current:E.current,offset:E.current,point:new k,tangent:new k,next:new k}),[n,s]),T=pd(g);x.useLayoutEffect(()=>{const C=T.current;A.curves=[];const S=t.length>0?t:C.children.map(I=>I.object);for(let I=0;I<S.length;I++)A.add(S[I]);if(h){const I=A.getPoints(typeof h=="number"?h:1),L=new gd(I);A.curves=[L]}A.updateArcLengths()}),x.useImperativeHandle(m,()=>Object.assign(g.current,{motion:y}),[y]),x.useLayoutEffect(()=>{E.current=Rs.repeat(E.current,1)},[o]);const _=x.useMemo(()=>new k,[]);return Ut((C,S)=>{const I=y.offset;if(ti.damp(E,"current",o!==void 0?o:y.current,c,S,d,void 0,l),y.offset=r?Rs.repeat(E.current,1):Rs.clamp(E.current,0,1),A.getCurveLengths().length>0){A.getPointAt(y.offset,y.point),A.getTangentAt(y.offset,y.tangent).normalize(),A.getPointAt(Rs.repeat(E.current-(I-y.offset),1),y.next);const L=(s==null?void 0:s.current)instanceof qt?s.current:p;L.position.copy(y.point),n&&ti.dampLookAt(L,py(n)?n.current.getWorldPosition(_):n,u,S,d,void 0,l)}}),x.createElement("group",wt({ref:g},f),x.createElement(jh.Provider,{value:y},a,e&&x.createElement(gy,{color:i})))});function fa(a,{path:t}){const[e]=Se(vh,[a],i=>i.setPath(t));return e}fa.preload=(a,{path:t})=>Se.preload(vh,[a],e=>e.setPath(t));function yy({children:a,files:t,...e}){const i=fa(t,{...e});return x.createElement(x.Fragment,null,a==null?void 0:a(i))}function bn(a){return Se(da,a)}bn.preload=a=>Se.preload(da,a);bn.clear=a=>Se.clear(da,a);function vy({path:a,...t}){const i=bn(a).children[0];return x.createElement(ia,wt({},t,{object:i}))}const Jh="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master";function In(a,t=`${Jh}/basis/`){const e=Q(s=>s.gl),i=Se(na,Rr(a)?Object.values(a):a,s=>{s.detectSupport(e),s.setTranscoderPath(t)});if(x.useEffect(()=>{(Array.isArray(i)?i:[i]).forEach(e.initTexture)},[e,i]),Rr(a)){const s=Object.keys(a),n={};return s.forEach(r=>Object.assign(n,{[r]:i[s.indexOf(r)]})),n}else return i}In.preload=(a,t=`${Jh}/basis/`)=>Se.preload(na,a,e=>{e.setTranscoderPath(t)});In.clear=a=>Se.clear(na,a);const Ay=({children:a,input:t,basisPath:e})=>{const i=In(t,e);return x.createElement(x.Fragment,null,a==null?void 0:a(i))},q=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Ty=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=_y},_y=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}({}),P=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}({}),v=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 pt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class bi{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 Sy{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 bi(t),this.fast_=new bi(e),this.defaultTTFB_=s,this.ttfb_=new bi(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new bi(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new bi(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new bi(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 xy(a,t,e){return(t=by(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function bt(){return bt=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},bt.apply(null,arguments)}function Yo(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 xt(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Yo(Object(e),!0).forEach(function(i){xy(a,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Yo(Object(e)).forEach(function(i){Object.defineProperty(a,i,Object.getOwnPropertyDescriptor(e,i))})}return a}function Cy(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 by(a){var t=Cy(a,"string");return typeof t=="symbol"?t:t+""}class Ye{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=Qe,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 Qe=function(){},Iy={trace:Qe,debug:Qe,log:Qe,warn:Qe,info:Qe,error:Qe};function Br(){return bt({},Iy)}function Ly(a,t){const e=self.console[a];return e?e.bind(self.console,`${t?"["+t+"] ":""}[${a}] >`):Qe}function Xo(a,t,e){return t[a]?t[a].bind(t):Ly(a,e)}const Or=Br();function Ry(a,t,e){const i=Br();if(typeof console=="object"&&a===!0||typeof a=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Xo(n,a,e)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.5`)}catch{return Br()}s.forEach(n=>{Or[n]=Xo(n,a)})}else bt(Or,i);return i}const Tt=Or;function Ve(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Dy(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Qh(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 l=new TextDecoder("utf-8").decode(a);if(t){const c=l.indexOf("\0");return c!==-1?l.substring(0,c):l}return l.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 Re={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 Py(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Zn={exports:{}},jo;function wy(){return jo||(jo=1,function(a,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(h,l,c){if(c=c||{},h=h.trim(),l=l.trim(),!l){if(!c.alwaysNormalize)return h;var u=o.parseURL(h);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return c.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(h);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=s.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var g=f.path,E=g.substring(0,g.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(h){var l=i.exec(h);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(h){for(h=h.split("").reverse().join("").replace(n,"");h.length!==(h=h.replace(r,"")).length;);return h.split("").reverse().join("")},buildURLFromParts:function(h){return h.scheme+h.netLoc+h.path+h.params+h.query+h.fragment}};a.exports=o})()}(Zn)),Zn.exports}var ma=wy();class Ln{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 Rt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class pa{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,My(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={[Rt.AUDIO]:null,[Rt.VIDEO]:null,[Rt.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 Ln),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ma.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Rt.AUDIO]=null,t[Rt.VIDEO]=null,t[Rt.AUDIOVIDEO]=null}}function jt(a){return a.sn!=="initSegment"}class en extends pa{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(q(t)&&q(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=q(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(!q(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return jt(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,h=o[t];if(!h){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:r};return}h.startPTS=Math.min(h.startPTS,e),h.endPTS=Math.max(h.endPTS,i),h.startDTS=Math.min(h.startDTS,s),h.endDTS=Math.max(h.endDTS,n)}}class qh extends pa{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 Zh(a,t){const e=Object.getPrototypeOf(a);if(e){const i=Object.getOwnPropertyDescriptor(e,t);return i||Zh(e,t)}}function My(a,t){const e=Zh(a,t);e&&(e.enumerable=!0,Object.defineProperty(a,t,e))}const fn=Math.pow(2,32)-1,By=[].push,tc={video:1,audio:2,id3:3,text:4};function $t(a){return String.fromCharCode.apply(null,a)}function ec(a,t){const e=a[t]<<8|a[t+1];return e<0?65536+e:e}function rt(a,t){const e=ic(a,t);return e<0?4294967296+e:e}function Wo(a,t){let e=rt(a,t);return e*=Math.pow(2,32),e+=rt(a,t+4),e}function ic(a,t){return a[t]<<24|a[t+1]<<16|a[t+2]<<8|a[t+3]}function tr(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 Oy(a){const t=a.byteLength;for(let e=0;e<t;){const i=rt(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 dt(a,t){const e=[];if(!t.length)return e;const i=a.byteLength;for(let s=0;s<i;){const n=rt(a,s),r=$t(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 h=dt(a.subarray(s+8,o),t.slice(1));h.length&&By.apply(e,h)}s=o}return e}function Fy(a){const t=[],e=a[0];let i=8;const s=rt(a,i);i+=4;let n=0,r=0;e===0?(n=rt(a,i),r=rt(a,i+4),i+=8):(n=Wo(a,i),r=Wo(a,i+8),i+=16),i+=2;let o=a.length+r;const h=ec(a,i);i+=2;for(let l=0;l<h;l++){let c=i;const u=rt(a,c);c+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return Tt.warn("SIDX has hierarchical references (not supported)"),null;const m=rt(a,c);c+=4,t.push({referenceSize:d,subsegmentDuration:m,info:{duration:m/s,start:o,end:o+d-1}}),o+=d,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:e,referencesCount:h,references:t}}function sc(a){const t=[],e=dt(a,["moov","trak"]);for(let s=0;s<e.length;s++){const n=e[s],r=dt(n,["tkhd"])[0];if(r){let o=r[0];const h=rt(r,o===0?12:20),l=dt(n,["mdia","mdhd"])[0];if(l){o=l[0];const c=rt(l,o===0?12:20),u=dt(n,["mdia","hdlr"])[0];if(u){const d=$t(u.subarray(8,12)),f={soun:Rt.AUDIO,vide:Rt.VIDEO}[d],m=dt(n,["mdia","minf","stbl","stsd"])[0],p=ky(m);f?(t[h]={timescale:c,type:f,stsd:p},t[f]=xt({timescale:c,id:h},p)):t[h]={timescale:c,type:d,stsd:p}}}}}return dt(a,["moov","mvex","trex"]).forEach(s=>{const n=rt(s,4),r=t[n];r&&(r.default={duration:rt(s,12),flags:rt(s,20)})}),t}function ky(a){const t=a.subarray(8),e=t.subarray(86),i=$t(t.subarray(4,8));let s=i,n;const r=i==="enca"||i==="encv";if(r){const l=dt(t,[i])[0].subarray(i==="enca"?28:78);dt(l,["sinf"]).forEach(u=>{const d=dt(u,["schm"])[0];if(d){const f=$t(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const m=dt(u,["frma"])[0];m&&(s=$t(m))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const h=dt(e,["avcC"])[0];h&&h.length>3&&(s+="."+Ns(h[1])+Ns(h[2])+Ns(h[3]),n=Us(o==="avc1"?"dva1":"dvav",e));break}case"mp4a":{const h=dt(t,[i])[0],l=dt(h.subarray(28),["esds"])[0];if(l&&l.length>7){let c=4;if(l[c++]!==3)break;c=er(l,c),c+=2;const u=l[c++];if(u&128&&(c+=2),u&64&&(c+=l[c++]),l[c++]!==4)break;c=er(l,c);const d=l[c++];if(d===64)s+="."+Ns(d);else break;if(c+=12,l[c++]!==5)break;c=er(l,c);const f=l[c++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((l[c]&224)>>5)),s+="."+m}break}case"hvc1":case"hev1":{const h=dt(e,["hvcC"])[0];if(h&&h.length>12){const l=h[1],c=["","A","B","C"][l>>6],u=l&31,d=rt(h,2),f=(l&32)>>5?"H":"L",m=h[12],p=h.subarray(6,12);s+="."+c+u,s+="."+Uy(d).toString(16).toUpperCase(),s+="."+f+m;let g="";for(let E=p.length;E--;){const A=p[E];(A||g)&&(g="."+A.toString(16).toUpperCase()+g)}s+=g}n=Us(o=="hev1"?"dvhe":"dvh1",e);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Us(s,e)||s;break}case"vp09":{const h=dt(e,["vpcC"])[0];if(h&&h.length>6){const l=h[4],c=h[5],u=h[6]>>4&15;s+="."+Ie(l)+"."+Ie(c)+"."+Ie(u)}break}case"av01":{const h=dt(e,["av1C"])[0];if(h&&h.length>2){const l=h[1]>>>5,c=h[1]&31,u=h[2]>>>7?"H":"M",d=(h[2]&64)>>6,f=(h[2]&32)>>5,m=l===2&&d?f?12:10:d?10:8,p=(h[2]&16)>>4,g=(h[2]&8)>>3,E=(h[2]&4)>>2,A=h[2]&3;s+="."+l+"."+Ie(c)+u+"."+Ie(m)+"."+p+"."+g+E+A+"."+Ie(1)+"."+Ie(1)+"."+Ie(1)+"."+0,n=Us("dav1",e)}break}}return{codec:s,encrypted:r,supplemental:n}}function Us(a,t){const e=dt(t,["dvvC"]),i=e.length?e[0]:dt(t,["dvcC"])[0];if(i){const s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return a+"."+Ie(s)+"."+Ie(n)}}function Uy(a){let t=0;for(let e=0;e<32;e++)t|=(a>>e&1)<<31-e;return t>>>0}function er(a,t){const e=t+5;for(;a[t++]&128&&t<e;);return t}function Ns(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Ie(a){return(a<10?"0":"")+a}function Ny(a,t){if(!a||!t)return a;const e=t.keyId;return e&&t.isCommonEncryption&&dt(a,["moov","trak"]).forEach(s=>{const r=dt(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=dt(r,["enca"]);const h=o.length>0;h||(o=dt(r,["encv"])),o.forEach(l=>{const c=h?l.subarray(28):l.subarray(78);dt(c,["sinf"]).forEach(d=>{const f=nc(d);if(f){const m=f.subarray(8,24);m.some(p=>p!==0)||(Tt.log(`[eme] Patching keyId in 'enc${h?"a":"v"}>sinf>>tenc' box: ${Re.hexDump(m)} -> ${Re.hexDump(e)}`),f.set(e,8))}})})}),a}function nc(a){const t=dt(a,["schm"])[0];if(t){const e=$t(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return dt(a,["schi","tenc"])[0]}return null}function Gy(a,t,e){const i={},s=dt(a,["moof","traf"]);for(let n=0;n<s.length;n++){const r=s[n],o=dt(r,["tfhd"])[0],h=rt(o,4),l=t[h];if(!l)continue;const c=i[h]||(i[h]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type}),u=dt(r,["tfdt"])[0];if(u){const y=u[0];let T=rt(u,4);y===1&&(T===fn?e.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=fn+1,T+=rt(u,8))),q(T)&&(!q(c.start)||T<c.start)&&(c.start=T)}const d=l.default,f=rt(o,0)|(d==null?void 0:d.flags);let m=(d==null?void 0:d.duration)||0;f&8&&(f&2?m=rt(o,12):m=rt(o,8));const p=dt(r,["trun"]);let g=c.start||0,E=0,A=m;for(let y=0;y<p.length;y++){const T=p[y],_=rt(T,4),C=c.sampleCount;c.sampleCount+=_;const S=T[3]&1,I=T[3]&4,L=T[2]&1,b=T[2]&2,w=T[2]&4,O=T[2]&8;let H=8,Y=_;for(S&&(H+=4),I&&_&&(!(T[H+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=C),H+=4,L?(A=rt(T,H),H+=4):A=m,b&&(H+=4),O&&(H+=4),g+=A,E+=A,Y--);Y--;)L?(A=rt(T,H),H+=4):A=m,b&&(H+=4),w&&(T[H+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(Y+1),c.keyFrameStart=g),H+=4),O&&(H+=4),g+=A,E+=A;!E&&m&&(E+=m*_)}c.duration+=E}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,r=0;const o=dt(a,["sidx"]);for(let h=0;h<o.length;h++){const l=Fy(o[h]);if(l!=null&&l.references){n=Math.min(n,l.earliestPresentationTime/l.timescale);const c=l.references.reduce((u,d)=>u+d.info.duration||0,0);r=Math.max(r,c+l.earliestPresentationTime/l.timescale)}}r&&q(r)&&Object.keys(i).forEach(h=>{i[h].duration||(i[h].duration=r*i[h].timescale-i[h].start)})}return i}function Hy(a,t,e){dt(t,["moof","traf"]).forEach(i=>{dt(i,["tfhd"]).forEach(s=>{const n=rt(s,4),r=a[n];if(!r)return;const o=r.timescale||9e4;dt(i,["tfdt"]).forEach(h=>{const l=h[0],c=e*o;if(c){let u=rt(h,4);if(l===0)u-=c,u=Math.max(u,0),tr(h,4,u);else{u*=Math.pow(2,32),u+=rt(h,8),u-=c,u=Math.max(u,0);const d=Math.floor(u/(fn+1)),f=Math.floor(u%(fn+1));tr(h,4,d),tr(h,8,f)}}})})})}function $y(a){const t={valid:null,remainder:null},e=dt(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 pe(a,t){const e=new Uint8Array(a.length+t.length);return e.set(a),e.set(t,a.length),e}function Jo(a,t){const e=[],i=t.samples,s=t.timescale,n=t.id;let r=!1;return dt(i,["moof"]).map(h=>{const l=h.byteOffset-8;dt(h,["traf"]).map(u=>{const d=dt(u,["tfdt"]).map(f=>{const m=f[0];let p=rt(f,4);return m===1&&(p*=Math.pow(2,32),p+=rt(f,8)),p/s})[0];return d!==void 0&&(a=d),dt(u,["tfhd"]).map(f=>{const m=rt(f,4),p=rt(f,0)&16777215,g=(p&1)!==0,E=(p&2)!==0,A=(p&8)!==0;let y=0;const T=(p&16)!==0;let _=0;const C=(p&32)!==0;let S=8;m===n&&(g&&(S+=8),E&&(S+=4),A&&(y=rt(f,S),S+=4),T&&(_=rt(f,S),S+=4),C&&(S+=4),t.type==="video"&&(r=Rn(t.codec)),dt(u,["trun"]).map(I=>{const L=I[0],b=rt(I,0)&16777215,w=(b&1)!==0;let O=0;const H=(b&4)!==0,Y=(b&256)!==0;let $=0;const z=(b&512)!==0;let W=0;const J=(b&1024)!==0,G=(b&2048)!==0;let U=0;const K=rt(I,4);let V=8;w&&(O=rt(I,V),V+=4),H&&(V+=4);let X=O+l;for(let R=0;R<K;R++){if(Y?($=rt(I,V),V+=4):$=y,z?(W=rt(I,V),V+=4):W=_,J&&(V+=4),G&&(L===0?U=rt(I,V):U=ic(I,V),V+=4),t.type===Rt.VIDEO){let tt=0;for(;tt<W;){const it=rt(i,X);if(X+=4,Ky(r,i[X])){const lt=i.subarray(X,X+it);ga(lt,r?2:1,a+U/s,e)}X+=it,tt+=it+4}}a+=$/s}}))})})}),e}function Rn(a){if(!a)return!1;const t=a.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Ky(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=rc(a);let n=0;n+=t;let r=0,o=0,h=0;for(;n<s.length;){r=0;do{if(n>=s.length)break;h=s[n++],r+=h}while(h===255);o=0;do{if(n>=s.length)break;h=s[n++],o+=h}while(h===255);const l=s.length-n;let c=n;if(o<l)n+=o;else if(o>l){Tt.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(r===4){if(s[c++]===181){const d=ec(s,c);if(c+=2,d===49){const f=rt(s,c);if(c+=4,f===1195456820){const m=s[c++];if(m===3){const p=s[c++],g=31&p,E=64&p,A=E?2+g*3:0,y=new Uint8Array(A);if(E){y[0]=p;for(let T=1;T<A;T++)y[T]=s[c++]}i.push({type:m,payloadType:r,pts:e,bytes:y})}}}}}else if(r===5&&o>16){const u=[];for(let m=0;m<16;m++){const p=s[c++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let m=0;m<d;m++)f[m]=s[c++];i.push({payloadType:r,pts:e,uuid:u.join(""),userData:ae(f),userDataBytes:f})}}}function rc(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 Vy(a){const t=a[0];let e="",i="",s=0,n=0,r=0,o=0,h=0,l=0;if(t===0){for(;$t(a.subarray(l,l+1))!=="\0";)e+=$t(a.subarray(l,l+1)),l+=1;for(e+=$t(a.subarray(l,l+1)),l+=1;$t(a.subarray(l,l+1))!=="\0";)i+=$t(a.subarray(l,l+1)),l+=1;i+=$t(a.subarray(l,l+1)),l+=1,s=rt(a,12),n=rt(a,16),o=rt(a,20),h=rt(a,24),l=28}else if(t===1){l+=4,s=rt(a,l),l+=4;const u=rt(a,l);l+=4;const d=rt(a,l);for(l+=4,r=2**32*u+d,Ty(r)||(r=Number.MAX_SAFE_INTEGER,Tt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=rt(a,l),l+=4,h=rt(a,l),l+=4;$t(a.subarray(l,l+1))!=="\0";)e+=$t(a.subarray(l,l+1)),l+=1;for(e+=$t(a.subarray(l,l+1)),l+=1;$t(a.subarray(l,l+1))!=="\0";)i+=$t(a.subarray(l,l+1)),l+=1;i+=$t(a.subarray(l,l+1)),l+=1}const c=a.subarray(l,a.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:r,presentationTimeDelta:n,eventDuration:o,id:h,payload:c}}function zy(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 Yy(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),zy([112,115,115,104],new Uint8Array([i,0,0,0]),a,n,s,r,e||new Uint8Array)}function Xy(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=jy(s);t.push(n),i+=n.size}}return t}function jy(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=Re.hexDump(new Uint8Array(r,e+12,16)),h=a.getUint32(28);let l=null,c=null;if(n===0){if(t-32<h||h<22)return{offset:e,size:t};c=new Uint8Array(r,e+32,h)}else if(n===1){if(!h||i<e+32+h*16+16)return{offset:e,size:t};l=[];for(let u=0;u<h;u++)l.push(new Uint8Array(r,e+32+u*16,16))}return{version:n,systemId:o,kids:l,data:c,offset:e,size:t}}const ac=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ki={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 oc(a,t){const e=ki[t];return!!e&&!!e[a.slice(0,4)]}function Fr(a,t,e=!0){return!a.split(",").some(i=>!lc(i,t,e))}function lc(a,t,e=!0){var i;const s=Ve(e);return(i=s==null?void 0:s.isTypeSupported(gs(a,t)))!=null?i:!1}function gs(a,t){return`${t}/mp4;codecs=${a}`}function Qo(a){if(a){const t=a.substring(0,4);return ki.video[t]}return 2}function mn(a){const t=ac();return a.split(",").reduce((e,i)=>{const n=t&&Rn(i)?9:ki.video[i];return n?(n*2+e)/(e?3:2):(ki.audio[i]+e)/(e?2:1)},0)}const ir={};function Wy(a,t=!0){if(ir[a])return ir[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(lc(e[s],"audio",t))return ir[a]=e[s],e[s];if(e[s]==="mp3"&&(i=Ve(t))!=null&&i.isTypeSupported("audio/mpeg"))return""}return a}const Jy=/flac|opus|mp4a\.40\.34/i;function pn(a,t=!0){return a.replace(Jy,e=>Wy(e.toLowerCase(),t))}function Qy(a,t){const e=[];if(a){const i=a.split(",");for(let s=0;s<i.length;s++)oc(i[s],"video")||e.push(i[s])}return t&&e.push(t),e.join(",")}function sn(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 qy(a){const t=a.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");i.length>2&&i[0]==="avc1"&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}function Zy(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 qo(a){const t=Ve(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 hc(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const cc={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function uc(a,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:a}}const Zo={};function tv(a,t,e,i,s,n){const r=a.audioCodec?a.audioGroups:null,o=n==null?void 0:n.audioCodec,h=n==null?void 0:n.channels,l=h?parseInt(h):o?1/0:2;let c=null;if(r!=null&&r.length)try{r.length===1&&r[0]?c=t.groups[r[0]].channels:c=r.reduce((u,d)=>{if(d){const f=t.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(m=>{u[m]=(u[m]||0)+f.channels[m]})}return u},{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))||!!c&&q(l)&&Object.keys(c).some(u=>parseInt(u)>l)}function dc(a,t,e){const i=a.videoCodec,s=a.audioCodec;if(!i&&!s||!e)return Promise.resolve(cc);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 h=i.split(","),l=navigator.userAgent;if(h.some(c=>Rn(c))&&ac())return Promise.resolve(uc(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${l})`),n));n.push.apply(n,h.map(c=>({type:"media-source",video:xt(xt({},r),{},{contentType:gs(Zy(c),"video")})})))}return s&&a.audioGroups&&a.audioGroups.forEach(r=>{var o;r&&((o=t.groups[r])==null||o.tracks.forEach(h=>{if(h.groupId===r){const l=h.channels||"",c=parseFloat(l);q(c)&&c>2&&n.push.apply(n,s.split(",").map(u=>({type:"media-source",audio:{contentType:gs(u,"audio"),channels:""+c}})))}}))}),Promise.all(n.map(r=>{const o=ev(r);return Zo[o]||(Zo[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 ev(a){const{audio:t,video:e}=a,i=e||t;if(i){const s=hc(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 kr=["NONE","TYPE-0","TYPE-1",null];function iv(a){return kr.indexOf(a)>-1}const gn=["SDR","PQ","HLG"];function sv(a){return!!a&&gn.indexOf(a)>-1}var ds={No:"",Yes:"YES",v2:"v2"};function tl(a){const{canSkipUntil:t,canSkipDateRanges:e,age:i}=a,s=i<t/2;return t&&s?e?ds.v2:ds.Yes:ds.No}class Ur{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 Ui{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 el(this._audioGroups,t)}hasSubtitleGroup(t){return el(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 el(a,t){return!t||!a?!1:a.indexOf(t)!==-1}function nv(){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 rv(a,t){let e=!1,i=[];if(a&&(e=a!=="SDR",i=[a]),t){i=t.allowedVideoRanges||gn.slice(0);const s=i.join("")!=="SDR"&&!t.videoCodec;e=t.preferHDR!==void 0?t.preferHDR:s&&nv(),e||(i=["SDR"])}return{preferHDR:e,allowedVideoRanges:i}}const av=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}},Bt=(a,t)=>JSON.stringify(a,av(t));function ov(a,t,e,i,s){const n=Object.keys(a),r=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,h=s==null?void 0:s.videoCodec,l=r&&parseInt(r)===2;let c=!1,u=!1,d=1/0,f=1/0,m=1/0,p=1/0,g=0,E=[];const{preferHDR:A,allowedVideoRanges:y}=rv(t,s);for(let I=n.length;I--;){const L=a[n[I]];c||(c=L.channels[2]>0),d=Math.min(d,L.minHeight),f=Math.min(f,L.minFramerate),m=Math.min(m,L.minBitrate),y.filter(w=>L.videoRanges[w]>0).length>0&&(u=!0)}d=q(d)?d:0,f=q(f)?f:0;const T=Math.max(1080,d),_=Math.max(30,f);m=q(m)?m:e,e=Math.max(m,e),u||(t=void 0);const C=n.length>1;return{codecSet:n.reduce((I,L)=>{const b=a[L];if(L===I)return I;if(E=u?y.filter(w=>b.videoRanges[w]>0):[],C){if(b.minBitrate>e)return be(L,`min bitrate of ${b.minBitrate} > current estimate of ${e}`),I;if(!b.hasDefaultAudio)return be(L,"no renditions with default or auto-select sound found"),I;if(o&&L.indexOf(o.substring(0,4))%5!==0)return be(L,`audio codec preference "${o}" not found`),I;if(r&&!l){if(!b.channels[r])return be(L,`no renditions with ${r} channel sound found (channels options: ${Object.keys(b.channels)})`),I}else if((!o||l)&&c&&b.channels[2]===0)return be(L,"no renditions with stereo sound found"),I;if(b.minHeight>T)return be(L,`min resolution of ${b.minHeight} > maximum of ${T}`),I;if(b.minFramerate>_)return be(L,`min framerate of ${b.minFramerate} > maximum of ${_}`),I;if(!E.some(w=>b.videoRanges[w]>0))return be(L,`no variants with VIDEO-RANGE of ${Bt(E)} found`),I;if(h&&L.indexOf(h.substring(0,4))%5!==0)return be(L,`video codec preference "${h}" not found`),I;if(b.maxScore<g)return be(L,`max score of ${b.maxScore} < selected max of ${g}`),I}return I&&(mn(L)>=mn(I)||b.fragmentError>a[I].fragmentError)?I:(p=b.minIndex,g=b.maxScore,L)},void 0),videoRanges:E,preferHDR:A,minFramerate:f,minBitrate:m,minIndex:p}}function be(a,t){Tt.log(`[abr] start candidates with "${a}" ignored because ${t}`)}function fc(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 lv(a,t,e,i){return a.slice(e,i+1).reduce((s,n,r)=>{if(!n.codecSet)return s;const o=n.audioGroups;let h=s[n.codecSet];h||(s[n.codecSet]=h={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),h.minBitrate=Math.min(h.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return h.minHeight=Math.min(h.minHeight,l),h.minFramerate=Math.min(h.minFramerate,n.frameRate),h.minIndex=Math.min(h.minIndex,r),h.maxScore=Math.max(h.maxScore,n.score),h.fragmentError+=n.fragmentError,h.videoRanges[n.videoRange]=(h.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const u=t.groups[c];u&&(h.hasDefaultAudio=h.hasDefaultAudio||t.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{h.channels[d]=(h.channels[d]||0)+u.channels[d]}))}),s},{})}function il(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(fi(a,s,e))return i}return-1}function fi(a,t,e){const{groupId:i,name:s,lang:n,assocLang:r,default:o}=a,h=a.forced;return(i===void 0||t.groupId===i)&&(s===void 0||t.name===s)&&(n===void 0||hv(n,t.lang))&&(n===void 0||t.assocLang===r)&&(o===void 0||t.default===o)&&(h===void 0||t.forced===h)&&(!("characteristics"in a)||cv(a.characteristics||"",t.characteristics))&&(e===void 0||e(a,t))}function hv(a,t="--"){return a.length===t.length?a===t:a.startsWith(t)||t.startsWith(a)}function cv(a,t=""){const e=a.split(","),i=t.split(",");return e.length===i.length&&!e.some(s=>i.indexOf(s)===-1)}function di(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 uv(a,t,e,i,s){const n=t[i],o=t.reduce((d,f,m)=>{const p=f.uri;return(d[p]||(d[p]=[])).push(m),d},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const h=n.videoRange,l=n.frameRate,c=n.codecSet.substring(0,4),u=sl(t,i,d=>{if(d.videoRange!==h||d.frameRate!==l||d.codecSet.substring(0,4)!==c)return!1;const f=d.audioGroups,m=e.filter(p=>!f||f.indexOf(p.groupId)!==-1);return we(a,m,s)>-1});return u>-1?u:sl(t,i,d=>{const f=d.audioGroups,m=e.filter(p=>!f||f.indexOf(p.groupId)!==-1);return we(a,m,s)>-1})}function sl(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 En(a,t){var e;return!!a&&a!==((e=t.loadLevelObj)==null?void 0:e.uri)}class mc extends Ye{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:h}=r;if(!s||!h)return;const l=performance.now(),c=n?n.stats:s.stats,u=n?n.duration:s.duration,d=l-c.loading.start,f=r.minAutoLevel,m=s.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const g=p>-1&&p!==m,E=!!e||g;if(!E&&(h.paused||!h.playbackRate||!h.readyState))return;const A=r.mainForwardBufferInfo;if(!E&&A===null)return;const y=this.bwEstimator.getEstimateTTFB(),T=Math.abs(h.playbackRate);if(d<=Math.max(y,1e3*(u/(T*2))))return;const _=A?A.len/T:0,C=c.loading.first?c.loading.first-c.loading.start:-1,S=c.loaded&&C>-1,I=this.getBwEstimate(),L=r.levels,b=L[m],w=Math.max(c.loaded,Math.round(u*(s.bitrate||b.averageBitrate)/8));let O=S?d-C:d;O<1&&S&&(O=Math.min(d,c.loaded*8/I));const H=S?c.loaded*1e3/O:0,Y=y/1e3,$=H?(w-c.loaded)/H:w*8/I+Y;if($<=_)return;const z=H?H*8:I,W=((i=(e==null?void 0:e.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,J=this.hls.config.abrBandWidthUpFactor;let G=Number.POSITIVE_INFINITY,U;for(U=m-1;U>f;U--){const R=L[U].maxBitrate,tt=!L[U].details||W;if(G=this.getTimeToLoadFrag(Y,z,u*R,tt),G<Math.min(_,u+Y))break}if(G>=$||G>u*10)return;S?this.bwEstimator.sample(d-Math.min(y,C),c.loaded):this.bwEstimator.sampleTTFB(d);const K=L[U].maxBitrate;this.getBwEstimate()*J>K&&this.resetEstimator(K);const V=this.findBestLevel(K,f,U,0,_,1,1);V>-1&&(U=V),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
9
+ Fragment duration: ${s.duration.toFixed(3)}
10
+ Time to underbuffer: ${_.toFixed(3)} s
11
+ Estimated load time for current fragment: ${$.toFixed(3)} s
12
+ Estimated load time for down switch fragment: ${G.toFixed(3)} s
13
+ TTFB estimate: ${C|0} ms
14
+ Current BW estimate: ${q(I)?I|0:"Unknown"} bps
15
+ New BW estimate: ${this.getBwEstimate()|0} bps
16
+ Switching to level ${U} @ ${K|0} bps`),r.nextLoadLevel=r.nextAutoLevel=U,this.clearTimer();const X=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===U&&U>0){const R=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${U>0?"and switching down":""}
17
+ Fragment duration: ${s.duration.toFixed(3)} s
18
+ Time to underbuffer: ${R.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,U>f){let tt=this.findBestLevel(this.hls.levels[f].bitrate,f,U,0,R,1,1);tt===-1&&(tt=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=tt,this.resetEstimator(this.hls.levels[tt].bitrate)}}};g||$>G*2?X():this.timer=self.setInterval(X,G*1e3),r.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:c})},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 Sy(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.FRAG_LOADING,this.onFragLoading,this),t.on(v.FRAG_LOADED,this.onFragLoaded,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.FRAG_LOADING,this.onFragLoading,this),t.off(v.FRAG_LOADED,this.onFragLoaded,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(v.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 P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case P.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,h=r-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(h-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(h)}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;q(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,h=(r.loaded?r.loaded.duration:0)+n;r.loaded={bytes:o,duration:h},r.realBitrate=Math.round(8*o/h)}if(e.bitrateTest){const n={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(v.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,h=this.getBwEstimate(),l=this.getStarvationDelay();let c=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(l){const g=this.findBestLevel(h,r,s,l,0,c,u);if(g>=0)return this.rebufferNotice=-1,g}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const g=this.bitrateTestDelay;g&&(d=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),c=u=1)}const f=this.findBestLevel(h,r,s,l,d,c,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const m=i.levels[r],p=i.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.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 h;const l=s+n,c=this.lastLoadedFragLevel,u=c===-1?this.hls.firstLevel:c,{fragCurrent:d,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:E}=this.hls;if(m.length===1)return 0;const A=m[u],y=!!((h=this.hls.latestLevelDetails)!=null&&h.live),T=g===-1||c===-1;let _,C="SDR",S=(A==null?void 0:A.frameRate)||0;const{audioPreference:I,videoPreference:L}=E,b=this.audioTracksByGroup||(this.audioTracksByGroup=fc(p));let w=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const z=this.codecTiers||(this.codecTiers=lv(m,b,e,i)),W=ov(z,C,t,I,L),{codecSet:J,videoRanges:G,minFramerate:U,minBitrate:K,minIndex:V,preferHDR:X}=W;w=V,_=J,C=X?G[G.length-1]:G[0],S=U,t=Math.max(t,K),this.log(`picked start tier ${Bt(W)}`)}else _=A==null?void 0:A.codecSet,C=A==null?void 0:A.videoRange;const O=f?f.duration:d?d.duration:0,H=this.bwEstimator.getEstimateTTFB()/1e3,Y=[];for(let z=i;z>=e;z--){var $;const W=m[z],J=z>u;if(!W)continue;if(E.useMediaCapabilities&&!W.supportedResult&&!W.supportedPromise){const tt=navigator.mediaCapabilities;typeof(tt==null?void 0:tt.decodingInfo)=="function"&&(tv(W,b,C,S,t,I)||Rn(W.videoCodec))?(W.supportedPromise=dc(W,b,tt),W.supportedPromise.then(it=>{if(!this.hls)return;W.supportedResult=it;const lt=this.hls.levels,It=lt.indexOf(W);it.error?this.warn(`MediaCapabilities decodingInfo error: "${it.error}" for level ${It} ${Bt(it)}`):it.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${It} ${Bt(it)}`),It>-1&&lt.length>1&&(this.log(`Removing unsupported level ${It}`),this.hls.removeLevel(It),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):W.supportedResult=cc}if((_&&W.codecSet!==_||C&&W.videoRange!==C||J&&S>W.frameRate||!J&&S>0&&S<W.frameRate||W.supportedResult&&!(($=W.supportedResult.decodingInfoResults)!=null&&$[0].smooth))&&(!T||z!==w)){Y.push(z);continue}const G=W.details,U=(f?G==null?void 0:G.partTarget:G==null?void 0:G.averagetargetduration)||O;let K;J?K=o*t:K=r*t;const V=O&&s>=O*2&&n===0?W.averageBitrate:W.maxBitrate,X=this.getTimeToLoadFrag(H,K,V*U,G===void 0);if(K>=V&&(z===c||W.loadError===0&&W.fragmentError===0)&&(X<=H||!q(X)||y&&!this.bitrateTestDelay||X<l)){const tt=this.forcedAutoLevel;return z!==g&&(tt===-1||tt!==g)&&(Y.length&&this.trace(`Skipped level(s) ${Y.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[Y[0]].codecs}" ${m[Y[0]].videoRange}; not compatible with "${_}" ${C}`),this.info(`switch candidate:${u}->${z} adjustedbw(${Math.round(K)})-bitrate=${Math.round(K-V)} ttfb:${H.toFixed(1)} avgDuration:${U.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${T} codecSet:${W.codecSet} videoRange:${W.videoRange} hls.loadLevel:${g}`)),T&&(this.firstSelection=z),z}}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 pc={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 dv(a,t,e){if(t===null||!Array.isArray(a)||!a.length||!q(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;for(let n=0;n<a.length;++n){const r=a[n];if(mv(t,e,r))return r}return null}function pi(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)&&nl(e,i,n)===0||fv(n,a,Math.min(s,i))))return n;const r=pc.search(t,nl.bind(null,e,i));return r&&(r!==a||!n)?r:n}function fv(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 nl(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 mv(a,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>a}function gc(a,t,e){if(a&&a.startCC<=t&&a.endCC>=t){let i=a.fragments;const{fragmentHint:s}=a;s&&(i=i.concat(s));let n;return pc.search(i,r=>r.cc<t?1:r.cc>t?-1:(n=r,r.end<=e?1:r.start>e?-1:0)),n||null}return null}function yn(a){switch(a.details){case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_TIMEOUT:case P.LEVEL_LOAD_TIMEOUT:case P.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function rl(a,t){const e=yn(t);return a.default[`${e?"timeout":"error"}Retry`]}function Ea(a,t){const e=a.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*a.retryDelayMs,a.maxRetryDelayMs)}function al(a){return xt(xt({},a),{errorRetry:null,timeoutRetry:null})}function vn(a,t,e,i){if(!a)return!1;const s=i==null?void 0:i.code,n=t<a.maxNumRetry&&(pv(s)||!!e);return a.shouldRetry?a.shouldRetry(a,t,e,i,n):n}function pv(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}var Xt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},de={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Ec extends Ye{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(v.ERROR,this.onError,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(v.ERROR,this.onError,this),t.off(v.ERROR,this.onErrorOut,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.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 P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case P.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction=Es();return}case P.FRAG_GAP:case P.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Xt.SendAlternateToPenaltyBox;return}case P.LEVEL_EMPTY_ERROR:case P.LEVEL_PARSING_ERROR:{var r,o;const l=e.parent===Z.MAIN?e.level:s.loadLevel;e.details===P.LEVEL_EMPTY_ERROR&&((r=e.context)!=null&&(o=r.levelDetails)!=null&&o.live)?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,l):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,l))}return;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level));return;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_LOAD_ERROR:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=s.loadLevelObj;if(l&&(n.type===pt.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===pt.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Xt.SendAlternateToPenaltyBox,e.errorAction.flags=de.MoveAllAlternatesMatchingHost;return}}return;case P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=s.loadLevelObj,c=l==null?void 0:l.attrs["HDCP-LEVEL"];c?e.errorAction={action:Xt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHDCP,hdcpLevel:c}:this.keySystemError(e)}return;case P.BUFFER_ADD_CODEC_ERROR:case P.REMUX_ALLOC_ERROR:case P.BUFFER_APPEND_ERROR:if(!e.errorAction){var h;e.errorAction=this.getLevelSwitchAction(e,(h=e.level)!=null?h:s.loadLevel)}return;case P.INTERNAL_EXCEPTION:case P.BUFFER_APPENDING_ERROR:case P.BUFFER_FULL_ERROR:case P.LEVEL_SWITCH_ERROR:case P.BUFFER_STALLED_ERROR:case P.BUFFER_SEEK_OVER_HOLE:case P.BUFFER_NUDGE_ON_STALL:e.errorAction=Es();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=rl(i.config.playlistLoadPolicy,t),n=this.playlistError++;if(vn(s,n,yn(t),t.response))return{action:Xt.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=rl(t.details.startsWith("key")?r:n,t),h=e.levels.reduce((c,u)=>c+u.fragmentError,0);if(s&&(t.details!==P.FRAG_GAP&&s.fragmentError++,vn(o,h,yn(t),t.response)))return{action:Xt.RetryRequest,flags:de.None,retryConfig:o,retryCount:h};const l=this.getLevelSwitchAction(t,i);return o&&(l.retryConfig=o,l.retryCount=h),l}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var n,r;const l=t.details;s.loadError++,l===P.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:m}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const p=(n=t.frag)==null?void 0:n.type,E=(p===Z.AUDIO&&l===P.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(l===P.BUFFER_ADD_CODEC_ERROR||l===P.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:C})=>s.audioCodec!==C),y=t.sourceBufferName==="video"&&(l===P.BUFFER_ADD_CODEC_ERROR||l===P.BUFFER_APPEND_ERROR)&&u.some(({codecSet:C,audioCodec:S})=>s.codecSet!==C&&s.audioCodec===S),{type:T,groupId:_}=(r=t.context)!=null?r:{};for(let C=u.length;C--;){const S=(C+d)%u.length;if(S!==d&&S>=f&&S<=m&&u[S].loadError===0){var o,h;const I=u[S];if(l===P.FRAG_GAP&&p===Z.MAIN&&t.frag){const L=u[S].details;if(L){const b=pi(t.frag,L.fragments,t.frag.start);if(b!=null&&b.gap)continue}}else{if(T===pt.AUDIO_TRACK&&I.hasAudioGroup(_)||T===pt.SUBTITLE_TRACK&&I.hasSubtitleGroup(_))continue;if(p===Z.AUDIO&&(o=s.audioGroups)!=null&&o.some(L=>I.hasAudioGroup(L))||p===Z.SUBTITLE&&(h=s.subtitleGroups)!=null&&h.some(L=>I.hasSubtitleGroup(L))||E&&s.audioCodec===I.audioCodec||!E&&s.audioCodec!==I.audioCodec||y&&s.codecSet===I.codecSet)continue}c=S;break}}if(c>-1&&i.loadLevel!==c)return t.levelRetry=!0,this.playlistError=0,{action:Xt.SendAlternateToPenaltyBox,flags:de.None,nextAutoLevel:c}}return{action:Xt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case Xt.DoNothing:break;case Xt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==P.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 Xt.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=kr[kr.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===P.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo")){const i=hc(t.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${t.sourceBufferName}Codec`]===i&&this.hls.removeLevel(n)}}}function Es(a){const t={action:Xt.DoNothing,flags:de.None};return a&&(t.resolved=!0),t}var Vt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class gv{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(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.BUFFER_APPENDED,this.onBufferAppended,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.BUFFER_APPENDED,this.onBufferAppended,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.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 h=o.body;if(h.start<=t&&t<=h.end)return h}}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 h=this.fragments[o];if(!h||r>=h.body.sn)return;if(!h.buffered&&(!h.loaded||n)){h.body.type===i&&this.removeFragment(h.body);return}const l=h.range[t];if(l){if(l.time.length===0){this.removeFragment(h.body);return}l.time.some(c=>{const u=!this.isTimeBuffered(c.startPTS,c.endPTS,e);return u&&this.removeFragment(h.body),u})}})}detectPartialFragments(t){const e=this.timeRanges;if(!e||t.frag.sn==="initSegment")return;const i=t.frag,s=Ii(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const r=!i.relurl;Object.keys(e).forEach(o=>{const h=i.elementaryStreams[o];if(!h)return;const l=e[o],c=r||h.partial===!0;n.range[o]=this.getBufferedTimes(i,t.part,c,l)}),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),Gs(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=Ii(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,h=t.minEndPTS||o,l=t.maxStartPTS||r;for(let c=0;c<s.length;c++){const u=s.start(c)-this.bufferPadding,d=s.end(c)+this.bufferPadding;if(l>=u&&h<=d){n.time.push({startPTS:Math.max(r,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(r<d&&o>u){const f=Math.max(r,s.start(c)),m=Math.min(o,s.end(c));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=u)break}return n}getPartialFragment(t){let e=null,i,s,n,r=0;const{bufferPadding:o,fragments:h}=this;return Object.keys(h).forEach(l=>{const c=h[l];c&&Gs(c)&&(s=c.body.start-o,n=c.body.end+o,t>=s&&t<=n&&(i=Math.min(t-s,n-t),r<=i&&(e=c.body,r=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||Gs(e))}getState(t){const e=Ii(t),i=this.fragments[e];return i?i.buffered?Gs(i)?Vt.PARTIAL:Vt.OK:Vt.APPENDING:Vt.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=Ii(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 l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(s)}this.timeRanges=n;const h=n[r];this.detectEvictedFragments(r,h,o,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ii(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 h=o.body;h.type!==i||s&&!h.gap||h.start<e&&h.end>t&&(o.buffered||n)&&this.removeFragment(h)})}removeFragment(t){const e=Ii(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 Gs(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 Ii(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 ei={cbc:0,ctr:1};class Ev{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 ei.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case ei.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 yv(a){const t=a.byteLength,e=t&&new DataView(a.buffer).getUint8(t-1);return e?a.slice(0,t-e):a}class vv{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],h=this.invSubMix,l=h[0],c=h[1],u=h[2],d=h[3],f=new Uint32Array(256);let m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,t[m]=E,e[E]=m;const A=f[m],y=f[A],T=f[y];let _=f[E]*257^E*16843008;s[m]=_<<24|_>>>8,n[m]=_<<16|_>>>16,r[m]=_<<8|_>>>24,o[m]=_,_=T*16843009^y*65537^A*257^m*16843008,l[E]=_<<24|_>>>8,c[E]=_<<16|_>>>16,u[E]=_<<8|_>>>24,d[E]=_,m?(m=A^f[f[f[T^A]]],p^=f[f[p]]):m=p=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,h;const l=this.keySchedule=new Uint32Array(r),c=this.invKeySchedule=new Uint32Array(r),u=this.sBox,d=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],E=f[3];let A,y;for(o=0;o<r;o++){if(o<n){A=l[o]=e[o];continue}y=A,o%n===0?(y=y<<8|y>>>24,y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[y&255],y^=d[o/n|0]<<24):n>6&&o%n===4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[y&255]),l[o]=A=(l[o-n]^y)>>>0}for(h=0;h<r;h++)o=r-h,h&3?y=l[o]:y=l[o-4],h<4||o<=4?c[h]=y:c[h]=m[u[y>>>24]]^p[u[y>>>16&255]]^g[u[y>>>8&255]]^E[u[y&255]],c[h]=c[h]>>>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,h=o[0],l=o[1],c=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],m=d[1],p=d[2],g=d[3];const E=new Int32Array(t),A=new Int32Array(E.length);let y,T,_,C,S,I,L,b,w,O,H,Y,$,z;const W=this.networkToHostOrderSwap;for(;e<E.length;){for(w=W(E[e]),O=W(E[e+1]),H=W(E[e+2]),Y=W(E[e+3]),S=w^n[0],I=Y^n[1],L=H^n[2],b=O^n[3],$=4,z=1;z<s;z++)y=h[S>>>24]^l[I>>16&255]^c[L>>8&255]^u[b&255]^n[$],T=h[I>>>24]^l[L>>16&255]^c[b>>8&255]^u[S&255]^n[$+1],_=h[L>>>24]^l[b>>16&255]^c[S>>8&255]^u[I&255]^n[$+2],C=h[b>>>24]^l[S>>16&255]^c[I>>8&255]^u[L&255]^n[$+3],S=y,I=T,L=_,b=C,$=$+4;y=r[S>>>24]<<24^r[I>>16&255]<<16^r[L>>8&255]<<8^r[b&255]^n[$],T=r[I>>>24]<<24^r[L>>16&255]<<16^r[b>>8&255]<<8^r[S&255]^n[$+1],_=r[L>>>24]<<24^r[b>>16&255]<<16^r[S>>8&255]<<8^r[I&255]^n[$+2],C=r[b>>>24]<<24^r[S>>16&255]<<16^r[I>>8&255]<<8^r[L&255]^n[$+3],A[e]=W(y^f),A[e+1]=W(C^m),A[e+2]=W(_^p),A[e+3]=W(T^g),f=w,m=O,p=H,g=Y,e=e+4}return A.buffer}}class Av{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=Tv(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function Tv(a){switch(a){case ei.cbc:return"AES-CBC";case ei.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const _v=16;class ya{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?yv(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 h=this.flush();h?n(h.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!==ei.cbc||e.byteLength!==16)return Tt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=pe(o,t),this.remainderData=null);const h=this.getValidChunk(t);if(!h.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new vv),l.expandKey(e);const c=r;return this.currentResult=l.decrypt(h.buffer,0,i),this.currentIV=h.slice(-16).buffer,c||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 Av(this.subtle,e,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ev(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Tt.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%_v;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(Tt.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ll=Math.pow(2,17);class Sv{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 Ue({type:et.NETWORK_ERROR,details:P.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,h)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(m=>m[0]==="GAP")){h(cl(t));return}else t.gap=!1;const l=this.loader=n?new n(s):new r(s),c=hl(t);t.loader=l;const u=al(s.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:ll};t.stats=l.stats;const f={onSuccess:(m,p,g,E)=>{this.resetLoader(t,l);let A=m.data;g.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(A.slice(0,16)),A=A.slice(16)),o({frag:t,part:null,payload:A,networkDetails:E})},onError:(m,p,g,E)=>{this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:xt({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:E}))},onAbort:(m,p,g)=>{this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:m}))}};e&&(f.onProgress=(m,p,g,E)=>e({frag:t,part:null,payload:g,networkDetails:E})),l.load(c,d,f)})}loadPart(t,e,i){this.abort();const s=this.config,n=s.fLoader,r=s.loader;return new Promise((o,h)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){h(cl(t,e));return}const l=this.loader=n?new n(s):new r(s),c=hl(t,e);t.loader=l;const u=al(s.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ll};e.stats=l.stats,l.load(c,d,{onSuccess:(f,m,p,g)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const E={frag:t,part:e,payload:f.data,networkDetails:g};i(E),o(E)},onError:(f,m,p,g)=>{this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:xt({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(t,l),h(new Ue({type:et.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,n=s.total;if(i.loaded+=s.loaded,n){const h=Math.round(t.duration/e.duration),l=Math.min(Math.round(i.loaded/n),h),u=(h-l)*Math.round(i.loaded/l);i.total=i.loaded+u}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 hl(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(q(s)&&q(n)){var r;let o=s,h=n;if(a.sn==="initSegment"&&xv((r=a.decryptdata)==null?void 0:r.method)){const l=n-s;l%16&&(h=n+(16-l%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=h}return i}function cl(a,t){const e=new Error(`GAP ${a.gap?"tag":"attribute"} found`),i={type:et.MEDIA_ERROR,details:P.FRAG_GAP,fatal:!1,frag:a,error:e,networkDetails:null};return t&&(i.part=t),(t||a).stats.aborted=!0,new Ue(i)}function xv(a){return a==="AES-128"||a==="AES-256"}class Ue extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class yc extends Ye{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 Dn{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=Hs(),this.buffering={audio:Hs(),video:Hs(),audiovideo:Hs()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=n,this.partial=r}}function Hs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const ul={length:0,start:()=>0,end:()=>0};class ht{static isBuffered(t,e){if(t){const i=ht.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=ht.getBuffered(t);return ht.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=ht.bufferedRanges(t);if(s.length)return ht.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((c,u)=>c.start-u.start||u.end-c.end);let s=-1,n=[];if(i)for(let c=0;c<t.length;c++){e>=t[c].start&&e<=t[c].end&&(s=c);const u=n.length;if(u){const d=n[u-1].end;t[c].start-d<i?t[c].end>d&&(n[u-1].end=t[c].end):n.push(t[c])}else n.push(t[c])}else n=t;let r=0,o,h=e,l=e;for(let c=0;c<n.length;c++){const u=n[c].start,d=n[c].end;if(s===-1&&e>=u&&e<=d&&(s=c),e+i>=u&&e<d)h=u,l=d,r=l-e;else if(e+i<u){o=u;break}}return{len:r,start:h||0,end:l||0,nextStart:o,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||ul}catch(e){return Tt.log("failed to get media.buffered",e),ul}}}const vc=/\{\$([a-zA-Z0-9-_]+)\}/g;function dl(a){return vc.test(a)}function Nr(a,t){if(a.variableList!==null||a.hasVariableRefs){const e=a.variableList;return t.replace(vc,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 fl(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 Cv(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 bv=/^(\d+)x(\d+)$/,ml=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Mt{constructor(t,e){typeof t=="string"&&(t=Mt.parseAttrList(t,e)),bt(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=bv.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(ml.lastIndex=0;(i=ml.exec(t))!==null;){const r=i[1].trim();let o=i[2];const h=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1;let l=!1;if(h)o=o.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(e&&(h||l))o=Nr(e,o);else if(!l&&!h)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":Tt.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=o}return s}}const Iv="com.apple.hls.interstitial";function Lv(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Rv(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class va{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]){Tt.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=r;break}t=bt(new Mt({}),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"]);q(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?(Tt.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(q(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===Iv}get isValid(){return!!this.id&&!this._badValueForSameId&&q(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 Dv=10;class Ac{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?q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Dv}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 Oi(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function Aa(a){switch(a){case"AES-128":case"AES-256":return ei.cbc;case"AES-256-CTR":return ei.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function Ta(a){return Uint8Array.from(atob(a),t=>t.charCodeAt(0))}function Gr(a){return Uint8Array.from(unescape(encodeURIComponent(a)),t=>t.charCodeAt(0))}function Pv(a){const t=Gr(a).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function wv(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 Mv(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=Ta(r)):e=Pv(r)}}return e}const An=typeof self<"u"?self:void 0;var _t={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Qt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function nn(a){switch(a){case Qt.FAIRPLAY:return _t.FAIRPLAY;case Qt.PLAYREADY:return _t.PLAYREADY;case Qt.WIDEVINE:return _t.WIDEVINE;case Qt.CLEARKEY:return _t.CLEARKEY}}var $s={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function sr(a){if(a===$s.WIDEVINE)return _t.WIDEVINE;if(a===$s.PLAYREADY)return _t.PLAYREADY;if(a===$s.CENC||a===$s.CLEARKEY)return _t.CLEARKEY}function Ks(a){switch(a){case _t.FAIRPLAY:return Qt.FAIRPLAY;case _t.PLAYREADY:return Qt.PLAYREADY;case _t.WIDEVINE:return Qt.WIDEVINE;case _t.CLEARKEY:return Qt.CLEARKEY}}function os(a){const{drmSystems:t,widevineLicenseUrl:e}=a,i=t?[_t.FAIRPLAY,_t.WIDEVINE,_t.PLAYREADY,_t.CLEARKEY].filter(s=>!!t[s]):[];return!i[_t.WIDEVINE]&&e&&i.push(_t.WIDEVINE),i}const _a=function(a){return An!=null&&(a=An.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Bv(a,t,e,i){let s;switch(a){case _t.FAIRPLAY:s=["cenc","sinf"];break;case _t.WIDEVINE:case _t.PLAYREADY:s=["cenc"];break;case _t.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return Ov(s,t,e,i)}function Ov(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 Fv(a){var t;return a.sessionType==="persistent-license"||!!((t=a.sessionTypes)!=null&&t.some(e=>e==="persistent-license"))}function Tc(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 h=Ta(o).subarray(0,16);return wv(h),h}}return null}let Vs={};class Ni{static clearKeyUriToKeyIdMap(){Vs={}}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&&!Oi(t)}isSupported(){if(this.method){if(Oi(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Qt.FAIRPLAY:case Qt.WIDEVINE:case Qt.PLAYREADY:case Qt.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(Oi(this.method)&&this.uri&&!this.iv){typeof t!="number"&&(Tt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=kv(t);return new Ni(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=Mv(this.uri);if(e)switch(this.keyFormat){case Qt.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case Qt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Yy(i,null,e),this.keyId=Tc(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=Vs[this.uri];if(!i){const s=Object.keys(Vs).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),Vs[this.uri]=i}this.keyId=i}return this}}function kv(a){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=a>>8*(15-e)&255;return t}const pl=/#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,gl=/#EXT-X-MEDIA:(.*)/g,Uv=/^#EXT(?:INF|-X-TARGETDURATION):/m,nr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Nv=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 _e{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 ma.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Uv.test(t)}static parseMasterPlaylist(t,e){const i=dl(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];pl.lastIndex=0;let r;for(;(r=pl.exec(t))!=null;)if(r[1]){var o;const l=new Mt(r[1],s),c=Nr(s,r[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:_e.resolve(c,e)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),vl(l.CODECS,u);const f=l["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},vl(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||n.push(u),s.levels.push(u)}else if(r[3]){const l=r[3],c=r[4];switch(l){case"SESSION-DATA":{const u=new Mt(c,s),d=u["DATA-ID"];d&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[d]=u);break}case"SESSION-KEY":{const u=El(c,e,s);u.encrypted&&u.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(u)):Tt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const u=new Mt(c,s);fl(s,u,e)}break}case"CONTENT-STEERING":{const u=new Mt(c,s);s.contentSteering={uri:_e.resolve(u["SERVER-URI"],e),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=yl(c);break}}}const h=n.length>0&&n.length<s.levels.length;return s.levels=h?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(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:r.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let h=0;for(gl.lastIndex=0;(s=gl.exec(t))!==null;){const l=new Mt(s[1],i),c=l.TYPE;if(c){const u=o[c],d=n[c]||[];n[c]=d;const f=l.LANGUAGE,m=l["ASSOC-LANGUAGE"],p=l.CHANNELS,g=l.CHARACTERISTICS,E=l["INSTREAM-ID"],A={attrs:l,bitrate:0,id:h++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:c,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?_e.resolve(l.URI,e):""};if(m&&(A.assocLang=m),p&&(A.channels=p),g&&(A.characteristics=g),E&&(A.instreamId=E),u!=null&&u.length){const y=_e.findGroup(u,A.groupId)||u[0];Al(A,y,"audioCodec"),Al(A,y,"textCodec")}d.push(A)}}return n}static parseLevelPlaylist(t,e,i,s,n,r){var o;const h={url:e},l=new Ac(e),c=l.fragments,u=[];let d=null,f=0,m=0,p=0,g=0,E=0,A=null,y=new en(s,h),T,_,C,S=-1,I=!1,L=null,b;if(nr.lastIndex=0,l.m3u8=t,l.hasVariableRefs=dl(t),((o=nr.exec(t))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(T=nr.exec(t))!==null;){I&&(I=!1,y=new en(s,h),y.playlistOffset=p,y.start=p,y.sn=f,y.cc=g,E&&(y.bitrate=E),y.level=i,d&&(y.initSegment=d,d.rawProgramDateTime&&(y.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),L&&(y.setByteRange(L),L=null)));const Y=T[1];if(Y){y.duration=parseFloat(Y);const $=(" "+T[2]).slice(1);y.title=$||null,y.tagList.push($?["INF",Y,$]:["INF",Y])}else if(T[3]){if(q(y.duration)){y.playlistOffset=p,y.start=p,C&&_l(y,C,l),y.sn=f,y.level=i,y.cc=g,c.push(y);const $=(" "+T[3]).slice(1);y.relurl=Nr(l,$),Hr(y,A,u),A=y,p+=y.duration,f++,m=0,I=!0}}else{if(T=T[0].match(Nv),!T){Tt.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<T.length&&T[_]===void 0;_++);const $=(" "+T[_]).slice(1),z=(" "+T[_+1]).slice(1),W=T[_+2]?(" "+T[_+2]).slice(1):null;switch($){case"BYTERANGE":A?y.setByteRange(z,A):y.setByteRange(z);break;case"PROGRAM-DATE-TIME":y.rawProgramDateTime=z,y.tagList.push(["PROGRAM-DATE-TIME",z]),S===-1&&(S=c.length);break;case"PLAYLIST-TYPE":l.type&&Fe(l,$,T),l.type=z.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Fe(l,$,T):c.length>0&&Sl(l,$,T),f=l.startSN=parseInt(z);break;case"SKIP":{l.skippedSegments&&Fe(l,$,T);const J=new Mt(z,l),G=J.decimalInteger("SKIPPED-SEGMENTS");if(q(G)){l.skippedSegments+=G;for(let K=G;K--;)c.push(null);f+=G}const U=J.enumeratedString("RECENTLY-REMOVED-DATERANGES");U&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(U.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Fe(l,$,T),l.targetduration=Math.max(parseInt(z),1);break;case"VERSION":l.version!==null&&Fe(l,$,T),l.version=parseInt(z);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Fe(l,$,T),l.live=!1;break;case"#":(z||W)&&y.tagList.push(W?[z,W]:[z]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([$]);break;case"BITRATE":y.tagList.push([$,z]),E=parseInt(z)*1e3,q(E)?y.bitrate=E:E=0;break;case"DATERANGE":{const J=new Mt(z,l),G=new va(J,l.dateRanges[J.ID],l.dateRangeTagCount);l.dateRangeTagCount++,G.isValid||l.skippedSegments?l.dateRanges[G.id]=G:Tt.warn(`Ignoring invalid DATERANGE tag: "${z}"`),y.tagList.push(["EXT-X-DATERANGE",z]);break}case"DEFINE":{{const J=new Mt(z,l);"IMPORT"in J?Cv(l,J,r):fl(l,J,e)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Fe(l,$,T):c.length>0&&Sl(l,$,T),l.startCC=g=parseInt(z);break;case"KEY":{const J=El(z,e,l);if(J.isSupported()){if(J.method==="NONE"){C=void 0;break}C||(C={}),C[J.keyFormat]&&(C=bt({},C)),C[J.keyFormat]=J}else Tt.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${z}"`);break}case"START":l.startTimeOffset=yl(z);break;case"MAP":{const J=new Mt(z,l);if(y.duration){const G=new en(s,h);Tl(G,J,i,C),d=G,y.initSegment=d,d.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=d.rawProgramDateTime)}else{const G=y.byteRangeEndOffset;if(G){const U=y.byteRangeStartOffset;L=`${G-U}@${U}`}else L=null;Tl(y,J,i,C),d=y,I=!0}d.cc=g;break}case"SERVER-CONTROL":{b&&Fe(l,$,T),b=new Mt(z),l.canBlockReload=b.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=b.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&b.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=b.optionalFloat("PART-HOLD-BACK",0),l.holdBack=b.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Fe(l,$,T);const J=new Mt(z);l.partTarget=J.decimalFloatingPoint("PART-TARGET");break}case"PART":{let J=l.partList;J||(J=l.partList=[]);const G=m>0?J[J.length-1]:void 0,U=m++,K=new Mt(z,l),V=new qh(K,y,h,U,G);J.push(V),y.duration+=V.duration;break}case"PRELOAD-HINT":{const J=new Mt(z,l);l.preloadHint=J;break}case"RENDITION-REPORT":{const J=new Mt(z,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(J);break}default:Tt.warn(`line parsed but not handled: ${T}`);break}}}A&&!A.relurl?(c.pop(),p-=A.duration,l.partList&&(l.fragmentHint=A)):l.partList&&(Hr(y,A,u),y.cc=g,l.fragmentHint=y,C&&_l(y,C,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const w=c.length,O=c[0],H=c[w-1];if(p+=l.skippedSegments*l.targetduration,p>0&&w&&H){l.averagetargetduration=p/w;const Y=H.sn;l.endSN=Y!=="initSegment"?Y:0,l.live||(H.endList=!0),O&&l.startCC===void 0&&(l.startCC=O.cc),S>0&&(Hv(c,S),O&&u.unshift(O))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&O&&_c(u,l),l.endCC=g,l}}function _c(a,t){const e=a.length;if(!e)return;const 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]],h=o.startDate.getTime();o.tagAnchor=i.ref;for(let l=e;l--;){const c=Gv(t,h,a,l,s);if(c!==-1){o.tagAnchor=t.fragments[c].ref;break}}}}function Gv(a,t,e,i,s){const n=e[i];if(n){const o=n.programDateTime;if(t>=o||i===0){var r;const h=(((r=e[i+1])==null?void 0:r.start)||s)-n.start;if(t<=o+h*1e3){const l=e[i].sn-a.startSN,c=a.fragments;if(c.length>e.length){const d=(e[i+1]||c[c.length-1]).sn-a.startSN;for(let f=d;f>l;f--){const m=c[f].programDateTime;if(t>=m&&t<m+c[f].duration*1e3)return f}}return l}}}return-1}function El(a,t,e){var i,s;const n=new Mt(a,e),r=(i=n.METHOD)!=null?i:"",o=n.URI,h=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!h&&Tt.error(`Invalid IV: ${n.IV}`);const u=o?_e.resolve(o,t):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Ni(r,u,c,d,h)}function yl(a){const e=new Mt(a).decimalFloatingPoint("TIME-OFFSET");return q(e)?e:null}function vl(a,t){let e=(a||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=e.filter(n=>oc(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 Al(a,t,e){const i=t[e];i&&(a[e]=i)}function Hv(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 Hr(a,t,e){a.rawProgramDateTime?e.push(a):t!=null&&t.programDateTime&&(a.programDateTime=t.endProgramDateTime)}function Tl(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 _l(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 Fe(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`)}function Sl(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`)}function rr(a,t){const e=t.startPTS;if(q(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 Sc(a,t,e,i,s,n){i-e<=0&&(Tt.warn("Fragment should have a positive duration",t),i=e+t.duration,n=s+t.duration);let o=e,h=i;const l=t.startPTS,c=t.endPTS;if(q(l)){const g=Math.abs(l-e);q(t.deltaPTS)?t.deltaPTS=Math.max(g,t.deltaPTS):t.deltaPTS=g,o=Math.max(e,l),e=Math.min(e,l),s=Math.min(s,t.startDTS),h=Math.min(i,c),i=Math.max(i,c),n=Math.max(n,t.endDTS)}const u=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=h,t.endDTS=n;const d=t.sn;if(!a||d<a.startSN||d>a.endSN)return 0;let f;const m=d-a.startSN,p=a.fragments;for(p[m]=t,f=m;f>0;f--)rr(p[f],p[f-1]);for(f=m;f<p.length-1;f++)rr(p[f],p[f+1]);return a.fragmentHint&&rr(p[p.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,u}function $v(a,t){if(a===t)return;let e=null;const i=a.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){e=c;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let s;zv(a,t,(l,c,u,d)=>{if((!t.startCC||t.skippedSegments)&&c.cc!==l.cc){const f=l.cc-c.cc;for(let m=u;m<d.length;m++)d[m].cc+=f;t.endCC=d[d.length-1].cc}q(l.startPTS)&&q(l.endPTS)&&(c.setStart(c.startPTS=l.startPTS),c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.setDuration(l.endPTS-l.startPTS),c.duration&&(s=c),t.PTSKnown=t.alignedSliding=!0),l.hasStreams&&(c.elementaryStreams=l.elementaryStreams),c.loader=l.loader,l.hasStats&&(c.stats=l.stats),l.initSegment&&(c.initSegment=l.initSegment,e=l.initSegment)});const n=t.fragments,r=t.fragmentHint?n.concat(t.fragmentHint):n;if(e&&r.forEach(l=>{var c;l&&(!l.initSegment||l.initSegment.relurl===((c=e)==null?void 0:c.relurl))&&(l.initSegment=e)}),t.skippedSegments){if(t.deltaUpdateFailed=n.some(l=>!l),t.deltaUpdateFailed){Tt.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.canSkipDateRanges&&(t.dateRanges=Kv(a.dateRanges,t));const l=a.fragments.filter(c=>c.rawProgramDateTime);if(a.hasProgramDateTime&&!t.hasProgramDateTime)for(let c=1;c<r.length;c++)r[c].programDateTime===null&&Hr(r[c],r[c-1],l);_c(l,t)}t.endCC=n[n.length-1].cc}if(!t.startCC){var o;const l=bc(a,t.startSN-1);t.startCC=(o=l==null?void 0:l.cc)!=null?o:n[0].cc}Vv(a.partList,t.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),s?Sc(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):xc(a,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=a.driftStartTime,t.driftStart=a.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const l=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=l),t.driftEndTime=h,t.driftEnd=l}else t.driftEndTime=a.driftEndTime,t.driftEnd=a.driftEnd,t.advancedDateTime=a.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=a.requestScheduled)}function Kv(a,t){const{dateRanges:e,recentlyRemovedDateranges:i}=t,s=bt({},a);i&&i.forEach(o=>{delete s[o]});const r=Object.keys(s).length;return r&&Object.keys(e).forEach(o=>{const h=s[o],l=new va(e[o].attr,h);l.isValid?(s[o]=l,h||(l.tagOrder+=r)):Tt.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Bt(e[o].attr)}"`)}),s}function Vv(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 zv(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,h=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=s;l<=n;l++){const c=h[r+l];let u=o[l];if(i&&!u&&c&&(u=t.fragments[l]=c),c&&u){if(e(c,u,l,o),c.url&&c.url!==u.url){t.playlistParsingError=xl(`media sequence mismatch ${u.sn}:`,a,t,c,u);return}else if(c.cc!==u.cc){t.playlistParsingError=xl(`discontinuity sequence mismatch (${c.cc}!=${u.cc})`,a,t,c,u);return}}}}function xl(a,t,e,i,s){return new Error(`${a} ${s.url}
19
+ Playlist starting @${t.startSN}
20
+ ${t.m3u8}
21
+
22
+ Playlist starting @${e.startSN}
23
+ ${e.m3u8}`)}function xc(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;$r(t,r)}function $r(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 Cc(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 bc(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 Cl(a,t,e){return a?Ic(a.partList,t,e):null}function Ic(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 Lc(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 fs(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 Yv(a,t){return!!(a&&t.startCC<a.endCC&&t.endCC>a.startCC)}function bl(a,t){if(a){const e=a.start+t;a.start=a.startPTS=e,a.endPTS=e+a.duration}}function Rc(a,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)bl(e[i],a);t.fragmentHint&&bl(t.fragmentHint,a),t.alignedSliding=!0}function Xv(a,t){a&&(Dc(t,a),!t.alignedSliding&&a&&Tn(t,a),!t.alignedSliding&&a&&!t.skippedSegments&&xc(a,t,!1))}function Dc(a,t){if(!Yv(t,a))return;const e=Math.min(t.endCC,a.endCC),i=fs(t.fragments,e),s=fs(a.fragments,e);if(!i||!s)return;Tt.log(`Aligning playlist at start of dicontinuity sequence ${e}`);const n=i.start-s.start;Rc(n,a)}function Tn(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=fs(i,r),n=fs(e,r)),(!s||!n)&&(s=i[Math.floor(i.length/2)],n=fs(e,s.cc)||e[Math.floor(e.length/2)]);const o=s.programDateTime,h=n.programDateTime;if(!o||!h)return;const l=(h-o)/1e3-(n.start-s.start);Rc(l,a)}const jv={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}},N={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Pn extends yc{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=N.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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:h,mediaBuffer:l,state:c}=this,u=h?h.currentTime:0,d=ht.bufferInfo(l||h,u,r.maxBufferHole);if(this.log(`media seeking to ${q(u)?u.toFixed(3):u}, state: ${c}`),this.state===N.ENDED)this.resetLoadingState();else if(o){const f=r.maxFragLookUpTolerance,m=o.start-f,p=o.start+o.duration+f;if(!d.len||p<d.start||m>d.end){const g=u>p;(u<m||g)&&(g&&o.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(h){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(u>f&&(this.lastCurrentTime=u),!this.loadingParts){const m=Math.max(d.end,u),p=this.shouldLoadParts(this.getLevelDetails(),m);p&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${m.toFixed(2)}`),this.loadingParts=p)}}!this.hls.hasEnoughToStart&&!d.len&&(this.log(`setting startPosition to ${u} because of seek before start`),this.nextLoadPosition=this.startPosition=u),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 Sv(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ya(t.config)}registerListeners(){const{hls:t}=this;t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===N.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=N.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.buffered;this.config.maxBufferHole&&n&&n.length>1&&(t=ht.bufferedInfo(n,t.start,0));const r=t.nextStart;if(r&&r>s&&r<e.edge||this.media.currentTime<t.start)return!1;const h=e.partList;if(h!=null&&h.length){const c=h[h.length-1];return ht.isBuffered(this.media,c.start+c.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===N.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=N.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.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===N.FRAG_LOADING||!this.fragCurrent&&r===N.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=N.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(v.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===N.STOPPED||this.state===N.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)===Vt.APPENDING){const n=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(t.duration,r?r.len:this.config.maxBufferLength),h=this.backtrackFragment;((h?t.sn-h.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)===Vt.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(v.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&&Oi(o.method)){const h=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer,Aa(o.method)).catch(l=>{throw s.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const c=self.performance.now();return s.trigger(v.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:h,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===N.STOPPED||this.state===N.ERROR||(this.warn(i),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==N.STOPPED&&(this.state=N.IDLE),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){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?jv.toString(ht.getBuffered(i)):"(detached)"})`),jt(t)){var s;if(t.type!==Z.SUBTITLE){const r=t.elementaryStreams;if(!Object.keys(r).some(o=>!!r[o])){this.state=N.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=N.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(h=>!h),o=new Dn(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=N.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(v.KEY_LOADED,u),this.state===N.KEY_LOADING&&(this.state=N.IDLE),u}),this.hls.trigger(v.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):t.encrypted||(o=this.keyLoader.loadClear(t,r.encryptedFragments),o&&this.log("[eme] blocking frag load until media-keys acquired"));const h=this.fragPrevious;if(jt(t)&&(!h||t.sn!==h.sn)){const u=this.shouldLoadParts(e.details,t.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${h==null?void 0:h.sn}->${t.sn}`),this.loadingParts=u)}if(i=Math.max(t.start,i||0),this.loadingParts&&jt(t)){const u=r.partList;if(u&&s){i>t.end&&r.fragmentHint&&(t=r.fragmentHint);const d=this.getNextPart(u,t,i);if(d>-1){const f=u[d];t=this.fragCurrent=f.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${f.index} (${d}/${u.length-1}) of ${this.fragInfo(t,!1,f)}) cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=N.FRAG_LOADING;let m;return o?m=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(t,f,e,s)).catch(p=>this.handleFragLoadError(p)):m=this.doFragPartsLoad(t,f,e,s).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(v.FRAG_LOADING,{frag:t,part:f,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!t.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(jt(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))}`),q(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=N.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(t,s)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(t,l?s:void 0),o]).then(([u])=>(!l&&u&&s&&s(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(v.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,i,s){return new Promise((n,r)=>{var o;const h=[],l=(o=i.details)==null?void 0:o.partList,c=u=>{this.fragmentLoader.loadPart(t,u,s).then(d=>{h[u.index]=d;const f=d.part;this.hls.trigger(v.FRAG_LOADED,d);const m=Cl(i.details,t.sn,u.index+1)||Ic(l,t.sn,u.index+1);if(m)c(m);else return n({frag:t,part:f,partsLoaded:h})}).catch(r)};c(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===P.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(v.ERROR,e)}else this.hls.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==N.PARSING){!this.fragCurrent&&this.state!==N.STOPPED&&this.state!==N.ERROR&&(this.state=N.IDLE);return}const{frag:i,part:s,level:n}=e,r=self.performance.now();i.stats.parsing.end=r,s&&(s.stats.parsing.end=r);const o=this.getLevelDetails(),l=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),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],h=o.details,l=r>-1?Cl(h,n,r):null,c=l?l.fragment:bc(h,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(t,e,i,s,n){var r;if(!t||this.state!==N.PARSING)return;const{data1:o,data2:h}=t;let l=o;if(o&&h&&(l=pe(o,h)),!((r=l)!=null&&r.length))return;const c={type:t.type,frag:e,part:i,chunkMeta:s,parent:e.type,data:l};if(this.hls.trigger(v.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ht.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=ht.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(!q(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=ht.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 ht.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 h=null;if(e.live){const u=n.initialLiveManifestSize;if(s<u)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${u})`),null;if(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<r){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),h=this.getInitialLiveFragment(e);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,m=h?(d!==-1&&d>=r?d:f)||h.start:t;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=h)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=m}}else t<=r&&(h=i[0]);if(!h){const u=this.loadingParts?e.partEnd:e.fragmentEnd;h=this.getFragmentAtPosition(t,u,e)}let c=this.filterReplacedPrimary(h,e);if(!c&&h){const u=h.sn-e.startSN;c=this.filterReplacedPrimary(i[u+1]||null,e)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===Vt.OK||i===Vt.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 h=r.sn;return this.loopSn!==h&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${h}`),this.loopSn=h),null}}return this.loopSn=void 0,r}get primaryPrefetch(){if(Il(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(Il(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,h=t.length;o<h;o++){const l=t[o];if(r=r&&!l.independent,s>-1&&i<l.start)break;const c=l.loaded;c?s=-1:(n||l.independent||r)&&l.fragment===e&&(s=o),n=c}return s}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t){const e=t.fragments,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=dv(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=gc(t,i.cc,i.end),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:h}=i,{maxFragLookUpTolerance:l}=s,c=i.partList,u=!!(this.loadingParts&&c!=null&&c.length&&h);u&&h&&!this.bitrateTest&&c[c.length-1].fragment.sn===h.sn&&(r=r.concat(h),o=h.sn);let d;if(t<e){var f;const p=t<this.lastCurrentTime||t>e-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=pi(n,r,t,p)}else d=r[r.length-1];if(d){const m=d.sn-i.startSN,p=this.fragmentTracker.getState(d);if((p===Vt.OK||p===Vt.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!u||c[0].fragment.sn>d.sn||!i.live&&!u)&&n&&d.level===n.level){const E=r[m+1];d.sn<o&&this.fragmentTracker.getState(E)!==Vt.OK?d=E: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&&q(n);if(r||!o&&!n){Xv(i,t);const h=t.fragmentStart;return this.log(`Live playlist sliding: ${h.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),h}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&&q(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&&jt(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!==N.FRAG_LOADING_WAITING_RETRY)&&(this.state=N.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const m=this.getCurrentContext(e.chunkMeta);m&&(e.frag=m.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===P.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const r=e.errorAction,{action:o,flags:h,retryCount:l=0,retryConfig:c}=r||{},u=!!r&&!!c,d=u&&o===Xt.RetryRequest,f=u&&!r.resolved&&h===de.MoveAllAlternatesMatchingHost;if(!d&&f&&jt(i)&&!i.endList)this.resetFragmentErrors(t),this.treatAsGap(i),r.resolved=!0;else if((d||f)&&l<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const m=Ea(c,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${m}ms`),r.resolved=!0,this.retryDate=self.performance.now()+m,this.state=N.FRAG_LOADING_WAITING_RETRY}else if(c&&r)if(this.resetFragmentErrors(t),l<c.maxNumRetry)!n&&o!==Xt.RemoveAlternatePermanently&&(r.resolved=!0);else{this.warn(`${e.details} reached or exceeded max retry (${l})`);return}else o===Xt.SendAlternateToPenaltyBox?this.state=N.WAITING_LEVEL:this.state=N.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===N.PARSING||this.state===N.PARSED){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),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!==N.STOPPED&&(this.state=N.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=ht.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===N.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==N.STOPPED&&(this.state=N.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((h,l)=>{const c=t.elementaryStreams[l];if(c){const u=c.endPTS-c.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${t.sn} ${l} duration reliably (${u})`),h||!1;const d=s?0:Sc(n,t,c.startPTS,c.endPTS,c.startDTS,c.endDTS);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:n,level:i,drift:d,type:l,frag:t,start:c.startPTS,end:c.endPTS}),!0}return h},!1)){var o;if(i.fragmentError===0&&this.treatAsGap(t,i),((o=this.transmuxer)==null?void 0:o.error)===null){const h=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(h.message),this.hls.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:h,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=N.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(v.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 Il(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Pc{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=Wv(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Wv(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 ar={exports:{}},Ll;function Jv(){return Ll||(Ll=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(h,l,c){this.fn=h,this.context=l,this.once=c||!1}function n(h,l,c,u,d){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,u||h,d),m=e?e+l:l;return h._events[m]?h._events[m].fn?h._events[m]=[h._events[m],f]:h._events[m].push(f):(h._events[m]=f,h._eventsCount++),h}function r(h,l){--h._eventsCount===0?h._events=new i:delete h._events[l]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)t.call(c,u)&&l.push(e?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},o.prototype.listeners=function(l){var c=e?e+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,m=new Array(f);d<f;d++)m[d]=u[d].fn;return m},o.prototype.listenerCount=function(l){var c=e?e+l:l,u=this._events[c];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,c,u,d,f,m){var p=e?e+l:l;if(!this._events[p])return!1;var g=this._events[p],E=arguments.length,A,y;if(g.fn){switch(g.once&&this.removeListener(l,g.fn,void 0,!0),E){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,c),!0;case 3:return g.fn.call(g.context,c,u),!0;case 4:return g.fn.call(g.context,c,u,d),!0;case 5:return g.fn.call(g.context,c,u,d,f),!0;case 6:return g.fn.call(g.context,c,u,d,f,m),!0}for(y=1,A=new Array(E-1);y<E;y++)A[y-1]=arguments[y];g.fn.apply(g.context,A)}else{var T=g.length,_;for(y=0;y<T;y++)switch(g[y].once&&this.removeListener(l,g[y].fn,void 0,!0),E){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,c);break;case 3:g[y].fn.call(g[y].context,c,u);break;case 4:g[y].fn.call(g[y].context,c,u,d);break;default:if(!A)for(_=1,A=new Array(E-1);_<E;_++)A[_-1]=arguments[_];g[y].fn.apply(g[y].context,A)}}return!0},o.prototype.on=function(l,c,u){return n(this,l,c,u,!1)},o.prototype.once=function(l,c,u){return n(this,l,c,u,!0)},o.prototype.removeListener=function(l,c,u,d){var f=e?e+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!d||m.once)&&(!u||m.context===u)&&r(this,f);else{for(var p=0,g=[],E=m.length;p<E;p++)(m[p].fn!==c||d&&!m[p].once||u&&m[p].context!==u)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:r(this,f)}return this},o.prototype.removeAllListeners=function(l){var c;return l?(c=e?e+l:l,this._events[c]&&r(this,c)):(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}(ar)),ar.exports}var Qv=Jv(),Sa=Py(Qv);const ys="1.6.5",Gi={};function qv(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Zv(){const a=Gi[ys];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 Gi[ys]=s,s}function tA(a){const t=Gi[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 Gi[a]=s,s}function eA(a){const t=Gi[a||ys];if(t&&t.clientCount--===1){const{worker:i,objectURL:s}=t;delete Gi[a||ys],s&&self.URL.revokeObjectURL(s),i.terminate()}}function wc(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 xa(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 wn(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 vs(a,t){const e=t;let i=0;for(;xa(a,t);){i+=10;const s=wn(a,t+6);i+=s,wc(a,t+10)&&(i+=10),t+=i}if(i>0)return a.subarray(e,e+i)}function iA(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 f=new Error(`invalid ADTS sampling index:${r}`);a.emit(v.ERROR,v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,h=t[e+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,c=s[r];let u=r;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|h<<3];return Tt.log(`manifest codec:${i}, parsed codec:${l}, channels:${h}, rate:${c} (ADTS object type:${o} sampling index:${r})`),{config:d,samplerate:c,channelCount:h,codec:l,parsedCodec:l,manifestCodec:i}}function Mc(a,t){return a[t]===255&&(a[t+1]&246)===240}function Bc(a,t){return a[t+1]&1?7:9}function Ca(a,t){return(a[t+3]&3)<<11|a[t+4]<<3|(a[t+5]&224)>>>5}function sA(a,t){return t+5<a.length}function _n(a,t){return t+1<a.length&&Mc(a,t)}function nA(a,t){return sA(a,t)&&Mc(a,t)&&Ca(a,t)<=a.length-t}function rA(a,t){if(_n(a,t)){const e=Bc(a,t);if(t+e>=a.length)return!1;const i=Ca(a,t);if(i<=e)return!1;const s=t+i;return s===a.length||_n(a,s)}return!1}function Oc(a,t,e,i,s){if(!a.samplerate){const n=iA(t,e,i,s);if(!n)return;bt(a,n)}}function Fc(a){return 1024*9e4/a}function aA(a,t){const e=Bc(a,t);if(t+e<=a.length){const i=Ca(a,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function kc(a,t,e,i,s){const n=Fc(a.samplerate),r=i+s*n,o=aA(t,e);let h;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,m=Math.max(0,e+f-t.length);m?(h=new Uint8Array(f-d),h.set(t.subarray(e+d,t.length),0)):h=t.subarray(e+d,e+f);const p={unit:h,pts:r};return m||a.samples.push(p),{sample:p,length:f,missing:m}}const l=t.length-e;return h=new Uint8Array(l),h.set(t.subarray(e,t.length),0),{sample:{unit:h,pts:r},length:l,missing:-1}}function oA(a,t){return xa(a,t)&&wn(a,t+6)+10<=a.length-t}function lA(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function or(a,t=0,e=1/0){return hA(a,t,e,Uint8Array)}function hA(a,t,e,i){const s=cA(a);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const r=uA(a)?a.byteOffset:0,o=(r+a.byteLength)/n,h=(r+t)/n,l=Math.floor(Math.max(0,Math.min(h,o))),c=Math.floor(Math.min(l+Math.max(e,0),o));return new i(s,l,c-l)}function cA(a){return a instanceof ArrayBuffer?a:a.buffer}function uA(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function dA(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(or(a.data,1,i)),n=a.data[2+i],r=a.data.subarray(3+i).indexOf(0);if(r===-1)return;const o=ae(or(a.data,3+i,r));let h;return s==="-->"?h=ae(or(a.data,4+i+r)):h=lA(a.data.subarray(4+i+r)),t.mimeType=s,t.pictureType=n,t.description=o,t.data=h,t}function fA(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 mA(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 pA(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 gA(a){return a.type==="PRIV"?fA(a):a.type[0]==="W"?pA(a):a.type==="APIC"?dA(a):mA(a)}function EA(a){const t=String.fromCharCode(a[0],a[1],a[2],a[3]),e=wn(a,4),i=10;return{type:t,size:e,data:a.subarray(i,i+e)}}const zs=10,yA=10;function Uc(a){let t=0;const e=[];for(;xa(a,t);){const i=wn(a,t+6);a[t+5]>>6&1&&(t+=zs),t+=zs;const s=t+i;for(;t+yA<s;){const n=EA(a.subarray(t)),r=gA(n);r&&e.push(r),t+=n.size+zs}wc(a,t)&&(t+=zs)}return e}function Nc(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function vA(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 ba(a){const t=Uc(a);for(let e=0;e<t.length;e++){const i=t[e];if(Nc(i))return vA(i)}}let ie=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 De(a="",t=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ia{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=pe(this.cachedData,t),this.cachedData=null);let i=vs(t,0),s=i?i.length:0,n;const r=this._audioTrack,o=this._id3Track,h=i?ba(i):void 0,l=t.length;for((this.basePTS===null||this.frameIndex===0&&q(h))&&(this.basePTS=AA(h,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:ie.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){const c=this.appendFrame(r,t,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=l}else oA(t,s)?(i=vs(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ie.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===l&&n!==l){const c=t.slice(n);this.cachedData?this.cachedData=pe(this.cachedData,c):this.cachedData=c}}return{audioTrack:r,videoTrack:De(),id3Track:o,textTrack:De()}}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:De(),id3Track:this._id3Track,textTrack:De()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const AA=(a,t,e)=>{if(q(a))return a*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};let Ys=null;const TA=[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],_A=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SA=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],xA=[0,1,1,4];function Gc(a,t,e,i,s){if(e+24>t.length)return;const n=Hc(t,e);if(n&&e+n.frameLength<=t.length){const r=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*r,h={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(h),{sample:h,length:n.frameLength,missing:0}}}function Hc(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,h=e===3?3-i:i===3?3:4,l=TA[h*14+s-1]*1e3,u=_A[(e===3?0:e===2?1:2)*3+n],d=o===3?1:2,f=SA[e][i],m=xA[i],p=f*8*m,g=Math.floor(f*l/u+r)*m;if(Ys===null){const y=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ys=y?parseInt(y[1]):0}return!!Ys&&Ys<=87&&i===2&&l>=224e3&&o===0&&(a[t+3]=a[t+3]|128),{sampleRate:u,channelCount:d,frameLength:g,samplesPerFrame:p}}}function La(a,t){return a[t]===255&&(a[t+1]&224)===224&&(a[t+1]&6)!==0}function $c(a,t){return t+1<a.length&&La(a,t)}function CA(a,t){return La(a,t)&&4<=a.length-t}function Kc(a,t){if(t+1<a.length&&La(a,t)){const i=Hc(a,t);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=t+s;return n===a.length||$c(a,n)}return!1}class bA extends Ia{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=vs(t,0);let s=(i==null?void 0:i.length)||0;if(Kc(t,s))return!1;for(let n=t.length;s<n;s++)if(rA(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return nA(t,e)}appendFrame(t,e,i){Oc(t,this.observer,e,i,t.manifestCodec);const s=kc(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const Vc=(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),h=8-o;n[0]=4278190080>>>24+h<<h,s[0]=(r[0]&n[0])>>h,e=e?e<<o|s[0]:s[0],t+=1,i-=o}return e};class IA extends Ia{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=zc(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=vs(t,0);if(!e)return!1;const i=e.length;return t[i]===11&&t[i+1]===119&&ba(e)!==void 0&&Vc(t,i)<16}}function zc(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],h=t[e+4]&63,c=[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][h*3+n]*2;if(e+c>t.length)return-1;const u=t[e+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(t[e+6]<<8|t[e+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+f,g=t[e+5]>>3,E=t[e+5]&7,A=new Uint8Array([n<<6|g<<1|E>>2,(E&3)<<6|u<<3|f<<2|h>>4,h<<4&224]),y=1536/o*9e4,T=i+s*y,_=t.subarray(e,e+c);return a.config=A,a.channelCount=p,a.samplerate=o,a.samples.push({unit:_,pts:T}),c}class LA extends Ia{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=vs(t,0);let i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&ba(e)!==void 0&&Vc(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(Kc(t,i))return Tt.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return CA(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return Gc(t,e,i,this.basePTS,this.frameIndex)}}const RA=/\/emsg[-/]ID3/i;class DA{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=De("video",1),r=this.audioTrack=De("audio",1),o=this.txtTrack=De("text",1);if(this.id3Track=De("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const h=sc(t);if(h.video){const{id:l,timescale:c,codec:u,supplemental:d}=h.video;n.id=l,n.timescale=o.timescale=c,n.codec=u,n.supplemental=d}if(h.audio){const{id:l,timescale:c,codec:u}=h.audio;r.id=l,r.timescale=c,r.codec=u}o.id=tc.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return Oy(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=pe(this.remainderData,t));const o=$y(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const r=this.extractID3Track(s,e);return n.samples=Jo(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=Jo(t,e),{videoTrack:e,audioTrack:De(),id3Track:s,textTrack:De()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=dt(t.samples,["emsg"]);s&&s.forEach(n=>{const r=Vy(n);if(RA.test(r.schemeIdUri)){const o=Rl(r,e);let h=r.eventDuration===4294967295?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;h<=.001&&(h=Number.POSITIVE_INFINITY);const l=r.payload;i.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:ie.emsg,duration:h})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Rl(r,e);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:o,pts:o,type:ie.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 Rl(a,t){return q(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale}class PA{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ya(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,ei.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 h=new Uint8Array(o);s.set(h,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=rc(n.data),o=this.getAvcEncryptedData(r);this.decryptBuffer(o.buffer).then(h=>{n.data=this.getAvcDecryptedUnit(r,h),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 Yc{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 h=0,l,c,u,d=-1,f=0;for(n===-1&&(d=0,f=this.getNALuType(e,0),n=0,h=1);h<s;){if(l=e[h++],!n){n=l?0:1;continue}if(n===1){n=l?0:2;continue}if(!l)n=3;else if(l===1){if(c=h-n-1,d>=0){const m={data:e.subarray(d,c),type:f};o.push(m)}else{const m=this.getLastNalUnit(t.samples);m&&(r&&h<=4-r&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-r)),c>0&&(m.data=pe(m.data,e.subarray(0,c)),m.state=0))}h<s?(u=this.getNALuType(e,h),d=h,f=u,n=0):n=-1}else n=0}if(d>=0&&n>=0){const m={data:e.subarray(d,s),type:f,state:n};o.push(m)}if(o.length===0){const m=this.getLastNalUnit(t.samples);m&&(m.data=pe(m.data,e))}return t.naluState=n,o}}class ms{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&&Tt.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 Dl extends Yc{parsePES(t,e,i,s){const n=this.parseNALu(t,i.data,s);let r=this.VideoSample,o,h=!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(l=>{var c,u;switch(l.type){case 1:{let p=!1;o=!0;const g=l.data;if(h&&g.length>4){const E=this.readSliceType(g);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){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=p;break}case 5:o=!0,(c=r)!=null&&c.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(l.data,1,i.pts,e.samples);break}case 7:{var f,m;o=!0,h=!0;const p=l.data,g=this.readSPS(p);if(!t.sps||t.width!==g.width||t.height!==g.height||((f=t.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=t.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){t.width=g.width,t.height=g.height,t.pixelRatio=g.pixelRatio,t.sps=[p];const E=p.subarray(1,4);let A="avc1.";for(let y=0;y<3;y++){let T=E[y].toString(16);T.length<2&&(T="0"+T),A+=T}t.codec=A}break}case 8:o=!0,t.pps=[l.data];break;case 9:o=!0,t.audFound=!0,(u=r)!=null&&u.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(l)}),s&&r&&(this.pushAccessUnit(r,t),this.VideoSample=null)}getNALuType(t,e){return t[e]&31}readSliceType(t){const e=new ms(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 ms(t);let i=0,s=0,n=0,r=0,o,h,l;const c=e.readUByte.bind(e),u=e.readBits.bind(e),d=e.readUEG.bind(e),f=e.readBoolean.bind(e),m=e.skipBits.bind(e),p=e.skipEG.bind(e),g=e.skipUEG.bind(e),E=this.skipScalingList.bind(this);c();const A=c();if(u(5),m(3),c(),g(),A===100||A===110||A===122||A===244||A===44||A===83||A===86||A===118||A===128){const I=d();if(I===3&&m(1),g(),g(),m(1),f())for(h=I!==3?8:12,l=0;l<h;l++)f()&&(l<6?E(16,e):E(64,e))}g();const y=d();if(y===0)d();else if(y===1)for(m(1),p(),p(),o=d(),l=0;l<o;l++)p();g(),m(1);const T=d(),_=d(),C=u(1);C===0&&m(1),m(1),f()&&(i=d(),s=d(),n=d(),r=d());let S=[1,1];if(f()&&f())switch(c()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[c()<<8|c(),c()<<8|c()];break}}return{width:Math.ceil((T+1)*16-i*2-s*2),height:(2-C)*(_+1)*16-(C?2:4)*(n+r),pixelRatio:S}}}class Pl extends Yc{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,h=!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(l=>{var c,u;switch(l.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,h){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,(c=r)!=null&&c.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(l.data,2,i.pts,e.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=bt(t.params,this.readVPS(l.data)),this.initVPS=l.data),t.vps=[l.data];break;case 33:if(o=!0,h=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],l.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const f=this.readSPS(l.data);t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.codec=f.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const m in f.params)t.params[m]=f.params[m]}this.pushParameterSet(t.sps,l.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 f=this.readPPS(l.data);for(const m in f)t.params[m]=f[m]}this.pushParameterSet(t.pps,l.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(u=r)!=null&&u.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(l)}),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 ms(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 ms(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(),h=e.readUByte(),l=e.readUByte(),c=e.readUByte(),u=e.readUByte(),d=e.readUByte(),f=e.readUByte(),m=e.readUByte(),p=e.readUByte(),g=e.readUByte(),E=e.readUByte(),A=[],y=[];for(let vt=0;vt<i;vt++)A.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let vt=i;vt<8;vt++)e.readBits(2);for(let vt=0;vt<i;vt++)A[vt]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[vt]&&e.readUByte();e.readUEG();const T=e.readUEG();T==3&&e.skipBits(1);const _=e.readUEG(),C=e.readUEG(),S=e.readBoolean();let I=0,L=0,b=0,w=0;S&&(I+=e.readUEG(),L+=e.readUEG(),b+=e.readUEG(),w+=e.readUEG());const O=e.readUEG(),H=e.readUEG(),Y=e.readUEG(),$=e.readBoolean();for(let vt=$?0:i;vt<=i;vt++)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 Jt=0;Jt<4;Jt++)for(let oe=0;oe<(Jt===3?2:6);oe++)if(!e.readBoolean())e.readUEG();else{const ge=Math.min(64,1<<4+(Jt<<1));Jt>1&&e.readEG();for(let gi=0;gi<ge;gi++)e.readEG()}e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const J=e.readUEG();let G=0;for(let vt=0;vt<J;vt++){let Jt=!1;if(vt!==0&&(Jt=e.readBoolean()),Jt){vt===J&&e.readUEG(),e.readBoolean(),e.readUEG();let oe=0;for(let ii=0;ii<=G;ii++){const ge=e.readBoolean();let gi=!1;ge||(gi=e.readBoolean()),(ge||gi)&&oe++}G=oe}else{const oe=e.readUEG(),ii=e.readUEG();G=oe+ii;for(let ge=0;ge<oe;ge++)e.readUEG(),e.readBoolean();for(let ge=0;ge<ii;ge++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const vt=e.readUEG();for(let Jt=0;Jt<vt;Jt++){for(let oe=0;oe<Y+4;oe++)e.readBits(1);e.readBits(1)}}let K=0,V=1,X=1,R=!0,tt=1,it=0;e.readBoolean(),e.readBoolean();let lt=!1;if(e.readBoolean()){if(e.readBoolean()){const si=e.readUByte(),Oa=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],xs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];si>0&&si<16?(V=Oa[si-1],X=xs[si-1]):si===255&&(V=e.readBits(16),X=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&&(I+=e.readUEG(),L+=e.readUEG(),b+=e.readUEG(),w+=e.readUEG()),e.readBoolean()&&(tt=e.readBits(32),it=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){const xs=e.readBoolean(),Fa=e.readBoolean();let zi=!1;(xs||Fa)&&(zi=e.readBoolean(),zi&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),zi&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let ka=0;ka<=i;ka++){R=e.readBoolean();const Vu=R||e.readBoolean();let Ua=!1;Vu?e.readEG():Ua=e.readBoolean();const Na=Ua?1:e.readUEG()+1;if(xs)for(let Yi=0;Yi<Na;Yi++)e.readUEG(),e.readUEG(),zi&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(Fa)for(let Yi=0;Yi<Na;Yi++)e.readUEG(),e.readUEG(),zi&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),K=e.readUEG())}let Wt=_,Xe=C;if(S||lt){let vt=1,Jt=1;T===1?vt=Jt=2:T==2&&(vt=2),Wt=_-vt*L-vt*I,Xe=C-Jt*w-Jt*b}const Vi=s?["A","B","C"][s]:"",Ku=o<<24|h<<16|l<<8|c;let Fn=0;for(let vt=0;vt<32;vt++)Fn=(Fn|(Ku>>vt&1)<<31-vt)>>>0;let kn=Fn.toString(16);return r===1&&kn==="2"&&(kn="6"),{codecString:`hvc1.${Vi}${r}.${kn}.${n?"H":"L"}${E}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[o,h,l,c],general_constraint_indicator_flags:[u,d,f,m,p,g],general_level_idc:E,bit_depth:O+8,bit_depth_luma_minus8:O,bit_depth_chroma_minus8:H,min_spatial_segmentation_idc:K,chroma_format_idc:T,frame_rate:{fixed:R,fps:it/tt}},width:Wt,height:Xe,pixelRatio:[V,X]}}readPPS(t){const e=new ms(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 Yt=188;class qe{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=qe.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(Yt*5,e-Yt)+1,s=0;for(;s<i;){let n=!1,r=-1,o=0;for(let h=s;h<e;h+=Yt)if(t[h]===71&&(e-h===Yt||t[h+Yt]===71)){if(o++,r===-1&&(r=h,r!==0&&(i=Math.min(r+Yt*99,t.length-Yt)+1)),n||(n=Kr(t,h)===0),n&&o>1&&(r===0&&o>2||h+Yt>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:tc[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=qe.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=qe.createTrack("audio",s),this._id3Track=qe.createTrack("id3"),this._txtTrack=qe.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,h=this._id3Track,l=this._txtTrack;let c=r.pid,u=r.pesData,d=o.pid,f=h.pid,m=o.pesData,p=h.pesData,g=null,E=this.pmtParsed,A=this._pmtId,y=t.length;if(this.remainderData&&(t=pe(this.remainderData,t),y=t.length,this.remainderData=null),y<Yt&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:r,id3Track:h,textTrack:l};const T=Math.max(0,qe.syncOffset(t));y-=(y-T)%Yt,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let _=0;for(let S=T;S<y;S+=Yt)if(t[S]===71){const I=!!(t[S+1]&64),L=Kr(t,S),b=(t[S+3]&48)>>4;let w;if(b>1){if(w=S+5+t[S+4],w===S+Yt)continue}else w=S+4;switch(L){case c:if(I){if(u&&(n=Li(u,this.logger))){if(this.videoParser===null)switch(r.segmentCodec){case"avc":this.videoParser=new Dl;break;case"hevc":this.videoParser=new Pl;break}this.videoParser!==null&&this.videoParser.parsePES(r,l,n,!1)}u={data:[],size:0}}u&&(u.data.push(t.subarray(w,S+Yt)),u.size+=S+Yt-w);break;case d:if(I){if(m&&(n=Li(m,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}m={data:[],size:0}}m&&(m.data.push(t.subarray(w,S+Yt)),m.size+=S+Yt-w);break;case f:I&&(p&&(n=Li(p,this.logger))&&this.parseID3PES(h,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(w,S+Yt)),p.size+=S+Yt-w);break;case 0:I&&(w+=t[w]+1),A=this._pmtId=wA(t,w);break;case A:{I&&(w+=t[w]+1);const O=MA(t,w,this.typeSupported,i,this.observer,this.logger);c=O.videoPid,c>0&&(r.pid=c,r.segmentCodec=O.segmentVideoCodec),d=O.audioPid,d>0&&(o.pid=d,o.segmentCodec=O.segmentAudioCodec),f=O.id3Pid,f>0&&(h.pid=f),g!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${g}'. Backtracking to sync byte @${T} to parse all TS packets.`),g=null,S=T-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=L;break}}else _++;_>0&&Vr(this.observer,new Error(`Found ${_} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=u,o.pesData=m,h.pesData=p;const C={audioTrack:o,videoTrack:r,id3Track:h,textTrack:l};return s&&this.extractRemainingSamples(C),C}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,h=s.pesData;let l;if(r&&(l=Li(r,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new Dl;break;case"hevc":this.videoParser=new Pl;break}this.videoParser!==null&&(this.videoParser.parsePES(i,n,l,!0),i.pesData=null)}else i.pesData=r;if(o&&(l=Li(o,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l);break}e.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;h&&(l=Li(h,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=h}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new PA(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 u=s.missing,d=s.sample.unit.byteLength;if(u===-1)n=pe(s.sample.unit,n);else{const f=d-u;s.sample.unit.set(n.subarray(0,u),f),t.samples.push(s.sample),i=s.missing}}let r,o;for(r=i,o=n.length;r<o-1&&!_n(n,r);r++);if(r!==i){let u;const d=r<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${r}`:u="No ADTS header found in AAC PES",Vr(this.observer,new Error(u),d,this.logger),!d)return}Oc(t,this.observer,n,r,this.audioCodec);let h;if(e.pts!==void 0)h=e.pts;else if(s){const u=Fc(t.samplerate);h=s.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,c;for(;r<o;)if(c=kc(t,n,r,h,l),r+=c.length,c.missing){this.aacOverFlow=c;break}else for(l++;r<o-1&&!_n(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($c(i,r)){const h=Gc(t,i,r,o,n);if(h)r+=h.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,h;for(;o<n&&(h=zc(t,i,o,s,r++))>0;)o+=h}}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=bt({},e,{type:this._videoTrack?ie.emsg:ie.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function Kr(a,t){return((a[t+1]&31)<<8)+a[t+2]}function wA(a,t){return(a[t+10]&31)<<8|a[t+11]}function MA(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],h=t+3+o-4,l=(a[t+10]&15)<<8|a[t+11];for(t+=12+l;t<h;){const c=Kr(a,t),u=(a[t+3]&15)<<8|a[t+4];switch(a[t]){case 207:if(!i){lr("ADTS AAC",n);break}case 15:r.audioPid===-1&&(r.audioPid=c);break;case 21:r.id3Pid===-1&&(r.id3Pid=c);break;case 219:if(!i){lr("H.264",n);break}case 27:r.videoPid===-1&&(r.videoPid=c);break;case 3:case 4:!e.mpeg&&!e.mp3?n.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="mp3");break;case 193:if(!i){lr("AC-3",n);break}case 129:e.ac3?r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&u>0){let d=t+5,f=u;for(;f>2;){switch(a[d]){case 106:e.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3");break}const p=a[d+1]+2;d+=p,f-=p}}break;case 194:case 135:return Vr(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),r;case 36:r.videoPid===-1&&(r.videoPid=c,r.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}t+=u+5}return r}function Vr(a,t,e,i){i.warn(`parsing error: ${t.message}`),a.emit(v.ERROR,v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:t,reason:t.message})}function lr(a,t){t.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Li(a,t){let e=0,i,s,n,r,o;const h=a.data;if(!a||a.size===0)return null;for(;h[0].length<19&&h.length>1;)h[0]=pe(h[0],h[1]),h.splice(1,1);if(i=h[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 c=i[7];c&192&&(r=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&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 u=n+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let f=0,m=h.length;f<m;f++){i=h[f];let p=i.byteLength;if(u)if(u>p){u-=p;continue}else i=i.subarray(u),p-=u,u=0;d.set(i,e),e+=p}return s&&(s-=n+3),{data:d,pts:r,dts:o,len:s}}return null}class BA{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 je=Math.pow(2,32)-1;class D{static init(){D.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 D.types)D.types.hasOwnProperty(t)&&(D.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]);D.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]);D.STTS=D.STSC=D.STCO=n,D.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),D.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),D.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),D.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]),h=new Uint8Array([0,0,0,1]);D.FTYP=D.box(D.types.ftyp,r,h,r,o),D.DINF=D.box(D.types.dinf,D.box(D.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 D.box(D.types.hdlr,D.HDLR_TYPES[t])}static mdat(t){return D.box(D.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(je+1)),s=Math.floor(e%(je+1));return D.box(D.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 D.box(D.types.mdia,D.mdhd(t.timescale||0,t.duration||0),D.hdlr(t.type),D.minf(t))}static mfhd(t){return D.box(D.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"?D.box(D.types.minf,D.box(D.types.smhd,D.SMHD),D.DINF,D.stbl(t)):D.box(D.types.minf,D.box(D.types.vmhd,D.VMHD),D.DINF,D.stbl(t))}static moof(t,e,i){return D.box(D.types.moof,D.mfhd(t),D.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=D.trak(t[e]);return D.box.apply(null,[D.types.moov,D.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(D.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=D.trex(t[e]);return D.box.apply(null,[D.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(je+1)),s=Math.floor(e%(je+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 D.box(D.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 D.box(D.types.sdtp,i)}static stbl(t){return D.box(D.types.stbl,D.stsd(t),D.box(D.types.stts,D.STTS),D.box(D.types.stsc,D.STSC),D.box(D.types.stsz,D.STSZ),D.box(D.types.stco,D.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=D.box(D.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),h=t.width,l=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return D.box(D.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,h>>8&255,h&255,l>>8&255,l&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,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,u>>24,u>>16&255,u>>8&255,u&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 D.box(D.types.mp4a,D.audioStsd(t),D.box(D.types.esds,D.esds(t)))}static mp3(t){return D.box(D.types[".mp3"],D.audioStsd(t))}static ac3(t){return D.box(D.types["ac-3"],D.audioStsd(t),D.box(D.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return D.box(D.types.stsd,D.STSD,D.mp4a(t));if(e==="ac3"&&t.config)return D.box(D.types.stsd,D.STSD,D.ac3(t));if(e==="mp3"&&t.codec==="mp3")return D.box(D.types.stsd,D.STSD,D.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return D.box(D.types.stsd,D.STSD,D.avc1(t));if(e==="hevc"&&t.vps)return D.box(D.types.stsd,D.STSD,D.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/(je+1)),o=Math.floor(i%(je+1));return D.box(D.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=D.sdtp(t),s=t.id,n=Math.floor(e/(je+1)),r=Math.floor(e%(je+1));return D.box(D.types.traf,D.box(D.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),D.box(D.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])),D.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,D.box(D.types.trak,D.tkhd(t),D.mdia(t))}static trex(t){const e=t.id;return D.box(D.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,h,l,c,u,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++)h=i[o],l=h.duration,c=h.size,u=h.flags,d=h.cts,r.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return D.box(D.types.trun,r)}static initSegment(t){D.types||D.init();const e=D.moov(t);return pe(D.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 m=0;m<i.length;m+=1){r+=3;for(let p=0;p<i[m].length;p+=1)r+=2+i[m][p].length}const o=new Uint8Array(r);o.set(n,0),r=n.length;const h=i.length-1;for(let m=0;m<i.length;m+=1){o.set(new Uint8Array([32+m|(m===h?128:0),0,i[m].length]),r),r+=3;for(let p=0;p<i[m].length;p+=1)o.set(new Uint8Array([i[m][p].length>>8,i[m][p].length&255]),r),r+=2,o.set(i[m][p],r),r+=i[m][p].length}const l=D.box(D.types.hvcC,o),c=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return D.box(D.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,c>>8&255,c&255,u>>8&255,u&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]),l,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}D.types=void 0;D.HDLR_TYPES=void 0;D.STTS=void 0;D.STSC=void 0;D.STCO=void 0;D.STSZ=void 0;D.VMHD=void 0;D.SMHD=void 0;D.STSD=void 0;D.FTYP=void 0;D.DINF=void 0;const Xc=9e4;function Ra(a,t,e=1,i=!1){const s=a*t*e;return i?Math.round(s):s}function OA(a,t,e=1,i=!1){return Ra(a,t,1/e,i)}function as(a,t=!1){return Ra(a,1e3,1/Xc,t)}function FA(a,t=1){return Ra(a,Xc,1/t)}const kA=10*1e3,UA=1024,NA=1152,GA=1536;let Ri=null,hr=null;function wl(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 rn{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,Ri===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ri=r?parseInt(r[1]):0}if(hr===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);hr=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,h=o-n;return h<-4294967296&&(e=!0,o=fe(o,i),h=o-n),h>0?n:o},i);return e&&this.logger.debug("PTS rollover detected"),s}remux(t,e,i,s,n,r,o,h){let l,c,u,d,f,m,p=n,g=n;const E=t.pid>-1,A=e.pid>-1,y=e.samples.length,T=t.samples.length>0,_=o&&y>0||y>1;if((!E||T)&&(!A||_)||this.ISGenerated||o){if(this.ISGenerated){var S,I,L,b;const Y=this.videoTrackConfig;(Y&&(e.width!==Y.width||e.height!==Y.height||((S=e.pixelRatio)==null?void 0:S[0])!==((I=Y.pixelRatio)==null?void 0:I[0])||((L=e.pixelRatio)==null?void 0:L[1])!==((b=Y.pixelRatio)==null?void 0:b[1]))||!Y&&_||this.nextAudioPts===null&&T)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,e,n,r));const w=this.isVideoContiguous;let O=-1,H;if(_&&(O=HA(e.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,O>0){this.logger.warn(`[mp4-remuxer]: Dropped ${O} out of ${y} video samples due to a missing keyframe`);const Y=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(O),e.dropped+=O,g+=(e.samples[0].pts-Y)/e.inputTimeScale,H=g}else O===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),m=!1);if(this.ISGenerated){if(T&&_){const Y=this.getVideoStartPts(e.samples),z=(fe(t.samples[0].pts,Y)-Y)/e.inputTimeScale;p+=Math.max(0,z),g+=Math.max(0,-z)}if(T){if(t.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(t,e,n,r)),c=this.remuxAudio(t,p,this.isAudioContiguous,r,A||_||h===Z.AUDIO?g:void 0),_){const Y=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(t,e,n,r)),l=this.remuxVideo(e,g,w,Y)}}else _&&(l=this.remuxVideo(e,g,w,0));l&&(l.firstKeyFrame=O,l.independent=O!==-1,l.firstKeyFramePTS=H)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=jc(i,n,this._initPTS,this._initDTS)),s.samples.length&&(d=Wc(s,n,this._initPTS))),{audio:c,video:l,initSegment:u,independent:m,text:d,id3:f}}generateIS(t,e,i,s){const n=t.samples,r=e.samples,o=this.typeSupported,h={},l=this._initPTS;let c=!l||s,u="audio/mp4",d,f,m,p;if(c&&(d=f=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}h.audio={id:"audio",container:u,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):D.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(p=t.id,m=t.inputTimeScale,!l||m!==l.timescale?d=f=n[0].pts-Math.round(m*i):c=!1)}if(e.sps&&e.pps&&r.length){if(e.timescale=e.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:D.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(p=e.id,m=e.inputTimeScale,!l||m!==l.timescale){const g=this.getVideoStartPts(r),E=Math.round(m*i);f=Math.min(f,fe(r[0].dts,g)-E),d=Math.min(d,g-E)}else c=!1;this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:d,timescale:m},this._initDTS={baseTime:f,timescale:m}):d=m=void 0,{tracks:h,initPTS:d,timescale:m,trackId:p}}remuxVideo(t,e,i,s){const n=t.inputTimeScale,r=t.samples,o=[],h=r.length,l=this._initPTS;let c=this.nextAvcDts,u=8,d=this.videoSampleDuration,f,m,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,E=!1;if(!i||c===null){const G=e*n,U=r[0].pts-fe(r[0].dts,r[0].pts);Ri&&c!==null&&Math.abs(G-U-c)<15e3?i=!0:c=G-U}const A=l.baseTime*n/l.timescale;for(let G=0;G<h;G++){const U=r[G];U.pts=fe(U.pts-A,c),U.dts=fe(U.dts-A,c),U.dts<r[G>0?G-1:G].dts&&(E=!0)}E&&r.sort(function(G,U){const K=G.dts-U.dts,V=G.pts-U.pts;return K||V}),f=r[0].dts,m=r[r.length-1].dts;const y=m-f,T=y?Math.round(y/(h-1)):d||t.inputTimeScale/30;if(i){const G=f-c,U=G>T,K=G<-1;if((U||K)&&(U?this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${as(G,!0)} ms (${G}dts) hole between fragments detected at ${e.toFixed(3)}`):this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${as(-G,!0)} ms (${G}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!K||c>=r[0].pts||Ri)){f=c;const V=r[0].pts-G;if(U)r[0].dts=f,r[0].pts=V;else{let X=!0;for(let R=0;R<r.length&&!(r[R].dts>V&&X);R++){const tt=r[R].pts;if(r[R].dts-=G,r[R].pts-=G,R<r.length-1){const it=r[R+1].pts,lt=r[R].pts,It=it<=lt,Wt=it<=tt;X=It==Wt}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${as(V,!0)}/${as(f,!0)}, delta: ${as(G,!0)} ms`)}}f=Math.max(0,f);let _=0,C=0,S=f;for(let G=0;G<h;G++){const U=r[G],K=U.units,V=K.length;let X=0;for(let R=0;R<V;R++)X+=K[R].data.length;C+=X,_+=V,U.length=X,U.dts<S?(U.dts=S,S+=T/4|0||1):S=U.dts,p=Math.min(U.pts,p),g=Math.max(U.pts,g)}m=r[h-1].dts;const I=C+4*_+8;let L;try{L=new Uint8Array(I)}catch(G){this.observer.emit(v.ERROR,v.ERROR,{type:et.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:G,bytes:I,reason:`fail allocating video mdat ${I}`});return}const b=new DataView(L.buffer);b.setUint32(0,I),L.set(D.types.mdat,4);let w=!1,O=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,Y=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY;for(let G=0;G<h;G++){const U=r[G],K=U.units;let V=0;for(let tt=0,it=K.length;tt<it;tt++){const lt=K[tt],It=lt.data,Wt=lt.data.byteLength;b.setUint32(u,Wt),u+=4,L.set(It,u),u+=Wt,V+=4+Wt}let X;if(G<h-1)d=r[G+1].dts-U.dts,X=r[G+1].pts-U.pts;else{const tt=this.config,it=G>0?U.dts-r[G-1].dts:T;if(X=G>0?U.pts-r[G-1].pts:T,tt.stretchShortVideoTrack&&this.nextAudioPts!==null){const lt=Math.floor(tt.maxBufferHole*n),It=(s?p+s*n:this.nextAudioPts)-U.pts;It>lt?(d=It-it,d<0?d=it:w=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${It/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(U.pts-U.dts);O=Math.min(O,d),Y=Math.max(Y,d),H=Math.min(H,X),$=Math.max($,X),o.push(wl(U.key,d,V,R))}if(o.length){if(Ri){if(Ri<70){const G=o[0].flags;G.dependsOn=2,G.isNonSync=0}}else if(hr&&$-H<Y-O&&T/Y<.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 G=f;for(let U=0,K=o.length;U<K;U++){const V=G+o[U].duration,X=G+o[U].cts;if(U<K-1){const R=V+o[U+1].cts;o[U].duration=R-X}else o[U].duration=U?o[U-1].duration:T;o[U].cts=0,G=V}}}d=w||!d?T:d,this.nextAvcDts=c=m+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const J={data1:D.moof(t.sequenceNumber++,f,bt(t,{samples:o})),data2:L,startPTS:p/n,endPTS:(g+d)/n,startDTS:f/n,endDTS:c/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 NA;case"ac3":return GA;default:return UA}}remuxAudio(t,e,i,s,n){const r=t.inputTimeScale,o=t.samplerate?t.samplerate:r,h=r/o,l=this.getSamplesPerFrame(t),c=l*h,u=this._initPTS,d=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0;let p=t.samples,g=d?0:8,E=this.nextAudioPts||-1;const A=e*r,y=u.baseTime*r/u.timescale;if(this.isAudioContiguous=i=i||p.length&&E>0&&(s&&Math.abs(A-E)<9e3||Math.abs(fe(p[0].pts-y,A)-E)<20*c),p.forEach(function(z){z.pts=fe(z.pts-y,A)}),!i||E<0){if(p=p.filter(z=>z.pts>=0),!p.length)return;n===0?E=0:s&&!m?E=Math.max(0,A):E=p[0].pts}if(t.segmentCodec==="aac"){const z=this.config.maxAudioFramesDrift;for(let W=0,J=E;W<p.length;W++){const G=p[W],U=G.pts,K=U-J,V=Math.abs(1e3*K/r);if(K<=-z*c&&m)W===0&&(this.logger.warn(`Audio frame @ ${(U/r).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*K/r)} ms.`),this.nextAudioPts=E=J=U);else if(K>=z*c&&V<kA&&m){let X=Math.round(K/c);J=U-X*c,J<0&&(X--,J+=c),W===0&&(this.nextAudioPts=E=J),this.logger.warn(`[mp4-remuxer]: Injecting ${X} audio frame @ ${(J/r).toFixed(3)}s due to ${Math.round(1e3*K/r)} ms gap.`);for(let R=0;R<X;R++){const tt=Math.max(J,0);let it=BA.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=G.unit.subarray()),p.splice(W,0,{unit:it,pts:tt}),J+=c,W++}}G.pts=J,J+=c}}let T=null,_=null,C,S=0,I=p.length;for(;I--;)S+=p[I].unit.byteLength;for(let z=0,W=p.length;z<W;z++){const J=p[z],G=J.unit;let U=J.pts;if(_!==null){const V=f[z-1];V.duration=Math.round((U-_)/h)}else if(i&&t.segmentCodec==="aac"&&(U=E),T=U,S>0){S+=g;try{C=new Uint8Array(S)}catch(V){this.observer.emit(v.ERROR,v.ERROR,{type:et.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:S,reason:`fail allocating audio mdat ${S}`});return}d||(new DataView(C.buffer).setUint32(0,S),C.set(D.types.mdat,4))}else return;C.set(G,g);const K=G.byteLength;g+=K,f.push(wl(!0,l,K,0)),_=U}const L=f.length;if(!L)return;const b=f[f.length-1];this.nextAudioPts=E=_+h*b.duration;const w=d?new Uint8Array(0):D.moof(t.sequenceNumber++,T/h,bt({},t,{samples:f}));t.samples=[];const O=T/r,H=E/r,$={data1:w,data2:C,startPTS:O,endPTS:H,startDTS:O,endDTS:H,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,$}}function fe(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 HA(a){for(let t=0;t<a.length;t++)if(a[t].key)return t;return-1}function jc(a,t,e,i){const s=a.samples.length;if(!s)return;const n=a.inputTimeScale;for(let o=0;o<s;o++){const h=a.samples[o];h.pts=fe(h.pts-e.baseTime*n/e.timescale,t*n)/n,h.dts=fe(h.dts-i.baseTime*n/i.timescale,t*n)/n}const r=a.samples;return a.samples=[],{samples:r}}function Wc(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=fe(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 $A{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.isVideoContiguous=!1,this.logger=s}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(Ny(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=sc(t);s.audio&&(e=Ml(s.audio,Rt.AUDIO,this.logger)),s.video&&(i=Ml(s.video,Rt.VIDEO,this.logger));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,h;let{initPTS:l,lastEndTime:c}=this;const u={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};q(c)||(c=this.lastEndTime=n||0);const d=e.samples;if(!(d!=null&&d.length))return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(d),m=this.initData),!((h=m)!=null&&h.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Gy(d,m,this.logger),g=m.audio?p[m.audio.id]:null,E=m.video?p[m.video.id]:null,A=Xs(E,1/0),y=Xs(g,1/0),T=Xs(E,0,!0),_=Xs(g,0,!0);let C,S=n,I=0;if(g&&(!E||!l&&y<A||l&&l.trackId===m.audio.id)?(f.trackId=m.audio.id,C=g,I=_-y):E&&(f.trackId=m.video.id,C=E,I=T-A),C){const z=C.timescale;S=C.start/z,f.timescale=z,l||(f.initPTS=C.start-n*z,this.initPTS=l={baseTime:f.initPTS,timescale:z,trackId:f.trackId})}(r||!l)&&(KA(l,S,n,I)||f.timescale!==l.timescale)&&(f.initPTS=S-n,l&&l.timescale===1&&this.logger.warn(`Adjusting initPTS @${n} from ${l.baseTime/l.timescale} to ${f.initPTS}`),this.initPTS=l={baseTime:f.initPTS,timescale:1});const L=t?S-l.baseTime/l.timescale:c;Hy(m,d,l.baseTime/l.timescale);const b=L+I;I>0?this.lastEndTime=b:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!m.audio,O=!!m.video;let H="";w&&(H+="audio"),O&&(H+="video");const Y={data1:d,startPTS:L,startDTS:L,endPTS:b,endDTS:b,type:H,hasAudio:w,hasVideo:O,nb:1,dropped:0};u.audio=w&&!O?Y:void 0,u.video=O?Y:void 0;const $=E==null?void 0:E.sampleCount;if($){const z=E.keyFrameIndex,W=z!==-1;Y.nb=$,Y.dropped=z===0||this.isVideoContiguous?0:W?z:$,Y.independent=W,Y.firstKeyFrame=z,W&&E.keyFrameStart&&(Y.firstKeyFramePTS=E.keyFrameStart-l.baseTime/l.timescale),this.isVideoContiguous||(u.independent=W),this.isVideoContiguous||(this.isVideoContiguous=W),Y.dropped&&this.logger.warn(`fmp4 does not start with IDR: firstIDR ${z}/${$} dropped: ${Y.dropped} pts: ${Y.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=jc(i,n,l,l),s.samples.length&&(u.text=Wc(s,n,l)),u}}function Xs(a,t,e=!1){return(a==null?void 0:a.start)!==void 0?(a.start+(e?a.duration:0))/a.timescale:t}function KA(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 Ml(a,t,e){const i=a==null?void 0:a.codec;return i&&i.length>4?i:t===Rt.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?pn(i,!1):(e.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(e.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Ne;try{Ne=self.performance.now.bind(self.performance)}catch{Ne=Date.now}const an=[{demux:DA,remux:$A},{demux:qe,remux:rn},{demux:bA,remux:rn},{demux:LA,remux:rn}];an.splice(2,0,{demux:IA,remux:rn});class Bl{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:h}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:c,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:m}=s||o,{audioCodec:p,videoCodec:g,defaultInitPts:E,duration:A,initSegmentData:y}=h,T=VA(r,e);if(T&&Oi(T.method)){const I=this.getDecrypter(),L=Aa(T.method);if(I.isSync()){let b=I.softwareDecrypt(r,T.key.buffer,T.iv.buffer,L);if(i.part>-1){const O=I.flush();b=O&&O.buffer}if(!b)return n.executeEnd=Ne(),cr(i);r=new Uint8Array(b)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(r,T.key.buffer,T.iv.buffer,L).then(b=>{const w=this.push(b,null,i);return this.decryptionPromise=null,w}),this.decryptionPromise}const _=this.needsProbing(c,u);if(_){const I=this.configureTransmuxer(r);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),n.executeEnd=Ne(),cr(i)}(c||u||m||_)&&this.resetInitSegment(y,p,g,A,e),(c||m||_)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const C=this.transmux(r,T,f,d,i);this.asyncResult=As(C);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Ne(),C}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 u=i.flush();u&&r.push(this.push(u.buffer,null,t))}const{demuxer:h,remuxer:l}=this;if(!h||!l){e.executeEnd=Ne();const u=[cr(t)];return this.asyncResult?Promise.resolve(u):u}const c=h.flush(o);return As(c)?(this.asyncResult=!0,c.then(u=>(this.flushRemux(r,u,t),r))):(this.flushRemux(r,c,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:n,id3Track:r,textTrack:o}=e,{accurateTimeOffset:h,timeOffset:l}=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 c=this.remuxer.remux(s,n,r,o,l,h,!0,this.id);t.push({remuxResult:c,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:h}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,o,h,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 u=0,d=an.length;u<d;u++){var r;if((r=an[u].demux)!=null&&r.probe(t,this.logger)){n=an[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,h=this.remuxer,l=n.remux,c=n.demux;(!h||!(h instanceof l))&&(this.remuxer=new l(i,e,s,this.logger)),(!o||!(o instanceof c))&&(this.demuxer=new c(i,e,s,this.logger),this.probe=c.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new ya(this.config)),t}}function VA(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 cr=a=>({remuxResult:{},chunkMeta:a});function As(a){return"then"in a&&a.then instanceof Function}class zA{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 YA{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 Ol=0;class Jc{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ol++,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=h=>{const l=h.data,c=this.hls;if(!(!c||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{c.logger[l.data.logType]&&c.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,c.trigger(l.event,l.data);break}}},this.onWorkerError=h=>{if(!this.hls)return;const l=new Error(`${h.message} (${h.filename}:${h.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const r=(h,l)=>{l=l||{},l.frag=this.frag||void 0,h===v.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(h,l)};this.observer=new Sa,this.observer.on(v.FRAG_DECRYPTED,r),this.observer.on(v.ERROR,r);const o=qo(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const h=this.hls.logger;if(n.workerPath||qv()){try{n.workerPath?(h.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=tA(n.workerPath)):(h.log(`injecting Web Worker for "${e}"`),this.workerContext=Zv());const{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:Bt(n)})}catch(c){h.warn(`Error setting up "${e}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new Bl(this.observer,o,n,"",e,t.logger)}return}}this.transmuxer=new Bl(this.observer,o,n,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Ol++;const e=this.hls.config,i=qo(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Bt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),eA(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,h,l,c){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:m}=this,p=r?r.start:n.start,g=n.decryptdata,E=this.frag,A=!(E&&n.cc===E.cc),y=!(E&&l.level===E.level),T=E?l.sn-E.sn:-1,_=this.part?l.part-this.part.index:-1,C=T===0&&l.id>1&&l.id===(E==null?void 0:E.stats.chunkCount),S=!y&&(T===1||T===0&&(_===1||C&&_<=0)),I=self.performance.now();(y||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=I),r&&(_||!S)&&(r.stats.parsing.start=I);const L=!(E&&((u=n.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),b=new YA(A,S,h,y,p,L);if(!S||A||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Z.MAIN?"level":"track"}: ${l.level} id: ${l.id}
24
+ discontinuity: ${A}
25
+ trackSwitch: ${y}
26
+ contiguous: ${S}
27
+ accurateTimeOffset: ${h}
28
+ timeOffset: ${p}
29
+ initSegmentChange: ${L}`);const w=new zA(i,s,e,o,c);this.configureTransmuxer(w)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(m){const w=m.push(t,g,l,b);As(w)?w.then(O=>{this.handleTransmuxComplete(O)}).catch(O=>{this.transmuxerError(O,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}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);As(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(v.ERROR,{type:et.MEDIA_ERROR,details:P.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 Fl=100;class Qc extends Pn{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(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(v.BUFFER_RESET,this.onBufferReset,this),t.on(v.BUFFER_CREATED,this.onBufferCreated,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(v.FRAG_LOADING,this.onFragLoading,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(v.BUFFER_RESET,this.onBufferReset,this),t.off(v.BUFFER_CREATED,this.onBufferCreated,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(v.FRAG_LOADING,this.onFragLoading,this),t.off(v.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===N.WAITING_INIT_PTS){const h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==r)&&this.syncWithAnchor(e,h==null?void 0:h.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==r?(o.abortRequests(),this.syncWithAnchor(e,o)):this.state===N.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(e&&(s==null?void 0:s.cc)===e.cc)return;const n=(s||t).cc,r=this.getLevelDetails(),o=this.getLoadPosition(),h=gc(r,n,o);h&&(this.log(`Waiting fragment cc (${e==null?void 0:e.cc}) cancelled because video is at cc ${t.cc}`),this.startFragRequested=!1,this.nextLoadPosition=h.start,this.resetLoadingState(),this.state===N.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels){this.startPosition=t,this.state=N.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Fl),i>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=N.IDLE):this.state=N.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case N.IDLE:this.doTickIdle();break;case N.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=N.WAITING_INIT_PTS}break}case N.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=N.IDLE}break}case N.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=N.FRAG_LOADING;const h=n.flush().buffer,l={frag:i,part:s,payload:h,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=N.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),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],h=o.details;if(!h||this.waitForLive(o)||this.waitForCdnTuneIn(h)){this.state=N.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Rt.AUDIO,Z.AUDIO));const c=this.getFwdBufferInfo(l,Z.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,h)){e.trigger(v.BUFFER_EOS,{type:"audio"}),this.state=N.ENDED;return}const u=c.len,d=e.maxBufferLength,f=h.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:c.end;if(this.switchingTrack&&s){const y=p;h.PTSKnown&&y<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}if(u>=d&&!this.switchingTrack&&g<f[f.length-1].start)return;let E=this.getNextFragment(g,h);if(E&&this.isLoopLoading(E,g)&&(E=this.getNextFragmentLoopLoading(E,h,c,Z.MAIN,d)),!E){this.bufferFlushed=!0;return}let A=((t=this.mainFragLoading)==null?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&A&&jt(E)&&!E.endList&&(!h.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(A)===Vt.OK&&(this.mainFragLoading=A=null),A&&jt(A))){if(E.start>A.end){const T=this.fragmentTracker.getFragAtPos(g,Z.MAIN);T&&T.end>A.end&&(A=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(E.start>A.end)return}this.loadFragment(E,o,g)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(i=>new Ui(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!==N.STOPPED&&(this.setInterval(Fl),this.state=N.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(v.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:n,id:r,groupId:o,track:h}=e;if(!s){this.warn(`Audio tracks reset while loading track ${r} "${h.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=e,this.state!==N.STOPPED&&(this.state=N.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${h.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const c=s[r];let u=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var d;u=this.alignPlaylists(n,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}n.alignedSliding||(Dc(n,l),n.alignedSliding||Tn(n,l),u=n.fragmentStart)}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(v.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:e.groupId}),this.state===N.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=N.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{config:r,trackId:o,levels:h}=this;if(!h){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 l=h[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const c=l.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const u=r.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Jc(this.hls,Z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],m=(e=i.initSegment)==null?void 0:e.data;if(f!==void 0){const g=s?s.index:-1,E=g!==-1,A=new Dn(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,E);d.push(n,m,u,"",i,s,c.totalduration,!1,A,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Pc,complete:!1};p.push(new Uint8Array(n)),this.state!==N.STOPPED&&(this.state=N.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&&jt(e.frag)&&(this.mainFragLoading=e,this.state===N.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(jt(i)){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(v.AUDIO_TRACK_SWITCHED,xt({},n)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(t,e){var i;if(e.fatal){this.state=N.ERROR;return}switch(e.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.AUDIO,e);break;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===N.WAITING_TRACK&&((i=e.context)==null?void 0:i.type)===pt.AUDIO_TRACK&&(this.state=N.IDLE);break;case P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(e.parent!=="audio")return;this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushing(t,{type:e}){e!==Rt.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Rt.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===N.ENDED&&(this.state=N.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,e,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:h,part:l,level:c}=o,{details:u}=c,{audio:d,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(h)||!u){this.fragmentTracker.removeFragment(h);return}if(this.state=N.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const g=h.initSegment||h;this._bufferInitSegment(c,p.tracks,g,r),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:p.tracks})}if(d){const{startPTS:g,endPTS:E,startDTS:A,endDTS:y}=d;l&&(l.elementaryStreams[Rt.AUDIO]={startPTS:g,endPTS:E,startDTS:A,endDTS:y}),h.setElementaryStreamInfo(Rt.AUDIO,g,E,A,y),this.bufferFragmentData(d,h,l,r)}if(m!=null&&(e=m.samples)!=null&&e.length){const g=bt({id:i,frag:h,details:u},m);s.trigger(v.FRAG_PARSING_METADATA,g)}if(f){const g=bt({id:i,frag:h,details:u},f);s.trigger(v.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(t,e,i,s){if(this.state!==N.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(v.BUFFER_CODECS,e);const o=n.initSegment;if(o!=null&&o.byteLength){const h={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(v.BUFFER_APPENDING,h)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);if(this.switchingTrack||s===Vt.NOT_LOADED||s===Vt.PARTIAL){var n;if(!jt(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=N.WAITING_INIT_PTS;const r=this.mainDetails;r&&r.fragmentStart!==e.details.fragmentStart&&Tn(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;fi({name:e,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o},t,di)||(En(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(v.AUDIO_TRACK_SWITCHED,xt({},t))}}class Mn extends Ye{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 h;try{h=new self.URL(o.URI,e.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),h=o.URI||""}if(h===t){n=r;break}else h===t.substring(0,h.length)&&(n=r)}if(n!==-1){const r=s[n],o=parseInt(r["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let h=parseInt(r["LAST-PART"])||(e==null?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const c=Math.min(e.age-e.partTarget,e.targetduration);h>=0&&c>e.partTarget&&(h+=1)}const l=i&&tl(i);return new Ur(o,h>=0?h:void 0,l)}}}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 h=this.hls.config.timelineOffset;if(h!==s.appliedTimelineOffset){const c=Math.max(h||0,0);s.appliedTimelineOffset=c,s.fragments.forEach(u=>{u.start=u.playlistOffset+c})}if(s.live||i!=null&&i.live){const c="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){$v(i,s);const A=s.playlistParsingError;if(A){this.warn(A);const y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var l;const{networkDetails:T}=e;y.trigger(v.ERROR,{type:et.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:A,reason:A.message,level:e.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:T,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(s.edge-d)*1e3,m=Cc(s,f);if(s.requestScheduled+m<r?s.requestScheduled=r:s.requestScheduled+=m,this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let p,g,E;if(s.canBlockReload&&s.endSN&&s.advanced){const A=this.hls.config.lowLatencyMode,y=s.lastPartSn,T=s.endSN,_=s.lastPartIndex,C=_!==-1,S=y===T;C?S?(g=T+1,E=A?0:_):(g=y,E=A?_+1:s.maxPartIndex):g=T+1;const I=s.age,L=I+s.ageHeader;let b=Math.min(L-s.partTarget,s.targetduration*1.5);if(b>0){if(L>s.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,E=void 0;else if(i!=null&&i.tuneInGoal&&L-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${b} with playlist age: ${s.age}`),b=0;else{const w=Math.floor(b/s.targetduration);if(g+=w,E!==void 0){const O=Math.round(b%s.targetduration/s.partTarget);E+=O}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${b} skip sn ${w} to part ${E}`)}s.tuneInGoal=b}if(p=this.getDeliveryDirectives(s,e.deliveryDirectives,g,E),A||!S){s.requestScheduled=r,this.loadingPlaylist(c,p);return}}else(s.canBlockReload||s.canSkipUntil)&&(p=this.getDeliveryDirectives(s,e.deliveryDirectives,g,E));p&&g!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(c,p,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=tl(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=ds.No),new Ur(i,s,n)}checkRetry(t){const e=t.details,i=yn(t),s=t.errorAction,{action:n,retryCount:r=0,retryConfig:o}=s||{},h=!!s&&!!o&&(n===Xt.RetryRequest||!s.resolved&&n===Xt.SendAlternateToPenaltyBox);if(h){var l;if(r>=o.maxNumRetry)return!1;if(i&&(l=t.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const c=Ea(o,r);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${e}" in ${c}ms`)}t.levelRetry=!0,s.resolved=!0}return h}}function qc(a,t){if(a.length!==t.length)return!1;for(let e=0;e<a.length;e++)if(!Ts(a[e].attrs,t[e].attrs))return!1;return!0}function Ts(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 zr(a,t){return t.label.toLowerCase()===a.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(a.lang||"").toLowerCase())}class Zc extends Mn{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(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVEL_LOADING,this.onLevelLoading,this),t.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(v.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,f)=>{d.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const h=this.hls.config.audioPreference;if(!n&&h){const d=we(h,o,di);if(d>-1)n=o[d];else{const f=we(h,this.tracks);n=this.tracks[f]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(v.AUDIO_TRACKS_UPDATED,c);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-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(v.ERROR,{type:et.MEDIA_ERROR,details:P.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(t,e){e.fatal||!e.context||e.context.type===pt.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&&fi(t,s,di))return s;const n=we(t,this.tracksInGroup,di);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=uv(t,e.levels,i,r,di);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(v.AUDIO_TRACK_SWITCHING,xt({},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||fi(t,s,di)))return i}if(t){const{name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:h}=t;for(let l=0;l<e.length;l++){const c=e[l];if(fi({name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:h},c,di))return l}for(let l=0;l<e.length;l++){const c=e[l];if(Ts(t.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<e.length;l++){const c=e[l];if(Ts(t.attrs,c.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&En(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(v.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null,track:t})}}class XA{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>":`
30
+ ${this.list("video")}
31
+ ${this.list("audio")}
32
+ ${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 kl=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,tu="HlsJsTrackRemovedError";class jA extends Error{constructor(t){super(t),this.name=tu}}class eu extends Ye{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(v.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=Dy(Ve(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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.BUFFER_RESET,this.onBufferReset,this),t.on(v.BUFFER_APPENDING,this.onBufferAppending,this),t.on(v.BUFFER_CODECS,this.onBufferCodecs,this),t.on(v.BUFFER_EOS,this.onBufferEos,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.FRAG_PARSED,this.onFragParsed,this),t.on(v.FRAG_CHANGED,this.onFragChanged,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.BUFFER_RESET,this.onBufferReset,this),t.off(v.BUFFER_APPENDING,this.onBufferAppending,this),t.off(v.BUFFER_CODECS,this.onBufferCodecs,this),t.off(v.BUFFER_EOS,this.onBufferEos,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.FRAG_PARSED,this.onFragParsed,this),t.off(v.FRAG_CHANGED,this.onFragChanged,this),t.off(v.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?bt(i,s.tracks):this.sourceBuffers.forEach(n=>{const[r]=n;r&&(i[r]=bt({},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=Ve(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 h=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||h&&r instanceof h,Ul(i),WA(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})
33
+ required tracks: ${Bt(i,(h,l)=>h==="initSegment"?void 0:l)};
34
+ transfer tracks: ${Bt(s,(h,l)=>h==="initSegment"?void 0:l)}}`),!Qh(s,i)){e.mediaSource=null,e.tracks=void 0;const h=t.currentTime,l=this.details,c=Math.max(h,(l==null?void 0:l.fragments[0].start)||0);if(c-h>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${h} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${h}`),this.onMediaDetaching(v.MEDIA_DETACHING,{}),this.onMediaAttaching(v.MEDIA_ATTACHING,e),t.currentTime=c;return}this.transferData=void 0,n.forEach(h=>{const l=h,c=s[l];if(c){const u=c.buffer;if(u){const d=this.fragmentTracker,f=c.id;if(d.hasFragments(f)||d.hasParts(f)){const g=ht.getBuffered(u);d.detectEvictedFragments(l,g,f,null,!0)}const m=ur(l),p=[l,u];this.sourceBuffers[m]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,c)}}}),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 h=n.sourceBuffers;for(let l=h.length;l--;)o&&h[l].abort(),n.removeSourceBuffer(h[l]);o&&n.endOfStream()}catch(h){this.warn(`onMediaDetaching: ${h.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&&Ul(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(v.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[ur(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new XA(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 h,l,c;const u=e[o],{id:d,codec:f,levelCodec:m,container:p,metadata:g,supplemental:E}=u;let A=i[o];const y=(h=this.transferData)==null||(l=h.tracks)==null?void 0:l[o],T=y!=null&&y.buffer?y:A,_=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),C=T==null?void 0:T.levelCodec;A||(A=i[o]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:p,levelCodec:m,metadata:g,id:d});const S=sn(_,C),I=S==null?void 0:S.replace(kl,"$1");let L=sn(f,m);const b=(c=L)==null?void 0:c.replace(kl,"$1");L&&S&&I!==b&&(o.slice(0,5)==="audio"&&(L=pn(L,this.appendSource)),this.log(`switching codec ${_} to ${L}`),L!==(A.pendingCodec||A.codec)&&(A.pendingCodec=L),A.container=p,this.appendChangeType(o,p,L))}),(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 h=this.tracks.video;(this.lastVideoAppendEnd>s||h!=null&&h.buffer&&ht.isBuffered(h.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:h,chunkMeta:l}=e,c=l.buffering[n],u=o.sn,d=self.performance.now();c.start=d;const f=o.stats.buffering,m=h?h.stats.buffering:null;f.start===0&&(f.start=d),m&&m.start===0&&(m.start=d);const p=i.audio;let g=!1;n==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(g=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const E=this.tracks.video,A=E==null?void 0:E.buffer;if(A&&u!=="initSegment"){const _=h||o,C=this.blockedAudioAppend;if(n==="audio"&&r!=="main"&&!this.blockedAudioAppend){const I=_.start+_.duration*.05,L=A.buffered,b=this.currentOp("video");!L.length&&!b?this.blockAudio(_):!b&&!ht.isBuffered(A,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(_)}else if(n==="video"){const S=_.end;if(C){const I=C.frag.start;(S>I||S<this.lastVideoAppendEnd||ht.isBuffered(A,I))&&this.unblockAudio()}this.lastVideoAppendEnd=S}}const y=(h||o).start,T={label:`append-${n}`,execute:()=>{if(c.executeStart=self.performance.now(),g){const _=this.tracks[n];if(_){const C=_.buffer;if(C){const S=y-C.timestampOffset;Math.abs(S)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${y} (delta: ${S}) sn: ${u})`),C.timestampOffset=y)}}}this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const _=self.performance.now();c.executeEnd=c.end=_,f.first===0&&(f.first=_),m&&m.first===0&&(m.first=_);const C={};this.sourceBuffers.forEach(([S,I])=>{S&&(C[S]=ht.getBuffered(I))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(v.BUFFER_APPENDED,{type:n,frag:o,part:h,chunkMeta:l,parent:o.type,timeRanges:C})},onError:_=>{var C;const S={type:et.MEDIA_ERROR,parent:o.type,details:P.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:h,chunkMeta:l,error:_,err:_,fatal:!1},I=(C=this.media)==null?void 0:C.error;if(_.code===DOMException.QUOTA_EXCEEDED_ERR)S.details=P.BUFFER_FULL_ERROR;else if(_.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)S.errorAction=Es(!0);else if(_.name===tu&&this.sourceBufferCount===0)S.errorAction=Es(!0);else{const L=++this.appendErrors[n];this.warn(`Failed ${L}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${I||"no media error"})`),(L>=this.hls.config.appendErrorMaxRetry||I)&&(S.fatal=!0)}this.hls.trigger(v.ERROR,S)}};this.append(T,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(v.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[Rt.AUDIOVIDEO]?n.push("audiovideo"):(r[Rt.AUDIO]&&n.push("audio"),r[Rt.VIDEO]&&n.push("video"));const o=()=>{const h=self.performance.now();i.stats.buffering.end=h,s&&(s.stats.buffering.end=h);const l=s?s.stats:i.stats;this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:s,stats:l,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(h=>{this.warn(`Fragment buffered callback ${h}`),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(v.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(v.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===P.BUFFER_APPEND_ERROR&&e.frag){var i;const s=(i=e.errorAction)==null?void 0:i.nextAutoLevel;q(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(q(o)&&o>=0){const h=Math.max(o,r),l=Math.floor(n/r)*r-h;this.flushBackBuffer(n,r,l)}if(q(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const h=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),l=Math.max(h,r),c=Math.floor(n/r)*r+l;this.flushFrontBuffer(n,r,c)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const o=ht.getBuffered(n);if(o.length>0&&i>o.start(0)){var r;this.hls.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:i});const h=this.tracks[s];if((r=this.details)!=null&&r.live)this.hls.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(h!=null&&h.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const r=ht.getBuffered(n),o=r.length;if(o<2)return;const h=r.start(o-1),l=r.end(o-1);if(i>h||t>=h&&t<=l)return;this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:h,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 l=Math.max(0,e.fragmentStart),c=Math.max(l,s);return{duration:1/0,start:l,end:c}}return{duration:1/0}}const n=(t=this.overrides)==null?void 0:t.duration;if(n)return q(n)?{duration:n}:null;const r=this.media.duration,o=q(i.duration)?i.duration:0;return s>o&&s>r||!q(r)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==t&&(q(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}) ${Bt(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(v.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(v.ERROR,{type:et.MEDIA_ERROR,details:P.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 h=this.getTrackCodec(o,r),l=`${o.container};codecs=${h}`;o.codec=h,this.log(`creating sourceBuffer(${l})${this.currentOp(r)?" Queued":""} ${Bt(o)}`);try{const c=i.addSourceBuffer(l),u=ur(r),d=[r,c];e[u]=d,o.buffer=c}catch(c){var s;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(r),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[r],this.hls.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l,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")&&Fr(i,"video")&&(s=Qy(s,i));const n=sn(s,t.levelCodec);return n?e.slice(0,5)==="audio"?pn(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(v.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(v.ERROR,{type:et.MEDIA_ERROR,details:P.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 h=q(s.duration)?s.duration:1/0,l=q(n.duration)?n.duration:1/0,c=Math.max(0,e),u=Math.min(i,h,l);u>c&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=i==null?void 0:i.buffer;if(!s)throw new jA(`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 Ul(a){const t=a.querySelectorAll("source");[].slice.call(t).forEach(e=>{a.removeChild(e)})}function WA(a,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,a.appendChild(e)}function ur(a){return a==="audio"?1:0}class Bn{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(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.BUFFER_CODECS,this.onBufferCodecs,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.BUFFER_CODECS,this.onBufferCodecs,this),t.off(v.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&&q(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,Bn.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,h)=>h?o.width!==h.width||o.height!==h.height:!0;let n=t.length-1;const r=Math.max(e,i);for(let o=0;o<t.length;o+=1){const h=t[o];if((h.width>=r||h.height>=r)&&s(h,t[o+1])){n=o;break}}return n}}const JA={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},te=JA,QA={HLS:"h"},qA=QA,ZA="CMCD-Object",tT="CMCD-Request",eT="CMCD-Session",iT="CMCD-Status",ls={OBJECT:ZA,REQUEST:tT,SESSION:eT,STATUS:iT},sT={[ls.OBJECT]:["br","d","ot","tb"],[ls.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[ls.SESSION]:["cid","pr","sf","sid","st","v"],[ls.STATUS]:["bs","rtp"]};class Hi{constructor(t,e){Array.isArray(t)&&(t=t.map(i=>i instanceof Hi?i:new Hi(i))),this.value=t,this.params=e}}const nT="Dict";function rT(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 aT(a,t,e,i){return new Error(`failed to ${a} "${rT(t)}" as ${e}`,{cause:i})}function Be(a,t,e){return aT("serialize",a,t,e)}class iu{constructor(t){this.description=t}}const Nl="Bare Item",oT="Boolean";function lT(a){if(typeof a!="boolean")throw Be(a,oT);return a?"?1":"?0"}function hT(a){return btoa(String.fromCharCode(...a))}const cT="Byte Sequence";function uT(a){if(ArrayBuffer.isView(a)===!1)throw Be(a,cT);return`:${hT(a)}:`}const dT="Integer";function fT(a){return a<-999999999999999||999999999999999<a}function su(a){if(fT(a))throw Be(a,dT);return a.toString()}function mT(a){return`@${su(a.getTime()/1e3)}`}function nu(a,t){if(a<0)return-nu(-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}const pT="Decimal";function gT(a){const t=nu(a,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Be(a,pT);const e=t.toString();return e.includes(".")?e:`${e}.0`}const ET="String",yT=/[\x00-\x1f\x7f]+/;function vT(a){if(yT.test(a))throw Be(a,ET);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function AT(a){return a.description||a.toString().slice(7,-1)}const TT="Token";function Gl(a){const t=AT(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Be(t,TT);return t}function Yr(a){switch(typeof a){case"number":if(!q(a))throw Be(a,Nl);return Number.isInteger(a)?su(a):gT(a);case"string":return vT(a);case"symbol":return Gl(a);case"boolean":return lT(a);case"object":if(a instanceof Date)return mT(a);if(a instanceof Uint8Array)return uT(a);if(a instanceof iu)return Gl(a);default:throw Be(a,Nl)}}const _T="Key";function Xr(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw Be(a,_T);return a}function Da(a){return a==null?"":Object.entries(a).map(([t,e])=>e===!0?`;${Xr(t)}`:`;${Xr(t)}=${Yr(e)}`).join("")}function ru(a){return a instanceof Hi?`${Yr(a.value)}${Da(a.params)}`:Yr(a)}function ST(a){return`(${a.value.map(ru).join(" ")})${Da(a.params)}`}function xT(a,t={whitespace:!0}){if(typeof a!="object")throw Be(a,nT);const e=a instanceof Map?a.entries():Object.entries(a),i=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([s,n])=>{n instanceof Hi||(n=new Hi(n));let r=Xr(s);return n.value===!0?r+=Da(n.params):(r+="=",Array.isArray(n.value)?r+=ST(n):r+=ru(n)),r}).join(`,${i}`)}function CT(a,t){return xT(a,t)}function bT(a){return a==="ot"||a==="sf"||a==="st"}function IT(a){return typeof a=="number"?q(a):a!=null&&a!==""&&a!==!1}function LT(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("/")}const on=a=>Math.round(a),RT=(a,t)=>(t!=null&&t.baseUrl&&(a=LT(a,t.baseUrl)),encodeURIComponent(a)),js=a=>on(a/100)*100,DT={br:on,d:on,bl:js,dl:js,mtp:js,nor:RT,rtp:js,tb:on};function PT(a,t){const e={};if(a==null||typeof a!="object")return e;const i=Object.keys(a).sort(),s=bt({},DT,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 h=s[r];h&&(o=h(o,t)),!(r==="v"&&o===1)&&(r=="pr"&&o===1||IT(o)&&(bT(r)&&typeof o=="string"&&(o=new iu(o)),e[r]=o))}),e}function au(a,t={}){return a?CT(PT(a,t),bt({whitespace:!1},t)):""}function wT(a,t={}){const e={};if(!a)return e;const i=Object.entries(a),s=Object.entries(sT).concat(Object.entries((t==null?void 0:t.customHeaderMap)||{})),n=i.reduce((r,o)=>{var h,l;const[c,u]=o,d=((h=s.find(f=>f[1].includes(c)))===null||h===void 0?void 0:h[0])||ls.REQUEST;return(l=r[d])!==null&&l!==void 0||(r[d]={}),r[d][c]=u,r},{});return Object.entries(n).reduce((r,[o,h])=>(r[o]=au(h,t),r),e)}function MT(a,t,e){return bt(a,wT(t,e))}const BT="CMCD";function OT(a,t={}){if(!a)return"";const e=au(a,t);return`${BT}=${encodeURIComponent(e)}`}const Hl=/CMCD=[^&#]+/;function FT(a,t,e){const i=OT(t,e);if(!i)return a;if(Hl.test(a))return a.replace(Hl,i);const s=a.includes("?")?"&":"?";return`${a}${s}${i}`}class ou{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:te.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],h=this.getObjectType(n),l={d:(r||n).duration*1e3,ot:h};(h===te.VIDEO||h===te.AUDIO||h==te.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(h)/1e3,l.bl=this.getBufferLength(h));const c=r?this.getNextPart(r):this.getNextFrag(n);c!=null&&c.url&&c.url!==n.url&&(l.nor=c.url),this.apply(s,l)}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(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHED,this.onMediaDetached,this),t.on(v.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHED,this.onMediaDetached,this),t.off(v.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:qA.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){bt(e,this.createData());const i=e.ot===te.INIT||e.ot===te.VIDEO||e.ot===te.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={}),MT(t.headers,e,n)):t.url=FT(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 h=r.length-1;h>=0;h--){const l=r[h];if(l.index===s&&l.fragment.sn===o)return r[h+1]}}}getObjectType(t){const{type:e}=t;if(e==="subtitle")return te.TIMED_TEXT;if(t.sn==="initSegment")return te.INIT;if(e==="audio")return te.AUDIO;if(e==="main")return this.hls.audioTracks.length?te.VIDEO:te.MUXED}getTopBandwidth(t){let e=0,i;const s=this.hls;if(t===te.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,r=n>-1?n+1:s.levels.length;i=s.levels.slice(0,r)}return i.forEach(n=>{n.bitrate>e&&(e=n.bitrate)}),e>0?e:NaN}getBufferLength(t){const e=this.media,i=t===te.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!e?NaN:ht.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 kT=3e5;class lu extends Ye{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(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.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)===Xt.SendAlternateToPenaltyBox&&i.flags===de.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:o,pathwayId:h,type:l}=e.context;o&&s?r=this.getPathwayForGroupId(o,l,r):h&&(r=h)}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: ${Bt(n)} penalized: ${Bt(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]>kT&&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,h=this.hls.levels[o];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Lc(e),this.hls.trigger(v.LEVELS_UPDATED,{levels:e});const l=this.hls.levels[o];h&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==h.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==h.bitrate&&this.log(`Unstable Pathways change from bitrate ${h.bitrate} to ${l.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===pt.AUDIO_TRACK&&s[n].hasAudioGroup(t)||e===pt.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":h}=n;if(e.some(c=>c.pathwayId===r))return;const l=this.getLevelsForPathway(o).map(c=>{const u=new Mt(c.attrs);u["PATHWAY-ID"]=r;const d=u.AUDIO&&`${u.AUDIO}_clone_${r}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${r}`;d&&(i[u.AUDIO]=d,u.AUDIO=d),f&&(s[u.SUBTITLES]=f,u.SUBTITLES=f);const m=hu(c.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",h),p=new Ui({attrs:u,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let g=1;g<c.audioGroups.length;g++)p.addGroupId("audio",`${c.audioGroups[g]}_clone_${r}`);if(c.subtitleGroups)for(let g=1;g<c.subtitleGroups.length;g++)p.addGroupId("text",`${c.subtitleGroups[g]}_clone_${r}`);return p});e.push(...l),$l(this.audioTracks,i,h,r),$l(this.subtitleTracks,s,h,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 c=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}const n={responseType:"json",url:s.href},r=e.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},h={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,u,d,f)=>{this.log(`Loaded steering manifest: "${s}"`);const m=c.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":E}=m;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),g&&this.clonePathways(g);const A={steeringManifest:m,url:s.toString()};this.hls.trigger(v.STEERING_MANIFEST_LOADED,A),E&&this.updatePathwayPriority(E)},onError:(c,u,d,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${u.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,m)},onTimeout:(c,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,h,l)}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 $l(a,t,e,i){a&&Object.keys(t).forEach(s=>{const n=a.filter(r=>r.groupId===s).map(r=>{const o=bt({},r);return o.details=void 0,o.attrs=new Mt(o.attrs),o.url=o.attrs.URI=hu(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 hu(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 h=new self.URL(a);return s&&!o&&(h.host=s),n&&Object.keys(n).sort().forEach(l=>{l&&h.searchParams.set(l,n[l])}),h.href}function re(a,t,e){me(a,t,e),a.addEventListener(t,e)}function me(a,t,e){a.removeEventListener(t,e)}class mi extends Ye{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.mediaKeys=null,this.setMediaKeysQueue=mi.CDMCleanupPromise?[mi.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=os(this.config));const o=r.map(Ks).filter(h=>!!h);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(r=>{const o=nn(r);let h,l;if(i==="sinf"){if(o!==_t.FAIRPLAY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const m=$t(new Uint8Array(s));try{const p=Ta(JSON.parse(m).sinf),g=nc(p);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=new Uint8Array(g.subarray(8,24)),l=_t.FAIRPLAY}catch(p){this.warn(`${n} Failed to parse sinf: ${p}`);return}}else{if(o!==_t.WIDEVINE&&o!==_t.PLAYREADY){this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const m=Xy(s),p=m.filter(E=>!!E.systemId&&sr(E.systemId)===o);p.length>1&&this.warn(`${n} Using first of ${p.length} pssh found for selected key-system ${o}`);const g=p[0];if(!g){m.length===0||m.some(E=>!E.systemId)?this.warn(`${n} contains incomplete or invalid pssh data`):this.log(`ignoring ${n} for ${m.map(E=>sr(E.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(l=sr(g.systemId),g.version===0&&g.data)if(l===_t.WIDEVINE){const E=g.data.length-22;h=new Uint8Array(g.data.subarray(E,E+16))}else l===_t.PLAYREADY&&(h=Tc(g.data))}if(!l||!h)return;const c=Re.hexDump(h),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let f=u[c];for(let m=0;m<d.length;m++){const p=d[m],g=p.decryptdata;if(!g.keyId)continue;const E=Re.hexDump(g.keyId);if(c===E||g.uri.replace(/-/g,"").indexOf(c)!==-1){if(f=u[E],g.pssh)break;delete u[E],g.pssh=new Uint8Array(s),g.keyId=h,f=u[c]=f.then(()=>this.generateRequestWithPreferredKeySession(p,i,s,"encrypted-event-key-match")),f.catch(A=>this.handleError(A));break}}if(!f){if(l!==o){this.log(`Ignoring "${e.type}" event with ${l} init data for selected key-system ${o}`);return}f=u[c]=this.getKeySystemSelectionPromise([l]).then(({keySystem:m,mediaKeys:p})=>{var g;this.throwIfDestroyed();const E=new Ni("ISO-23001-7",c,(g=Ks(m))!=null?g:"");return E.pssh=new Uint8Array(s),E.keyId=h,this.attemptSetMediaKeys(m,p).then(()=>{this.throwIfDestroyed();const A=this.createMediaKeySessionContext({decryptdata:E,keySystem:m,mediaKeys:p});return this.generateRequestWithPreferredKeySession(A,i,s,"encrypted-event-no-match")})}),f.catch(m=>this.handleError(m))}})}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(v.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(v.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=e[t];if(s)return s.licenseUrl;if(t===_t.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,h)=>!!r&&h.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 h=l=>{const c=l.shift();this.getMediaKeysPromise(c,s,n).then(u=>r({keySystem:c,mediaKeys:u})).catch(u=>{l.length?h(l):u instanceof ue?o(u):o(new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};h(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return _a===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=Bv(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: ${Bt(s)}`),r=this.requestMediaKeySystemAccess(t,s);const o=this.keySystemAccessPromises[t]={keySystemAccess:r};return r.catch(h=>{this.log(`Failed to obtain access to key-system "${t}": ${h}`)}),r.then(h=>{this.log(`Access for key-system "${h.keySystem}" obtained`);const l=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),o.mediaKeys=h.createMediaKeys().then(c=>(this.log(`Media-keys created for "${t}"`),o.hasMediaKeys=!0,l.then(u=>u?this.setMediaKeysServerCertificate(c,t,u):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${t}"}: ${c}`)}),o.mediaKeys})}return r.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Re.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 Re.hexDump(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Re.hexDump(((i=t.decryptdata)==null?void 0:i.keyId)||[])}
35
+ } (data length: ${e&&e.byteLength})`),s.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ks(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:e,mediaKeys:i})=>this.attemptSetMediaKeys(e,i))}selectKeySystem(t){return new Promise((e,i)=>this.getKeySystemSelectionPromise(t).then(({keySystem:s})=>{const n=Ks(s);n?e(n):i(new Error(`Unable to find format for key-system "${s}"`))}).catch(i))}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){const e=os(this.config),i=t.map(nn).filter(s=>!!s&&e.indexOf(s)!==-1);return this.selectKeySystem(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:h})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,h).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:h,decryptdata:e}))))),(this.keyIdToKeySessionPromise[i]=n.then(o=>{const h="cenc",l=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,h,l,"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(v.ERROR,t.data):this.hls.trigger(v.ERROR,{type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const s=nn(t.keyFormat),n=s?[s]:os(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=os(this.config)),t.length===0)throw new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Bt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.mediaKeys=e,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 m=o.call(this.hls,e,i,t);if(!m)throw new Error("Invalid response from configured generateRequest filter");e=m.initDataType,i=m.initData?m.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(m){var h;if(this.warn(m.message),(h=this.hls)!=null&&h.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${l} (init data type: ${e} length: ${i?i.byteLength:null})`);const c=new Sa,u=t._onmessage=m=>{const p=t.mediaKeysSession;if(!p){c.emit("error",new Error("invalid state"));return}const{messageType:g,message:E}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(t,E).catch(A=>{c.eventNames().length?c.emit("error",A):this.handleError(A)}):g==="license-release"?t.keySystem===_t.FAIRPLAY&&(this.updateKeySession(t,Gr("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${g}"`)},d=t._onkeystatuseschange=m=>{if(!t.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const g=t.keyStatus;c.emit("keyStatus",g),g==="expired"&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};re(t.mediaKeysSession,"message",u),re(t.mediaKeysSession,"keystatuseschange",d);const f=new Promise((m,p)=>{c.on("error",p),c.on("keyStatus",g=>{g.startsWith("usable")?m():g==="output-restricted"?p(new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?p(new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?p(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return t.mediaKeysSession.generateRequest(e,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=t.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${l}`)}).catch(m=>{throw new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw c.removeAllListeners(),this.removeSession(t),m}).then(()=>(c.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: ${Re.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Re.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 h={responseType:"arraybuffer",url:n},l=e.certLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,m,p)=>{r(d.data)},onError:(d,f,m,p)=>{o(new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:xt({url:h.url,data:void 0},d)},`"${t}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,m)=>{o(new ue({type:et.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:h.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(d,f,m)=>{o(new Error("aborted"))}};s.load(h,c,u)})):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:P.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:P.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 c;for(let u=0,d=n.length;u<d;u++){var r,o;c=n[u];const f=(r=c.querySelector("name"))==null?void 0:r.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&t.setRequestHeader(f,m)}}const h=s.querySelector("Challenge"),l=h==null?void 0:h.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Gr(atob(l))}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 h=o.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const l=this.config.licenseResponseCallback;if(l)try{h=l.call(this.hls,o,r,t)}catch(c){this.error(c)}s(h)}else{const h=i.errorRetry,l=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new ue({type:et.KEY_SYSTEM_ERROR,details:P.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 c=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} 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:h,licenseChallenge:l})=>{t.keySystem==_t.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(h,l)),h.send(l)})})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,re(i,"encrypted",this.onMediaEncrypted),re(i,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(me(t,"encrypted",this.onMediaEncrypted),me(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const e=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ni.clearKeyUriToKeyIdMap();const s=i.length;mi.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(n=>{var r;this.log(`Could not clear media keys: ${n}`),(r=this.hls)==null||r.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))).catch(n=>{var r;this.log(`Could not close sessions and clear media keys: ${n}`),(r=this.hls)==null||r.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).then(()=>{s&&this.log("finished closing key sessions and clearing media keys")})}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(Fv(n)?new Promise((o,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(o)}):Promise.resolve()).catch(o=>{var h;this.log(`Could not remove session: ${o}`),(h=this.hls)==null||h.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>e.close()).catch(o=>{var h;this.log(`Could not close session: ${o}`),(h=this.hls)==null||h.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}}}mi.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 cu{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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(v.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,h=1e3*r/n,l=this.hls;if(l.trigger(v.FPS_DROP,{currentDropped:r,currentDecoded:o,totalDroppedFrames:i}),h>0&&r>l.config.fpsDroppedMonitoringThreshold*o){let c=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=c)&&(c=c-1,l.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:l.currentLevel}),l.autoLevelCapping=c,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 uu(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 du(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){Tt.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){Tt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}e==="disabled"&&(a.mode=e)}function Mi(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 jr(a,t,e,i){const s=a.mode;if(s==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const n=NT(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 UT(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 NT(a,t,e){const i=[],s=UT(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 ln(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 fu extends Mn{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=ln(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(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVEL_LOADING,this.onLevelLoading,this),t.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(v.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;ln(i.textTracks).forEach(r=>{Mi(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(c=>!i||i.indexOf(c.groupId)!==-1);if(r.length)this.selectDefaultTrack&&!r.some(c=>c.default)&&(this.selectDefaultTrack=!1),r.forEach((c,u)=>{c.id=u});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=r;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const c=we(o,r);if(c>-1)n=r[c];else{const u=we(o,this.tracks);n=this.tracks[u]}}let h=this.findTrackId(n);h===-1&&n&&(h=this.findTrackId(null));const l={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(v.SUBTITLE_TRACKS_UPDATED,l),h!==-1&&this.trackId===-1&&this.setSubtitleTrack(h)}}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||fi(n,t)))return s}if(t){for(let s=0;s<e.length;s++){const n=e[s];if(Ts(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const n=e[s];if(Ts(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(zr(s,t))return i}}return-1}onError(t,e){e.fatal||!e.context||e.context.type===pt.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&&fi(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(v.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=ln(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(n=>zr(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||!q(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(v.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:h,type:l,url:c}=s;this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:r,groupId:o,name:h,type:l,url:c});const u=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(u)}}function GT(){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 ps(a){let t=5381,e=a.length;for(;e;)t=t*33^a.charCodeAt(--e);return(t>>>0).toString()}const Fi=.025;let Sn=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function HT(a,t,e){return`${a.identifier}-${e+1}-${ps(t)}`}class $T{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){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;return t<=0||isNaN(i)?!1:i===0?!0:(((e=this.assetList[t])==null?void 0:e.startOffset)||0)>i}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 dr(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=dr(e,t);return e-i<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=q(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 dr(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)<Fi))}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"?Sn.Range:Sn.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 KT(this)}}function dr(a,t){return a-t.start<t.duration/2&&!(Math.abs(a-(t.start+t.duration))<Fi)?t.start:t.start+t.duration}function mu(a,t,e){const i=new self.URL(a,e);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",t),i}function fr(a,t){for(;(e=a.assetList[++t])!=null&&e.error;)var e;return t}function KT(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function Pi(a){const t=a.timelineStart,e=a.duration||0;return`["${a.identifier}" ${t.toFixed(2)}-${(t+e).toFixed(2)}]`}class VT{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=()=>{this.reachedPlayout(this.currentTime)&&this.hls.trigger(v.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new t(e);this.interstitial=i,this.assetItem=s;let r=s.uri;try{r=mu(r,e.primarySessionId).href}catch{}n.loadSource(r);const o=()=>{this.hasDetails=!0};n.once(v.LEVEL_LOADED,o),n.once(v.AUDIO_TRACK_LOADED,o),n.once(v.SUBTITLE_TRACK_LOADED,o),n.on(v.MEDIA_ATTACHING,(h,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(v.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(v.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){var t;return((t=this.interstitial)==null?void 0:t.appendInPlace)||!1}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if((e=this.hls)!=null&&e.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const i=this.timelineOffset,s=ht.bufferInfo(t,i,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}reachedPlayout(t){const i=this.interstitial.playoutLimit;return this.startOffset+t>=i}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=ht.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()}resetDetails(){const t=this.hls;if(this.hasDetails){t.stopLoad();const e=i=>delete i.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}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;return`HlsAssetPlayer: ${Pi(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Kl=.033;class zT extends Ye{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),h=n?n.filter(l=>!o.includes(l.identifier)):[];r.length&&r.sort((l,c)=>{const u=l.cue.pre,d=l.cue.post,f=c.cue.pre,m=c.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!m)return 1;if(m&&!d)return-1;if(!u&&!f&&!d&&!m){const p=l.startTime,g=c.startTime;if(p!==g)return p-g}return l.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=r,h.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(t,h)}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,h)=>Math.abs(o.playout.start-s[h].playout.start)>.005||Math.abs(o.playout.end-s[h].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],h=t[o];if(h.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(h):(l=new $T(h,e),this.eventMap[o]=l,i===!1&&(l.appendInPlace=i)),s.push(l)}}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(h=>!h.error&&!(h.cue.once&&h.hasPlayed)),t.length){this.resolveOffsets(t,e);let h=0,l=0;if(t.forEach((c,u)=>{const d=c.cue.pre,f=c.cue.post,m=t[u-1]||null,p=c.appendInPlace,g=f?n:c.startOffset,E=c.duration,A=c.timelineOccupancy===Sn.Range?E:0,y=c.resumptionOffset,T=(m==null?void 0:m.startTime)===g,_=g+c.cumulativeDuration;let C=p?_+E:g+y;if(d||!f&&g<=0){const I=l;l+=A,c.timelineStart=_;const L=r;r+=E,i.push({event:c,start:_,end:C,playout:{start:L,end:r},integrated:{start:I,end:l}})}else if(g<=n){if(!T){const b=g-h;if(b>Kl){const w=h,O=l;l+=b;const H=r;r+=b;const Y={previousEvent:t[u-1]||null,nextEvent:c,start:w,end:w+b,playout:{start:H,end:r},integrated:{start:O,end:l}};i.push(Y)}else b>0&&m&&(m.cumulativeDuration+=b,i[i.length-1].end=g)}f&&(C=_),c.timelineStart=_;const I=l;l+=A;const L=r;r+=E,i.push({event:c,start:_,end:C,playout:{start:L,end:r},integrated:{start:I,end:l}})}else return;const S=c.resumeTime;f||S>n?h=n:h=S}),h<n){var o;const c=h,u=l,d=n-h;l+=d;const f=r;r+=d,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:h,end:c+d,playout:{start:f,end:r},integrated:{start:u,end:l}})}this.setDurations(n,r,l)}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,h)=>{const l=o.cue.pre,c=o.cue.post,u=l?0:c?s:o.startTime;this.updateAssetDurations(o),r===u?o.cumulativeDuration=n:(n=0,r=u),!c&&o.snapOptions.in&&(o.resumeAnchor=pi(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)),!o.appendInPlace&&h+1<t.length&&t[h+1].startTime-t[h].resumeTime<Kl&&(t[h+1].appendInPlace=!1,t[h+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;return Math.abs(i-s)>Fi?(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,h=o.edge;if(i>=h)return this.log(`"${t.identifier}" resumption ${i} past ${r} playlist end ${h}`),!1;const l=pi(null,o.fragments,i);if(!l)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const c=r==="audio"?.175:0;return Math.abs(l.start-i)<Fi+c||Math.abs(l.end-i)<Fi+c?!1:(this.log(`"${t.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.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 h=e+i;r.startOffset=i,r.timelineStart=h,s||(s=r.duration===null),n||(n=!!r.error);const l=r.error?0:r.duration||0;i+=l}),s&&!n?t.duration=Math.max(i,t.duration):t.duration=i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function We(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class YT{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=mu(i,this.hls.sessionId,t.baseUrl)}catch(d){const f=this.assignAssetListError(t,P.ASSET_LIST_LOAD_ERROR,d,i);this.hls.trigger(v.ERROR,f);return}e&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+e);const n=this.hls.config,r=n.loader,o=new r(n),h={responseType:"json",url:s.href},l=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,m,p)=>{const g=d.data,E=g==null?void 0:g.ASSETS;if(!Array.isArray(E)){const A=this.assignAssetListError(t,P.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(v.ERROR,A);return}t.assetListResponse=g,this.hls.trigger(v.ASSET_LIST_LOADED,{event:t,assetListResponse:g,networkDetails:p})},onError:(d,f,m,p)=>{const g=this.assignAssetListError(t,P.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,p,m);this.hls.trigger(v.ERROR,g)},onTimeout:(d,f,m)=>{const p=this.assignAssetListError(t,P.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,m);this.hls.trigger(v.ERROR,p)}};return o.load(h,c,u),this.hls.trigger(v.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 Vl(a){a==null||a.play().catch(()=>{})}class XT extends Ye{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 h;const d=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(o)&&(h=this.media)!=null&&h.paused&&(this.shouldPlay=!1),!r){const f=this.findItemIndex(o);if(d>f){const m=this.schedule.findJumpRestrictedIndex(f+1,d);if(m>f){this.setSchedulePosition(m);return}}}this.setSchedulePosition(d);return}const l=this.playingAsset;if(!l){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 c=l.timelineStart,u=l.duration||0;(r&&i<c||i>=c+u)&&this.setScheduleToAssetAtTime(i,l)},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||[],h=n.items||[],l=n.durations,c=i.map(m=>m.identifier),u=!!(o.length||c.length);(u||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
36
+ Schedule: ${h.map(m=>We(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const p=m.assetItem.timelineStart,g=m.timelineOffset-p;if(g)try{m.timelineOffset=p}catch(E){Math.abs(g)>Fi&&this.warn(`${E} ("${m.assetId}" ${m.timelineOffset}->${p})`)}}});let d=null;if(r){const m=this.updateItem(r,this.timelinePos);this.itemsMatch(r,m)&&(this.playingItem=m,this.waitingItem=this.endedItem=null,d=()=>this.trimInPlace(m,r))}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f){const m=this.updateItem(f,this.bufferedPos);this.itemsMatch(f,m)?(this.bufferingItem=m,d||(d=()=>this.trimInPlace(m,f))):f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))}if(i.forEach(m=>{m.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),u||s){if(this.hls.trigger(v.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:h.slice(0),durations:l,removedIds:c}),this.isInterstitial(r)&&c.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}d&&d(),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new YT(t),this.schedule=new zT(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(v.BUFFER_APPENDED,this.onBufferAppended,this),t.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(v.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(v.MEDIA_ENDED,this.onMediaEnded,this),t.on(v.ERROR,this.onError,this),t.on(v.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(v.BUFFER_CODECS,this.onBufferCodecs,this),t.off(v.BUFFER_APPENDED,this.onBufferAppended,this),t.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(v.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(v.MEDIA_ENDED,this.onMediaEnded,this),t.off(v.ERROR,this.onError,this),t.off(v.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){me(t,"play",this.onPlay),me(t,"pause",this.onPause),me(t,"seeking",this.onSeeking),me(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;re(i,"seeking",this.onSeeking),re(i,"timeupdate",this.onTimeupdate),re(i,"play",this.onPlay),re(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=u=>u&&t.getAssetPlayer(u.identifier),s=(u,d,f,m,p)=>{if(u){let g=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Sn.Point){const A=i(f);(A==null?void 0:A.interstitial)===E&&(g+=A.assetItem.startOffset+A[p])}}else{const A=m==="bufferedPos"?r():t[m];g+=A-u.start}return g}return 0},n=(u,d)=>{if(u!==0&&d!=="primary"&&t.schedule.length){var f;const m=t.schedule.findItemIndexAtTime(u),p=(f=t.schedule.items)==null?void 0:f[m];if(p){const g=p[d].start-p.start;return u+g}}return u},r=()=>{const u=t.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d;return(d=t.primaryDetails)!=null&&d.live?t.primaryDetails.edge:t.schedule.durations[u]},h=(u,d)=>{var f,m;const p=t.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip)return;t.log(`seek to ${u} "${d}"`);const g=t.effectivePlayingItem,E=t.schedule.findItemIndexAtTime(u,d),A=(m=t.schedule.items)==null?void 0:m[E],y=t.getBufferingPlayer(),T=y==null?void 0:y.interstitial,_=T==null?void 0:T.appendInPlace,C=g&&t.itemsMatch(g,A);if(g&&(_||C)){const I=i(t.playingAsset),L=(I==null?void 0:I.media)||t.primaryMedia;if(L){const b=d==="primary"?L.currentTime:s(g,d,t.playingAsset,"timelinePos","currentTime"),w=u-b,O=(_?b:L.currentTime)+w;if(O>=0&&(!I||_||O<=I.duration)){L.currentTime=O;return}}}if(A){let I=u;if(d!=="primary"){const b=A[d].start,w=u-b;I=A.start+w}const L=!t.isInterstitial(A);if((!t.isInterstitial(g)||g.event.appendInPlace)&&(L||A.event.appendInPlace)){const b=t.media||(_?y==null?void 0:y.media:null);b&&(b.currentTime=I)}else if(g){const b=t.findItemIndex(g);if(E>b){const O=t.schedule.findJumpRestrictedIndex(b+1,E);if(O>b){t.setSchedulePosition(O);return}}let w=0;if(L)t.timelinePos=I,t.checkBuffer();else{var S;const O=A==null||(S=A.event)==null?void 0:S.assetList;if(O){const H=u-(A[d]||A).start;for(let Y=O.length;Y--;){const $=O[Y];if($.duration&&H>=$.startOffset&&H<$.startOffset+$.duration){w=Y;break}}}}t.setSchedulePosition(E,w)}}},l=()=>{const u=t.effectivePlayingItem;if(t.isInterstitial(u))return u;const d=e();return t.isInterstitial(d)?d:null},c={get currentTime(){const u=l(),d=t.effectivePlayingItem;return d&&d===u?s(d,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),f=t.effectivePlayingItem;f&&f===d&&h(u+f.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(f=>t.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&t.effectivePlayingAsset?d.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var u,d;return((u=t.schedule)==null||(d=u.events)==null?void 0:d.slice(0))||[]},get schedule(){var u,d;return((u=t.schedule)==null||(d=u.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?c:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const u=e();return t.findItemIndex(u)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const u=t.effectivePlayingItem;return t.findItemIndex(u)},primary:{get bufferedEnd(){return r()},get currentTime(){const u=t.timelinePos;return u>0?u:0},set currentTime(u){h(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=t.primaryDetails)==null?void 0:u.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(u){h(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return n(((u=t.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=t.effectivePlayingItem,d=u==null?void 0:u.event;if(d&&!d.restrictions.skip){const f=t.findItemIndex(u);if(d.appendInPlace){const m=u.playout.start+u.event.duration;h(m+.001,"playout")}else t.advanceAfterAssetEnded(d,f,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||!q(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} ${Bt(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,h=o&&t.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource;let c;if(r.media)h&&(n=r.transferMedia(),this.detachedData=n),c="Primary";else if(l){const f=this.getBufferingPlayer();f?(n=f.transferMedia(),c=`${f}`):c="detached MediaSource"}else c="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${Bt(n)}`);else if(!this.detachedData||r.media===e){const f=this.playerQueue;f.length>1&&f.forEach(m=>{if(o&&m.interstitial.appendInPlace!==h){const p=m.interstitial;this.clearInterstitial(m.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}}const u=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed",d=u&&n?n:e;if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${c}`),d===n){const f=o&&t.assetId===this.schedule.assetIdAtEnd;d.overrides={duration:this.schedule.duration,endOfStream:!o||f,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=fr(t,i);if(!t.isAssetPastPlayoutLimit(s))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 h=t.resumeTime;this.timelinePos<h&&(this.timelinePos=h,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.advanceAfterAssetEnded(n,r,o-1)}}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 l=n.event,c=this.playingAsset,u=c==null?void 0:c.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(n,s)||e!==void 0&&u!==((o=l.assetList)==null?void 0:o[e].identifier))){var h;const f=l.findAssetIndex(c);this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${l.assetList.length} ${Pi(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(v.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:f,event:l,schedule:i.slice(0),scheduleIndex:t,player:d}),this.retreiveMediaSource(u,s),d.media&&!((h=this.detachedData)!=null&&h.mediaSource)&&d.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${We(n)}`),l.hasPlayed=!0,this.hls.trigger(v.INTERSTITIAL_ENDED,{event:l,schedule:i.slice(0),scheduleIndex:t}),l.cue.once)){this.updateSchedule();const f=this.schedule.items;if(s&&f){const m=this.schedule.findItemIndex(s);this.advanceSchedule(m,f,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,h=this.playerQueue;if(h.length&&h.forEach(l=>{const c=l.interstitial,u=this.schedule.findEventIndex(c.identifier);(u<t||u>t+1)&&this.clearInterstitial(c,r)}),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const l=r.event;if(i===void 0){i=this.schedule.findAssetIndex(l,this.timelinePos);const f=fr(l,i-1);if(l.isAssetPastPlayoutLimit(f)){this.advanceAfterAssetEnded(l,t,i);return}i=f}const c=this.waitingItem;this.assetsBuffered(r,o)||this.setBufferingItem(r);let u=this.preloadAssets(l,i);if(this.eventItemsMatch(r,c||s)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${We(r)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(v.INTERSTITIAL_STARTED,{event:l,schedule:e.slice(0),scheduleIndex:t})),!l.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${l}`);return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${l}`);return}this.waitingItem=this.endedItem=null,this.playingItem=r;const d=l.assetList[i];if(!d){const f=e[t+1],m=this.media;f&&m&&!this.isInterstitial(f)&&m.currentTime<f.start&&(m.currentTime=this.timelinePos=f.start),this.advanceAfterAssetEnded(l,t,i||0);return}if(u||(u=this.getAssetPlayer(d.identifier)),u===null||u.destroyed){const f=l.assetList.length;this.warn(`asset ${i+1}/${f} player destroyed ${l}`),u=this.createAssetPlayer(l,d,i)}if(!this.eventItemsMatch(r,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(u,i,e,t,o),this.shouldPlay&&Vl(u.media)}else r!==null?(this.resumePrimary(r,t,s),this.shouldPlay&&Vl(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 ${We(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(`INTERSTITIALS_PRIMARY_RESUMED ${We(t)}`),this.hls.trigger(v.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:ht.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(v.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(v.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(e.level===-1)return;const i=this.hls.levels[e.level],s=xt(xt({},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=xt(xt({},this.altSelection),{},{audio:i});return}const n=xt(xt({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s){this.altSelection=xt(xt({},this.altSelection),{},{subtitles:i});return}const n=xt(xt({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(t,e){const i=il(e);this.playerQueue.forEach(s=>s.hls.setAudioOption(e)||s.hls.setAudioOption(i))}onSubtitleTrackSwitch(t,e){const i=il(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}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((n,r)=>{t.event.isAssetPastPlayoutLimit(r)&&this.clearAssetPlayer(n.identifier,null)});const i=t.end+.25,s=ht.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.attachPrimary(i,null),this.flushFrontBuffer(i))}}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=ht.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 h=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l,c;const u=this.findItemIndex(n),d=Math.min(u+1,e.length-1),f=e[d];if((h===-1&&n&&t>=n.end||(l=f.event)!=null&&l.appendInPlace&&t+.01>=f.start)&&(h=d),d-o>1&&(n==null||(c=n.event)==null?void 0:c.appendInPlace)===!1)return;if(this.bufferedPos=t,h>u&&h>o)this.bufferedToItem(f);else{const m=this.primaryDetails;this.primaryLive&&m&&t>m.edge-m.targetduration&&f.start<m.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(f)&&this.preloadAssets(f.event,0)}}else i&&r&&!this.itemsMatch(r,n)&&(h===o?this.bufferedToItem(r):h===o+1&&this.bufferedToItem(e[h]))}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();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const h=o?o.remaining:e?e.end-this.timelinePos:0;this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${We(t)}`+(e?` (${h.toFixed(2)} remaining)`:"")),this.playbackDisabled||(r?t.event.assetList.forEach(l=>{const c=this.getAssetPlayer(l.identifier);c&&c.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering()))),this.hls.trigger(v.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],h=this.primaryMedia;o&&h&&this.bufferAssetPlayer(r,h)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,n=s===0&&!t.assetListLoader,r=t.cue.once;if(n){const h=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(h+.25)}let l,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(t.cue.pre||t.cue.post)){const d=c-h;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${l?` live-start: ${c} start-offset: ${l}`:""}`),i)return this.createAsset(t,0,0,h,t.duration,i);const u=this.assetListLoader.loadAssetList(t,l);u&&(t.assetListLoader=u)}else if(!r&&s){for(let h=e;h<s;h++){const l=t.assetList[h],c=this.getAssetPlayerQueueIndex(l.identifier);(c===-1||this.playerQueue[c].destroyed)&&!l.error&&this.createAssetPlayer(t,l,h)}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(v.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:HT(t,r,e),duration:n,startOffset:i,timelineStart:s,uri:r};return this.createAssetPlayer(t,o,e)}createAssetPlayer(t,e,i){const s=this.hls,n=s.userConfig;let r=n.videoPreference;const o=s.loadLevelObj||s.levels[s.currentLevel];(r||o)&&(r=bt({},r),o.videoCodec&&(r.videoCodec=o.videoCodec),o.videoRange&&(r.allowedVideoRanges=[o.videoRange]));const h=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let c=0;if(this.primaryLive||t.appendInPlace){const y=this.timelinePos-e.timelineStart;if(y>1){const T=e.duration;T&&y<T&&(c=y)}}const u=e.identifier,d=xt(xt({},n),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:r,audioPreference:h||n.audioPreference,subtitlePreference:l||n.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(d.timelineOffset=e.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=bt({},f,{contentId:ps(e.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const m=new VT(this.HlsPlayerClass,d,t,e);this.playerQueue.push(m),t.assetList[i]=e;const p=y=>{if(y.live){const C=new Error(`Interstitials MUST be VOD assets ${t}`),S={fatal:!0,type:et.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:C};this.handleAssetItemError(S,t,this.schedule.findEventIndex(t.identifier),i,C.message);return}const T=y.edge-y.fragmentStart,_=e.duration;(_===null||T>_)&&(this.log(`Interstitial asset "${u}" duration change ${_} > ${T}`),e.duration=T,this.updateSchedule())};m.on(v.LEVEL_UPDATED,(y,{details:T})=>p(T)),m.on(v.LEVEL_PTS_UPDATED,(y,{details:T})=>p(T));const g=(y,T)=>{const _=this.getAssetPlayer(u);if(_&&T.tracks){_.off(v.BUFFER_CODECS,g),_.tracks=T.tracks;const C=this.primaryMedia;this.bufferingAsset===_.assetItem&&C&&!_.media&&this.bufferAssetPlayer(_,C)}};m.on(v.BUFFER_CODECS,g);const E=()=>{var y;const T=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${T}`),!T)return;const _=this.schedule.findEventIndex(t.identifier),C=(y=this.schedule.items)==null?void 0:y[_];if(this.isInterstitial(C)){const I=t.findAssetIndex(e),L=fr(t,I);if(!t.isAssetPastPlayoutLimit(L))this.bufferedToItem(C,L);else{var S;const b=(S=this.schedule.items)==null?void 0:S[_+1];b&&this.bufferedToItem(b)}}};m.on(v.BUFFERED_TO_END,E);const A=y=>()=>{if(!this.getAssetPlayer(u))return;this.shouldPlay=!0;const _=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,_,y)};return m.once(v.MEDIA_ENDED,A(i)),m.once(v.PLAYOUT_LIMIT_REACHED,A(1/0)),m.on(v.ERROR,(y,T)=>{const _=this.getAssetPlayer(u);if(T.details===P.BUFFER_STALLED_ERROR){if(_!=null&&_.media){const C=_.currentTime,S=_.duration-C;C&&t.appendInPlace&&S/_.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${u} ${t} at ${_.media.currentTime}`),E()):(this.warn(`Stalled at ${C} of ${C+S} in asset ${u} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${T.error} ${t}`)}),m.on(v.DESTROYING,()=>{if(!this.getAssetPlayer(u))return;const T=new Error(`Asset player destroyed unexpectedly ${u}`),_={fatal:!0,type:et.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(_,t,this.schedule.findEventIndex(t.identifier),i,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Pi(e)}`),this.hls.trigger(v.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:m}),m}clearInterstitial(t,e){t.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,e)}),t.reset()}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(e!==-1){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(i!==-1){this.log(`clear asset player "${t}" toSegment: ${e&&We(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:h}=t,l=r.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!c||c.identifier!==h)&&(c&&(this.clearAssetPlayer(c.identifier,i[s]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${Pi(o)}`),this.hls.trigger(v.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}=t,o=this.schedule.findEventIndex(n.identifier),h=(i=this.schedule.items)==null?void 0:i[o];if(!h)return;this.setBufferingItem(h),this.bufferingAsset=r;const l=this.getBufferingPlayer();if(l===t)return;const c=n.appendInPlace;if(c&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const u=(l==null?void 0:l.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(c&&r!==this.playingAsset){if(!t.tracks)return;if(u&&!Qh(u,t.tracks)){const d=new Error(`Asset ${Pi(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:et.OTHER_ERROR,details:P.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},m=n.findAssetIndex(r);this.handleAssetItemError(f,n,o,m,d.message);return}}this.transferMediaTo(t,e)}handleAssetItemError(t,e,i,s,n){if(t.details===P.BUFFER_STALLED_ERROR)return;const r=e.assetList[s];this.warn(`INTERSTITIAL_ASSET_ERROR ${r&&Pi(r)} ${t.error}`);const o=r==null?void 0:r.identifier,h=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[h]||null,c=this.schedule.items,u=bt({},t,{fatal:!1,errorAction:Es(!0),asset:r,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:l});if(this.hls.trigger(v.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const d=this.playingAsset,f=new Error(n);if(r&&(this.clearAssetPlayer(o,null),r.error=f),!e.assetList.some(m=>!m.error))e.error=f;else if(e.appendInPlace){for(let m=s;m<e.assetList.length;m++)this.resetAssetPlayer(e.assetList[m].identifier);this.updateSchedule()}e.error?this.primaryFallback(e):d&&d.identifier===o&&this.advanceAfterAssetEnded(e,i,s)}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?We(i):"<none>"} error: ${t.error}`);let s=this.timelinePos;s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);this.itemsMatch(i,n)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e));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,h=s.duration;let l=0;r.forEach((m,p)=>{const g=parseFloat(m.DURATION);this.createAsset(s,p,l,o+l,g,m.URI),l+=g}),s.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${h}) ${s}`);const c=this.waitingItem,u=(c==null?void 0:c.event.identifier)===n;this.updateSchedule();const d=(i=this.bufferingItem)==null?void 0:i.event;if(u){var f;const m=this.schedule.findEventIndex(n),p=(f=this.schedule.items)==null?void 0:f[m];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),this.primaryFallback(s);return}this.setBufferingItem(p)}this.setSchedulePosition(m)}else if((d==null?void 0:d.identifier)===n&&d.appendInPlace){const m=s.assetList[0],p=this.getAssetPlayer(m.identifier),g=this.primaryMedia;m&&p&&g&&this.bufferAssetPlayer(p,g)}}onError(t,e){switch(e.details){case P.ASSET_LIST_PARSING_ERROR:case P.ASSET_LIST_LOAD_ERROR:case P.ASSET_LIST_LOAD_TIMEOUT:{const i=e.interstitial;i&&this.primaryFallback(i);break}case P.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const zl=500;class pu extends Pn{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(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=N.IDLE,this.setInterval(zl),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(jt(i)&&(this.fragPrevious=i),this.state=N.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let r;const o=i.start;for(let l=0;l<n.length;l++)if(o>=n[l].start&&o<=n[l].end){r=n[l];break}const h=i.start+i.duration;r?r.end=h:(r={start:o,end:h},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===P.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==N.STOPPED&&(this.state=N.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(this.levels&&qc(this.levels,e)){this.levels=e.map(i=>new Ui(i));return}this.tracksBuffered=[],this.levels=e.map(i=>{const s=new Ui(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!==N.STOPPED&&this.setInterval(zl)}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 h=n[o];if(o>=n.length||!h)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 l=0;if(r.live||(i=h.details)!=null&&i.live){const u=this.mainDetails;if(r.deltaUpdateFailed||!u)return;const d=u.fragments[0];if(!h.details)r.hasProgramDateTime&&u.hasProgramDateTime?(Tn(r,u),l=r.fragmentStart):d&&(l=d.start,$r(r,l));else{var c;l=this.alignPlaylists(r,h.details,(c=this.levelLastLoaded)==null?void 0:c.details),l===0&&d&&(l=d.start,$r(r,l))}}h.details=r,this.levelLastLoaded=h,o===s&&(this.hls.trigger(v.SUBTITLE_TRACK_UPDATED,{details:r,id:o,groupId:e.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===N.IDLE&&(pi(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),h.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&&Oi(s.method)){const r=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Aa(s.method)).catch(o=>{throw n.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:e}),o}).then(o=>{const h=performance.now();n.trigger(v.FRAG_DECRYPTED,{frag:e,payload:o,stats:{tstart:r,tdecrypt:h}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=N.IDLE})}}doTick(){if(!this.media){this.state=N.IDLE;return}if(this.state===N.IDLE){const{currentTrackId:t,levels:e}=this,i=e==null?void 0:e[t];if(!i||!e.length||!i.details||this.waitForLive(i))return;const{config:s}=this,n=this.getLoadPosition(),r=ht.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:h}=r,l=i.details,c=this.hls.maxBufferLength+l.levelTargetDuration;if(h>c)return;const u=l.fragments,d=u.length,f=l.edge;let m=null;const p=this.fragPrevious;if(o<f){const A=s.maxFragLookUpTolerance,y=o>f-A?0:A;m=pi(p,u,Math.max(u[0].start,o),y),!m&&p&&p.start<u[0].start&&(m=u[0])}else m=u[d-1];if(m=this.filterReplacedPrimary(m,i.details),!m)return;const g=m.sn-l.startSN,E=u[g-1];if(E&&E.cc===m.cc&&this.fragmentTracker.getState(E)===Vt.NOT_LOADED&&(m=E),this.fragmentTracker.getState(m)===Vt.NOT_LOADED){const A=this.mapToInitFragWhenRequired(m);A&&this.loadFragment(A,i,o)}}}loadFragment(t,e,i){jt(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new jT(this.tracksBuffered[this.currentTrackId]||[])}}class jT{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 WT={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},gu=a=>String.fromCharCode(WT[a]||a),Te=15,ke=100,JT={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},QT={17:2,18:4,21:6,22:8,23:10,19:13,20:15},qT={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ZT={25:2,26:4,29:6,30:8,31:10,27:13,28:15},t_=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class e_{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i=typeof e=="function"?e():e;Tt.log(`${this.time} [${t}] ${i}`)}}}const ci=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class Eu{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 i_{constructor(){this.uchar=" ",this.penState=new Eu}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 s_{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Eu,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<ke;e++)this.chars.push(new i_);this.logger=t}equals(t){for(let e=0;e<ke;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<ke;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<ke;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ke)}moveCursor(t){const e=this.pos+t;if(t>1)for(let i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=gu(t);if(this.pos>=ke){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<ke;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<ke;i++){const s=this.chars[i].uchar;s!==" "&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class mr{constructor(t){this.rows=[],this.currRow=Te-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Te;e++)this.rows.push(new s_(t));this.logger=t}reset(){for(let t=0;t<Te;t++)this.rows[t].clear();this.currRow=Te-1}equals(t){let e=!0;for(let i=0;i<Te;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Te;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Te;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 = "+Bt(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<Te;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const o=r.rows[n].cueStartTime,h=this.logger.time;if(o!==null&&h!==null&&o<h)for(let l=0;l<this.nrRollUpRows;l++)this.rows[e-this.nrRollUpRows+l+1].copy(r.rows[n+l])}}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 = "+Bt(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<Te;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(`
37
+ `)),i}getTextAndFormat(){return this.rows}}class Yl{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 mr(i),this.nonDisplayedMemory=new mr(i),this.lastOutputScreen=new mr(i),this.currRollUpRow=this.displayedMemory.rows[Te-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[Te-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: "+Bt(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 Xl{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=r_(),this.logger=void 0;const s=this.logger=new e_;this.channels=[null,new Yl(t,e,s),new Yl(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,()=>"["+ci([e[i],e[i+1]])+"] -> ("+ci([s,n])+")");const h=this.cmdHistory;if(s>=16&&s<=31){if(n_(s,n,h)){Ws(null,null,h),this.logger.log(3,()=>"Repeated command ("+ci([s,n])+") is dropped");continue}Ws(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 Ws(null,null,h);if(!r&&(o=this.parseChars(s,n),o)){const c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!r&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ci([s,n])+" orig: "+ci([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 ("+ci([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?JT[t]:qT[t]:i=r===1?QT[t]:ZT[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 '"+gu(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 = "+ci(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=t_[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()}Ws(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 Ws(a,t,e){e.a=a,e.b=t}function n_(a,t,e){return e.a===a&&e.b===t}function r_(){return{a:null,b:null}}var Pa=function(){if(An!=null&&An.VTTCue)return self.VTTCue;const a=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,h){if(typeof h!="string"||!Array.isArray(o))return!1;const l=h.toLowerCase();return~o.indexOf(l)?l:!1}function i(o){return e(a,o)}function s(o){return e(t,o)}function n(o,...h){let l=1;for(;l<arguments.length;l++){const c=arguments[l];for(const u in c)o[u]=c[u]}return o}function r(o,h,l){const c=this,u={enumerable:!0};c.hasBeenReset=!1;let d="",f=!1,m=o,p=h,g=l,E=null,A="",y=!0,T="auto",_="start",C=50,S="middle",I=50,L="middle";Object.defineProperty(c,"id",n({},u,{get:function(){return d},set:function(b){d=""+b}})),Object.defineProperty(c,"pauseOnExit",n({},u,{get:function(){return f},set:function(b){f=!!b}})),Object.defineProperty(c,"startTime",n({},u,{get:function(){return m},set:function(b){if(typeof b!="number")throw new TypeError("Start time must be set to a number.");m=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},u,{get:function(){return p},set:function(b){if(typeof b!="number")throw new TypeError("End time must be set to a number.");p=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},u,{get:function(){return g},set:function(b){g=""+b,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},u,{get:function(){return E},set:function(b){E=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},u,{get:function(){return A},set:function(b){const w=i(b);if(w===!1)throw new SyntaxError("An invalid or illegal string was specified.");A=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},u,{get:function(){return y},set:function(b){y=!!b,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},u,{get:function(){return T},set:function(b){if(typeof b!="number"&&b!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},u,{get:function(){return _},set:function(b){const w=s(b);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");_=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},u,{get:function(){return C},set:function(b){if(b<0||b>100)throw new Error("Position must be between 0 and 100.");C=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},u,{get:function(){return S},set:function(b){const w=s(b);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");S=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},u,{get:function(){return I},set:function(b){if(b<0||b>100)throw new Error("Size must be between 0 and 100.");I=b,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},u,{get:function(){return L},set:function(b){const w=s(b);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");L=w,this.hasBeenReset=!0}})),c.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class a_{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function yu(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 o_{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 vu(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],h=r[1];t(o,h)}}const Wr=new Pa(0,0,""),Js=Wr.align==="middle"?"middle":"center";function l_(a,t,e){const i=a;function s(){const o=yu(a);if(o===null)throw new Error("Malformed timestamp: "+i);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,h){const l=new o_;vu(o,function(d,f){let m;switch(d){case"region":for(let p=e.length-1;p>=0;p--)if(e[p].id===f){l.set(d,e[p].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":m=f.split(","),l.integer(d,m[0]),l.percent(d,m[0])&&l.set("snapToLines",!1),l.alt(d,m[0],["auto"]),m.length===2&&l.alt("lineAlign",m[1],["start",Js,"end"]);break;case"position":m=f.split(","),l.percent(d,m[0]),m.length===2&&l.alt("positionAlign",m[1],["start",Js,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",Js,"end","left","right"]);break}},/:/,/\s/),h.region=l.get("region",null),h.vertical=l.get("vertical","");let c=l.get("line","auto");c==="auto"&&Wr.line===-1&&(c=-1),h.line=c,h.lineAlign=l.get("lineAlign","start"),h.snapToLines=l.get("snapToLines",!0),h.size=l.get("size",100),h.align=l.get("align",Js);let u=l.get("position","auto");u==="auto"&&Wr.position===50&&(u=h.align==="start"||h.align==="left"?0:h.align==="end"||h.align==="right"?100:50),h.position=u}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 Au(a){return a.replace(/<br(?: \/)?>/gi,`
38
+ `)}class h_{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new a_,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=Au(n);r<n.length&&n[r]!=="\r"&&n[r]!==`
39
+ `;)++r;const o=n.slice(0,r);return n[r]==="\r"&&++r,n[r]===`
40
+ `&&++r,e.buffer=n.slice(r),o}function s(n){vu(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 Pa(0,0,""),e.state="CUE",n.indexOf("-->")===-1){e.cue.id=n;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{l_(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+=`
41
+ `),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+=`
42
+
43
+ `,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 c_=/\r\n|\n\r|\n|\r/g,pr=function(t,e,i=0){return t.slice(i,i+e.length)===e},u_=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(!q(e)||!q(i)||!q(s)||!q(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=60*1e3*s,e+=60*60*1e3*n,e};function wa(a,t,e){return ps(a.toString())+ps(t.toString())+ps(e)}const d_=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 f_(a,t,e,i,s,n,r){const o=new h_,h=ae(new Uint8Array(a)).trim().replace(c_,`
44
+ `).split(`
45
+ `),l=[],c=t?FA(t.baseTime,t.timescale):0;let u="00:00.000",d=0,f=0,m,p=!0;o.oncue=function(g){const E=e[i];let A=e.ccOffset;const y=(d-c)/9e4;if(E!=null&&E.new&&(f!==void 0?A=e.ccOffset=E.start:d_(e,i,y)),y){if(!t){m=new Error("Missing initPTS for VTT MPEGTS");return}A=y-e.presentationOffset}const T=g.endTime-g.startTime,_=fe((g.startTime+A-f)*9e4,s*9e4)/9e4;g.startTime=Math.max(_,0),g.endTime=Math.max(_+T,0);const C=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(C)),g.id||(g.id=wa(g.startTime,g.endTime,C)),g.endTime>0&&l.push(g)},o.onparsingerror=function(g){m=g},o.onflush=function(){if(m){r(m);return}n(l)},h.forEach(g=>{if(p)if(pr(g,"X-TIMESTAMP-MAP=")){p=!1,g.slice(16).split(",").forEach(E=>{pr(E,"LOCAL:")?u=E.slice(6):pr(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{f=u_(u)/1e3}catch(E){m=E}return}else g===""&&(p=!1);o.parse(g+`
46
+ `)}),o.flush()}const gr="stpp.ttml.im1t",Tu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,_u=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,m_={left:"start",center:"center",right:"end",start:"start",end:"end"};function jl(a,t,e,i){const s=dt(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=OA(t.baseTime,1,t.timescale);try{n.forEach(o=>e(p_(o,r)))}catch(o){i(o)}}function p_(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((u,d)=>(u[d]=s.getAttribute(`ttp:${d}`)||n[d],u),{}),o=s.getAttribute("xml:space")!=="preserve",h=Wl(Er(s,"styling","style")),l=Wl(Er(s,"layout","region")),c=Er(s,"body","[begin]");return[].map.call(c,u=>{const d=Su(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=vr(u.getAttribute("begin"),r),m=vr(u.getAttribute("dur"),r);let p=vr(u.getAttribute("end"),r);if(f===null)throw Jl(u);if(p===null){if(m===null)throw Jl(u);p=f+m}const g=new Pa(f-t,p-t,d);g.id=wa(g.startTime,g.endTime,g.text);const E=l[u.getAttribute("region")],A=h[u.getAttribute("style")],y=g_(E,A,h),{textAlign:T}=y;if(T){const _=m_[T];_&&(g.lineAlign=_),g.align=T}return bt(g,y),g}).filter(u=>u!==null)}function Er(a,t,e){const i=a.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function Wl(a){return a.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Su(a,t){return[].slice.call(a.childNodes).reduce((e,i,s)=>{var n;return i.nodeName==="br"&&s?e+`
47
+ `:(n=i.childNodes)!=null&&n.length?Su(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function g_(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,h)=>{const l=yr(t,i,h)||yr(a,i,h)||yr(s,i,h);return l&&(o[h]=l),o},{})}function yr(a,t,e){return a&&a.hasAttributeNS(t,e)?a.getAttributeNS(t,e):null}function Jl(a){return new Error(`Could not parse ttml timestamp ${a}`)}function vr(a,t){if(!a)return null;let e=yu(a);return e===null&&(Tu.test(a)?e=E_(a,t):_u.test(a)&&(e=y_(a,t))),e}function E_(a,t){const e=Tu.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 y_(a,t){const e=_u.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 Qs{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 xu{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=ql(),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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(v.FRAG_LOADING,this.onFragLoading,this),t.on(v.FRAG_LOADED,this.onFragLoaded,this),t.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(v.FRAG_LOADING,this.onFragLoading,this),t.off(v.FRAG_LOADED,this.onFragLoaded,this),t.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Qs(this,"textTrack1"),e=new Qs(this,"textTrack2"),i=new Qs(this,"textTrack3"),s=new Qs(this,"textTrack4");this.cea608Parser1=new Xl(1,t,e),this.cea608Parser2=new Xl(3,i,s)}addCues(t,e,i,s,n){let r=!1;for(let o=n.length;o--;){const h=n[o],l=v_(h[0],h[1],e,i);if(l>=0&&(h[0]=Math.min(h[0],e),h[1]=Math.max(h[1],i),r=!0,l/(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(v.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(v.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(Ql(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,Mi(i[t]),uu(i[t],s);else{const h=this.createTextTrack("captions",n,r);h&&(h[t]=!0,i[t]=h)}}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(v.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=>{Mi(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ql(),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++)Mi(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(n=>n.textCodec===gr);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(qc(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const r=this.media,o=r?ln(r.textTracks):null;if(this.tracks.forEach((h,l)=>{let c;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Ql(o[d],h)){u=o[d],o[d]=null;break}u&&(c=u)}if(c)Mi(c);else{const u=Cu(h);c=this.createTextTrack(u,h.name,h.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){const h=o.filter(l=>l!==null).map(l=>l.label);h.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${h.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(v.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:h,sn:l}=e.frag,c=(i=(s=e.part)==null?void 0:s.index)!=null?i:-1;n&&r&&(l!==o+1||l===o&&c!==this.lastPartIndex+1||h!==this.lastCc)&&(n.reset(),r.reset()),this.lastCc=h,this.lastSn=l,this.lastPartIndex=c}}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],h=this.vttCCs;h[i.cc]||(h[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===gr?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;jl(e,this.initPTS[t.cc],s=>{this._appendCues(s,t.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(v.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 h=this.hls,l=(e=i.initSegment)!=null&&e.data?pe(i.initSegment.data,new Uint8Array(s)).buffer:s;f_(l,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),h.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{const u=c.message==="Missing initPTS for VTT MPEGTS";u?r.push(t):this._fallbackToIMSC1(i,s),h.logger.log(`Failed to parse VTT cue: ${c}`),!(u&&o>i.cc)&&h.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||jl(e,this.initPTS[t.cc],()=>{i.textCodec=gr,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=>du(s,n))}else{const s=this.tracks[e];if(!s)return;const n=s.default?"default":"subtitles"+e;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:t,track:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===Z.SUBTITLE&&this.onFragLoaded(v.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(h=>jr(o[h],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(h=>jr(o[h],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++],h=127&t[s++];if(o===0&&h===0)continue;if((4&r)!==0){const c=3&r;(c===0||c===1)&&(e[c].push(o),e[c].push(h))}}return e}}function Cu(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Ql(a,t){return!!a&&a.kind===Cu(t)&&zr(t,a)}function v_(a,t,e,i){return Math.min(t,i)-Math.max(a,e)}function ql(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const A_=/\s/,bu={newCue(a,t,e,i){const s=[];let n,r,o,h,l;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,h=0,l="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)A_.test(n.chars[p].uchar)&&o?h++:(l+=n.chars[p].uchar,o=!1);n.cueStartTime=t,t===e&&(e+=1e-4),h>=16?h--:h++;const f=Au(l.trim()),m=wa(t,e,f);a!=null&&(u=a.cues)!=null&&u.getCueById(m)||(r=new c(t,e,f),r.id=m,r.line=d+1,r.align="left",r.position=10+Math.min(80,Math.floor(h*8/32)*10),s.push(r))}return a&&s.length&&(s.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),s.forEach(d=>du(a,d))),s}};function Iu(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const T_=/(\d+)-(\d+)\/(\d+)/;class Jr{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||C_,this.controller=new self.AbortController,this.stats=new Ln}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=__(t,this.controller.signal),r=t.responseType==="arraybuffer",o=r?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=h&&q(h)?h:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},e.timeout),(As(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},l-(f-s.loading.start)),!u.ok){const{status:p,statusText:g}=u;throw new b_(g||"fetch, bad network response",p,u)}s.loading.first=f,s.total=x_(u.headers)||s.total;const m=(d=this.callbacks)==null?void 0:d.onProgress;return m&&q(e.highWaterMark)?this.loadProgressively(u,s,t,e.highWaterMark,m):r?u.arrayBuffer():t.responseType==="json"?u.json():u.text()}).then(u=>{var d,f;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=u[o];p&&(s.loaded=s.total=p);const g={url:m.url,data:u,code:m.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!q(e.highWaterMark)&&E(s,t,u,m),(f=this.callbacks)==null||f.onSuccess(g,s,t,m)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const f=u&&u.code||0,m=u?u.message:null;(d=this.callbacks)==null||d.onError({code:f,text:m},t,u?u.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,n){const r=new Pc,o=t.body.getReader(),h=()=>o.read().then(l=>{if(l.done)return r.dataLength&&n(e,i,r.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const c=l.value,u=c.length;return e.loaded+=u,u<s||r.dataLength?(r.push(c),r.dataLength>=s&&n(e,i,r.flush().buffer,t)):n(e,i,c.buffer,t),h()}).catch(()=>Promise.reject());return h()}}function __(a,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(bt({},a.headers))};return a.rangeEnd&&e.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),e}function S_(a){const t=T_.exec(a);if(t)return parseInt(t[2])-parseInt(t[1])+1}function x_(a){const t=a.get("Content-Range");if(t){const i=S_(t);if(q(i))return i}const e=a.get("Content-Length");if(e)return parseInt(e)}function C_(a,t){return new self.Request(a.url,t)}class b_ extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const I_=/^age:\s*[\d.]+\s*$/im;class Ma{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 Ln,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&&q(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 l=e.status,c=e.responseType==="text"?e.responseText:null;if(l>=200&&l<300){const m=c??e.response;if(m!=null){var r,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=e.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const g=(r=this.callbacks)==null?void 0:r.onProgress;g&&g(i,t,m,e);const E={url:e.responseURL,data:m,code:l};(o=this.callbacks)==null||o.onSuccess(E,i,t,e);return}}const u=n.loadPolicy.errorRetry,d=i.retry,f={url:t.url,data:void 0,code:l};if(vn(u,d,!1,f))this.retry(u);else{var h;Tt.error(`${l} while loading ${t.url}`),(h=this.callbacks)==null||h.onError({code:l,text:e.statusText},t,e,i)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(vn(t,e,!0))this.retry(t);else{var i;Tt.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=Ea(t,i.retry),i.retry++,Tt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e==null?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&I_.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const L_={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},R_=xt(xt({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,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",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:Ma,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mc,bufferController:eu,capLevelController:Bn,errorController:Ec,fpsController:cu,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:_a,requireKeySystemAccessOnStart:!1,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,preserveManualLevelOnError:!1,certLoadPolicy:{default:L_},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},D_()),{},{subtitleStreamController:pu,subtitleTrackController:fu,timelineController:xu,audioStreamController:Qc,audioTrackController:Zc,emeController:mi,cmcdController:ou,contentSteeringController:lu,interstitialsController:XT});function D_(){return{cueHandler:bu,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 P_(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=Qr(a),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,h=t[o]===void 0,l=[];n.forEach(c=>{const u=`${r}Loading${c}`,d=t[u];if(d!==void 0&&h){l.push(u);const f=i[o].default;switch(t[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&e.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${Bt(t[o])}`)}),xt(xt({},i),t)}function Qr(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Qr):Object.keys(a).reduce((t,e)=>(t[e]=Qr(a[e]),t),{}):a}function w_(a,t){const e=a.loader;e!==Jr&&e!==Ma?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Iu()&&(a.loader=Jr,a.progressive=!0,a.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const hn=2,M_=.1,B_=.05,O_=100;class F_ extends yc{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(v.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.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(O_),this.mediaSource=e.mediaSource;const i=this.media=e.media;re(i,"playing",this.onMediaPlaying),re(i,"waiting",this.onMediaWaiting),re(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(me(i,"playing",this.onMediaPlaying),me(i,"waiting",this.onMediaWaiting),me(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 r=this.media;if(!r)return;const{seeking:o}=r,h=this.seeking&&!o,l=!this.seeking&&o,c=r.paused&&!o||r.ended||r.playbackRate===0;if(this.seeking=o,t!==e){e&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&t>e&&this.nudgeOnVideoHole(t,e)),this.waiting===0&&this.stallResolved(t);return}if(l||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(v.MEDIA_ENDED,{stalled:!1}));return}if(!ht.getBuffered(r).length){this.nudgeRetry=0;return}const u=ht.bufferInfo(r,t,0),d=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const C=Zl(this.hls.inFlightFragments,t),S=u.len>hn,I=!d||C||d-t>hn&&!f.getPartialFragment(t);if(S||I)return;this.moved=!1}const m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!d)return;const S=Math.max(d,u.start||0)-t,L=!!(m!=null&&m.live)?m.targetduration*2:hn,b=f.getPartialFragment(t);if(S>0&&(S<=L||b)){r.paused||this._trySkipBufferHole(b);return}}const p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),E=this.waiting;let A=this.stalled;if(A===null)if(E>0&&g-E<p)A=this.stalled=E;else{this.stalled=g;return}const y=g-A;if(!o&&(y>=p||E)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(t-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const _=ht.bufferInfo(r,t,n.maxBufferHole);this._tryFixBufferStall(_,y,t)}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(v.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=ht.bufferedInfo(ht.timeRangesToArray(this.buffered.audio),t,0);if(n.len>1&&e>=n.start){const r=ht.timeRangesToArray(s),o=ht.bufferedInfo(r,e,0).bufferedIndex;if(o>-1&&o<r.length-1){const h=ht.bufferedInfo(r,t,0).bufferedIndex,l=r[o].end,c=r[o+1].start;if((h===-1||h>o)&&c-l<1&&t-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${l} -> ${c} buffered index: ${h}`);this.warn(u.message),this.media.currentTime+=1e-6;const d=this.fragmentTracker.getPartialFragment(t)||void 0,f=ht.bufferInfo(this.media,t,0);this.hls.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,e,i){var s,n;const{fragmentTracker:r,media:o}=this,h=(s=this.hls)==null?void 0:s.config;if(!o||!r||!h)return;const l=(n=this.hls)==null?void 0:n.latestLevelDetails,c=r.getPartialFragment(i);if((c||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;const u=t.buffered,d=this.adjacentTraversal(t,i);(u&&u.length>1&&t.len>h.maxBufferHole||t.nextStart&&(t.nextStart-i<h.maxBufferHole||d))&&(e>h.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const n=i.getFragAtPos(e,Z.MAIN),r=i.getFragAtPos(s,Z.MAIN);if(n&&r)return r.sn-n.sn<2}return!1}_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 (${Bt(t)})`);this.warn(r.message),e.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.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=ht.bufferInfo(s,r,0),h=r<o.start?o.start:o.nextStart;if(h&&this.hls){const c=o.len<=n.maxBufferHole,u=o.len>0&&o.len<1&&s.readyState<3,d=h-r;if(d>0&&(c||u)){if(d>n.maxBufferHole){let m=!1;if(r===0){const p=i.getAppendedFrag(0,Z.MAIN);p&&h<p.end&&(m=!0)}if(!m){const p=t||i.getAppendedFrag(r,Z.MAIN);if(p){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Zl(this.hls.inFlightFragments,h))return 0;let E=!1,A=p.end;for(;A<h;){const y=i.getPartialFragment(A);if(y)A+=y.duration;else{E=!0;break}}if(E)return 0}}}const f=Math.max(h+B_,r+M_);if(this.warn(`skipping hole, adjusting currentTime from ${r} to ${f}`),this.moved=!0,s.currentTime=f,!(t!=null&&t.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${f}`);this.hls.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:t||void 0,buffer:o.len,bufferInfo:o})}return f}}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,h=new Error(`Nudging 'currentTime' from ${r} to ${o}`);this.warn(h.message),i.currentTime=o,e.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.BUFFER_NUDGE_ON_STALL,error:h,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(v.ERROR,{type:et.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Zl(a,t){const e=th(a.main);if(e&&e.start<=t)return e;const i=th(a.audio);return i&&i.start<=t?i:null}function th(a){if(!a)return null;switch(a.state){case N.IDLE:case N.STOPPED:case N.ENDED:case N.ERROR:return null}return a.frag}const k_=.25;function qr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function eh(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,Bt(s?xt({type:s},i):i))}return n}const qs=(()=>{const a=qr();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function U_(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class N_{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(v.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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.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&&Mi(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 uu(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=qr();if(r)for(let o=0;o<n.length;o++){const h=n[o].type;if(h===ie.emsg&&!i||!s)continue;const l=Uc(n[o].data);if(l){const c=n[o].pts;let u=c+n[o].duration;u>qs&&(u=qs),u-c<=0&&(u=c+k_);for(let f=0;f<l.length;f++){const m=l[f];if(!Nc(m)){this.updateId3CueEnds(c,h);const p=eh(r,c,u,m,h);p&&this.id3Track.addCue(p)}}}}}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===qs&&(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:h}}=r;if(n&&(o||h)){let l;s==="audio"?l=c=>c.type===ie.audioId3&&h:s==="video"?l=c=>c.type===ie.emsg&&o:l=c=>c.type===ie.audioId3&&h||c.type===ie.emsg&&o,jr(n,e,i,l)}}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 c=Object.keys(r).filter(u=>!n.includes(u));for(let u=c.length;u--;){const d=c[u],f=r[d].cues;delete r[d],Object.keys(f).forEach(m=>{try{const p=f[m];p.removeEventListener("enter",this.onEventCueEnter),i.removeCue(p)}catch{}})}}else r=this.dateRangeCuesAppended={}}const h=t.fragments[t.fragments.length-1];if(n.length===0||!q(h==null?void 0:h.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=qr();for(let c=0;c<n.length;c++){const u=n[c],d=s[u],f=d.startTime,m=r[u],p=(m==null?void 0:m.cues)||{};let g=(m==null?void 0:m.durationKnown)||!1,E=qs;const{duration:A,endDate:y}=d;if(y&&A!==null)E=f+A,g=!0;else if(d.endOnNext&&!g){const _=n.reduce((C,S)=>{if(S!==d.id){const I=s[S];if(I.class===d.class&&I.startDate>d.startDate&&(!C||d.startDate<C.startDate))return I}return C},null);_&&(E=_.startTime,g=!0)}const T=Object.keys(d.attr);for(let _=0;_<T.length;_++){const C=T[_];if(!Lv(C))continue;const S=p[C];if(S)g&&!m.durationKnown?S.endTime=E:Math.abs(S.startTime-f)>.01&&(S.startTime=f,S.endTime=E);else if(l){let I=d.attr[C];Rv(C)&&(I=U_(I));const b=eh(l,f,E,{key:C,data:I},ie.dateRange);b&&(b.id=u,this.id3Track.addCue(b),p[C]=b,this.hls.config.interstitialsController&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&b.addEventListener("enter",this.onEventCueEnter))}}r[u]={cues:p,dateRange:d,durationKnown:g}}}}class G_{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 h=s-o,l=Math.min(this.maxLatency,o+i.targetduration);if(h<l&&h>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,r)),d=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(e,f)}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,h=this.hls.userConfig;let l=o&&i||e;(this._targetLatencyUpdated||h.liveSyncDuration||h.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:r*s);const c=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}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(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.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===P.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 H_ extends Mn{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(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.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,h=!1,l=!1;e.levels.forEach(c=>{const u=c.attrs;let{audioCodec:d,videoCodec:f}=c;d&&(c.audioCodec=d=pn(d,i)||void 0),f&&(f=c.videoCodec=qy(f));const{width:m,height:p,unknownCodecs:g}=c;let E=g?g.length:0;if(g)for(let b=E;b--;){const w=g[b];this.isAudioSupported(w)?(c.audioCodec=d=d?`${d},${w}`:w,E--,ki.audio[d.substring(0,4)]=2):this.isVideoSupported(w)&&(c.videoCodec=f=f?`${f},${w}`:w,E--,ki.video[f.substring(0,4)]=2)}if(o||(o=!!(m&&p)),h||(h=!!f),l||(l=!!d),E||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:A,"FRAME-RATE":y,"HDCP-LEVEL":T,"PATHWAY-ID":_,RESOLUTION:C,"VIDEO-RANGE":S}=u,L=`${`${_||"."}-`}${c.bitrate}-${C}-${y}-${A}-${S}-${T}`;if(n[L])if(n[L].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const b=r[L]+=1;c.attrs["PATHWAY-ID"]=new Array(b+1).join(".");const w=this.createLevel(c);n[L]=w,s.push(w)}else n[L].addGroupId("audio",u.AUDIO),n[L].addGroupId("text",u.SUBTITLES);else{const b=this.createLevel(c);n[L]=b,r[L]=1,s.push(b)}}),this.filterAndSortMediaOptions(s,e,o,h,l)}createLevel(t){const e=new Ui(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=uc(s,[])}return e}isAudioSupported(t){return Fr(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Fr(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,n){let r=[],o=[],h=t;if((i||s)&&n&&(h=h.filter(({videoCodec:g,videoRange:E,width:A,height:y})=>(!!g||!!(A&&y))&&sv(E))),h.length===0){Promise.resolve().then(()=>{if(this.hls){let g="no level with compatible codecs found in manifest",E=g;e.levels.length&&(E=`one or more CODECS in variant not supported: ${Bt(e.levels.map(y=>y.attrs.CODECS).filter((y,T,_)=>_.indexOf(y)===T))}`,this.warn(E),g+=` (${E})`);const A=new Error(g);this.hls.trigger(v.ERROR,{type:et.MEDIA_ERROR,details:P.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:A,reason:E})}});return}e.audioTracks&&(r=e.audioTracks.filter(g=>!g.audioCodec||this.isAudioSupported(g.audioCodec)),ih(r)),e.subtitles&&(o=e.subtitles,ih(o));const l=h.slice(0);h.sort((g,E)=>{if(g.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&g.height!==E.height)return g.height-E.height;if(g.frameRate!==E.frameRate)return g.frameRate-E.frameRate;if(g.videoRange!==E.videoRange)return gn.indexOf(g.videoRange)-gn.indexOf(E.videoRange);if(g.videoCodec!==E.videoCodec){const A=Qo(g.videoCodec),y=Qo(E.videoCodec);if(A!==y)return y-A}if(g.uri===E.uri&&g.codecSet!==E.codecSet){const A=mn(g.codecSet),y=mn(E.codecSet);if(A!==y)return y-A}return g.averageBitrate!==E.averageBitrate?g.averageBitrate-E.averageBitrate:0});let c=l[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==l.length)){for(let g=0;g<l.length;g++)if(l[g].pathwayId===h[0].pathwayId){c=l[g];break}}this._levels=h;for(let g=0;g<h.length;g++)if(h[g]===c){var u;this._firstLevel=g;const E=c.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${E}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const y=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);y>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}const d=n&&!s,f=this.hls.config,m=!!(f.audioStreamController&&f.audioTrackController),p={levels:h,audioTracks:r,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:n,video:s,altAudio:m&&!d&&r.some(g=>!!g.url)};this.hls.trigger(v.MANIFEST_PARSED,p)}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 c=new Error("invalid level idx"),u=t<0;if(this.hls.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.LEVEL_SWITCH_ERROR,level:t,fatal:u,error:c,reason:c.message}),u)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 h={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(v.LEVEL_SWITCHING,h);const l=r.details;if(!l||l.live){const c=this.switchParams(r.uri,s==null?void 0:s.details,l);this.loadPlaylist(c)}}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===pt.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 h=r.details;h===e.details&&h.advanced&&(h=void 0),this.playlistLoaded(s,e,h)}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(v.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));Lc(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(v.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(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function ih(a){const t={};a.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function Lu(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ba(){if(!Ve())return!1;const t=Lu();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Ru(){if(!Ba())return!1;const a=Ve();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(gs(t,"video")))||["mp4a.40.2","fLaC"].some(t=>a.isTypeSupported(gs(t,"audio"))))}function $_(){var a;const t=Lu();return typeof(t==null||(a=t.prototype)==null?void 0:a.changeType)=="function"}const K_=100;class V_ extends Pn{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||!q(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(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(v.BUFFER_CREATED,this.onBufferCreated,this),t.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(v.BUFFER_CREATED,this.onBufferCreated,this),t.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.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(K_),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=N.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=N.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case N.WAITING_LEVEL:{const{levels:e,level:i}=this,s=e==null?void 0:e[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=N.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=N.IDLE;break}break}case N.FRAG_LOADING_WAITING_RETRY:{var t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||(t=this.media)!=null&&t.seeking){const{levels:s,level:n}=this,r=s==null?void 0:s[n];this.resetStartWhenNotLoaded(r||null),this.state=N.IDLE}}break}this.state===N.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 h=this.getLevelDetails();if(h&&this._streamEnded(o,h)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(v.BUFFER_EOS,p),this.state=N.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 l=r.details;if(!l||this.state===N.WAITING_LEVEL||this.waitForLive(r)){this.level=n,this.state=N.WAITING_LEVEL,this.startFragRequested=!1;return}const c=o.len,u=this.getMaxBufferLength(r.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&jt(f)&&this.fragmentTracker.getState(f)!==Vt.OK){var m;const g=((m=this.backtrackFragment)!=null?m:f).sn-l.startSN,E=l.fragments[g-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const g=this.audioOnly&&!this.altAudio?Rt.AUDIO:Rt.VIDEO,E=(g===Rt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,g,Z.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,Z.MAIN,u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,r,d))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===Vt.NOT_LOADED||s===Vt.PARTIAL?jt(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,h=t[o],l=this.fragLastKbps;l&&this.fragCurrent?i=this.fragCurrent.duration*h.maxBitrate/(1e3*l)+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 h=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,c=Math.max(r.end,h+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case N.KEY_LOADING:case N.FRAG_LOADING:case N.FRAG_LOADING_WAITING_RETRY:case N.PARSING:case N.PARSED:this.state=N.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio===2?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;re(i,"playing",this.onMediaPlaying),re(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(me(i,"playing",this.onMediaPlaying),me(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(v.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&&!$_(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==N.IDLE)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=N.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:n}=this,r=e.level,o=e.details,h=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:${h}`);const l=e.levelInfo,c=this.fragCurrent;c&&(this.state===N.FRAG_LOADING||this.state===N.FRAG_LOADING_WAITING_RETRY)&&c.level!==e.level&&c.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=l.details)!=null&&i.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,u),this.hls.trigger(v.LEVEL_UPDATED,{details:o,level:r}),this.state===N.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=N.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,h=n>=r-e.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!h)){const c=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!h&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=ht.bufferInfo(i,s,0);if(!(u!=null&&(l=u.buffered)!=null&&l.length)){i.currentTime=s;return}if(u.start<=n){i.currentTime=s;return}const{nextStart:f}=ht.bufferedInfo(u.buffered,n,0);f&&(i.currentTime=f)}else 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 h=o.details;if(!h){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const l=o.videoCodec,c=h.PTSKnown||!h.live,u=(e=i.initSegment)==null?void 0:e.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Jc(this.hls,Z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,p=m!==-1,g=new Dn(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p),E=this.initPTS[i.cc];f.push(n,u,d,l,i,s,h.totalduration,c,g,E)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio===2;if(En(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(v.BUFFER_FLUSHED,()=>{var r;(r=this.hls)==null||r.trigger(v.AUDIO_TRACK_SWITCHED,e)}),i.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(v.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=En(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 h=i[o];if(h.id==="main"){if(n=o,s=h,o==="video"){const l=i[o];l&&(this.videoBuffer=l.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===N.PARSED&&(this.state=N.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),jt(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const r=this.media;r&&(!this._hasEnoughToStart&&ht.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=N.ERROR;return}switch(e.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.MAIN,e);break;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===N.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===pt.LEVEL&&(this.state=N.IDLE);break;case P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;this.resetLoadingState();break;case P.BUFFER_FULL_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){this.state=N.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Rt.AUDIO||!this.altAudio){const i=(e===Rt.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=ht.getBuffered(t),o=r.length?r.start(0):0,h=o-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||h>0&&(h<l||this.loadingParts&&h<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${h} to match buffer start`),i+=h,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=N.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(v.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:h,part:l,level:c}=o,{video:u,text:d,id3:f,initSegment:m}=n,{details:p}=c,g=this.altAudio?void 0:n.audio;if(this.fragContextChanged(h)){this.fragmentTracker.removeFragment(h);return}if(this.state=N.PARSING,m){if(m!=null&&m.tracks){const y=h.initSegment||h;this._bufferInitSegment(c,m.tracks,y,r),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:m.tracks})}const E=m.initPTS,A=m.timescale;q(E)&&(this.initPTS[h.cc]={baseTime:E,timescale:A},s.trigger(v.INIT_PTS_FOUND,{frag:h,id:i,initPTS:E,timescale:A}))}if(u&&p){g&&u.type==="audiovideo"&&this.logMuxedErr(h);const E=p.fragments[h.sn-1-p.startSN],A=h.sn===p.startSN,y=!E||h.cc>E.cc;if(n.independent!==!1){const{startPTS:T,endPTS:_,startDTS:C,endDTS:S}=u;if(l)l.elementaryStreams[u.type]={startPTS:T,endPTS:_,startDTS:C,endDTS:S};else if(u.firstKeyFrame&&u.independent&&r.id===1&&!y&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),L=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,b=u.firstKeyFramePTS?u.firstKeyFramePTS:T;if(!A&&L<b-this.config.maxBufferHole&&!y){this.backtrack(h);return}else y&&(h.gap=!0);h.setElementaryStreamInfo(u.type,h.start,_,h.start,S,!0)}else A&&T-(p.appliedTimelineOffset||0)>hn&&(h.gap=!0);h.setElementaryStreamInfo(u.type,T,_,C,S),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(u,h,l,r,A||y)}else if(A||y)h.gap=!0;else{this.backtrack(h);return}}if(g){const{startPTS:E,endPTS:A,startDTS:y,endDTS:T}=g;l&&(l.elementaryStreams[Rt.AUDIO]={startPTS:E,endPTS:A,startDTS:y,endDTS:T}),h.setElementaryStreamInfo(Rt.AUDIO,E,A,y,T),this.bufferFragmentData(g,h,l,r)}if(p&&f!=null&&(e=f.samples)!=null&&e.length){const E={id:i,frag:h,details:p,samples:f.samples};s.trigger(v.FRAG_PARSING_METADATA,E)}if(p&&d){const E={id:i,frag:h,details:p,samples:d.samples};s.trigger(v.FRAG_PARSING_USERDATA,E)}}logMuxedErr(t){this.warn(`${jt(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==N.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 l=sn(n.codec,t.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const u=n.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),t.audioCodec&&t.audioCodec!==l&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${l}"`),n.levelCodec=l,n.id=Z.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${t.audioCodec||""}/${n.codec}]`),delete e.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=Z.MAIN;const l=r.codec;if((l==null?void 0:l.length)===4)switch(l){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||""}/${l}]${r.codec!==l?" 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 h=Object.keys(e);if(h.length){if(this.hls.trigger(v.BUFFER_CODECS,e),!this.hls)return;h.forEach(l=>{const u=e[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:l,data:u,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=N.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(ht.isBuffered(t,i)?e=this.getAppendedFrag(i):ht.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(v.FRAG_CHANGED,{frag:e}),(!s||s.level!==n)&&this.hls.trigger(v.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 q(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(q(e)){const i=this.getLevelDetails(),s=this.currentFrag||(i?pi(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 z_{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=P.KEY_LOAD_ERROR,i,s,n){return new Ue({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&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length){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))return this.emeController.selectKeySystemFormat(r).then(o=>{if(r.setKeyFormat(o),this.emeController&&this.config.requireKeySystemAccessOnStart){const h=nn(o);if(h)return this.emeController.getKeySystemAccess([h])}})}}else if(this.config.requireKeySystemAccessOnStart){const i=os(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}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 l=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,P.KEY_LOAD_ERROR,l))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(t,P.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 h;switch((h=o.mediaKeySessionContext)==null?void 0:h.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>(n.key=l.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,P.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 h={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,m,p)=>{const{frag:g,keyInfo:E,url:A}=m;if(!g.decryptdata||E!==this.keyUriToKeyInfo[A])return o(this.createKeyLoadError(g,P.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=g.decryptdata.key=new Uint8Array(d.data),g.keyLoader=null,E.loader=null,r({frag:g,keyInfo:E})},onError:(d,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,P.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),m,xt({url:h.url,data:void 0},d)))},onTimeout:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(e,P.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(e,P.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(h,c,u)})}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 sh(a){const{type:t}=a;switch(t){case pt.AUDIO_TRACK:return Z.AUDIO;case pt.SUBTITLE_TRACK:return Z.SUBTITLE;default:return Z.MAIN}}function Ar(a,t){let e=a.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class Y_{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(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_LOADING,this.onLevelLoading,this),t.off(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(v.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:pt.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:n,url:r,deliveryDirectives:o,levelInfo:h}=e;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:pt.LEVEL,url:r,deliveryDirectives:o,levelOrTrack:h})}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:pt.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:pt.SUBTITLE_TRACK,url:n,deliveryDirectives:r,levelOrTrack:o})}onLevelsUpdated(t,e){const i=this.loaders[pt.LEVEL];if(i){const s=i.context;s&&!e.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[pt.LEVEL])}}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const l=this.hls.logger,c=s.context;if(c&&c.levelOrTrack===t.levelOrTrack&&(c.url===t.url||c.deliveryDirectives&&!t.deliveryDirectives)){c.url===t.url?l.log(`[playlist-loader]: ignore ${t.url} ongoing request`):l.log(`[playlist-loader]: ignore ${t.url} in favor of ${c.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let n;if(t.type===pt.MANIFEST?n=i.manifestLoadPolicy.default:n=bt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),q((e=t.deliveryDirectives)==null?void 0:e.part)){let l;if(t.type===pt.LEVEL&&t.level!==null?l=this.hls.levels[t.level].details:t.type===pt.AUDIO_TRACK&&t.id!==null?l=this.hls.audioTracks[t.id].details:t.type===pt.SUBTITLE_TRACK&&t.id!==null&&(l=this.hls.subtitleTracks[t.id].details),l){const c=l.partTarget,u=l.targetduration;if(c&&u){const d=Math.max(c*3,u*.8)*1e3;n=bt({},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},h={onSuccess:(l,c,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const m=l.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,u,new Error("no EXTM3U delimiter"),d||null,c);return}c.parsing.start=performance.now(),_e.isMediaPlaylist(m)||u.type!==pt.MANIFEST?this.handleTrackOrLevelPlaylist(l,c,u,d||null,f):this.handleMasterPlaylist(l,c,u,d)},onError:(l,c,u,d)=>{this.handleNetworkError(c,u,!1,l,d)},onTimeout:(l,c,u)=>{this.handleNetworkError(c,u,!0,void 0,l)}};s.load(t,o,h)}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=Ar(t,i),h=_e.parseMasterPlaylist(r,o);if(h.playlistParsingError){this.handleManifestParsingError(t,i,h.playlistParsingError,s,e);return}const{contentSteering:l,levels:c,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:m}=h;this.variableList=m;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":E}=_e.parseMasterPlaylistMedia(r,o,h);p.length&&!p.some(y=>!y.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Mt({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:E,contentSteering:l,url:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(t,e,i,s,n){const r=this.hls,{id:o,level:h,type:l}=i,c=Ar(t,i),u=q(h)?h:q(o)?o:0,d=sh(i),f=_e.parseLevelPlaylist(t.data,c,u,d,0,this.variableList);if(l===pt.MANIFEST){const m={attrs:new Mt({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=e.loading.start+Cc(f,0),r.trigger(v.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:c,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,t,e,i,s,n)}handleManifestParsingError(t,e,i,s,n){this.hls.trigger(v.ERROR,{type:et.NETWORK_ERROR,details:P.MANIFEST_PARSING_ERROR,fatal:e.type===pt.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===pt.LEVEL?r+=`: ${t.level} id: ${t.id}`:(t.type===pt.AUDIO_TRACK||t.type===pt.SUBTITLE_TRACK)&&(r+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let h=P.UNKNOWN,l=!1;const c=this.getInternalLoader(t);switch(t.type){case pt.MANIFEST:h=i?P.MANIFEST_LOAD_TIMEOUT:P.MANIFEST_LOAD_ERROR,l=!0;break;case pt.LEVEL:h=i?P.LEVEL_LOAD_TIMEOUT:P.LEVEL_LOAD_ERROR,l=!1;break;case pt.AUDIO_TRACK:h=i?P.AUDIO_TRACK_LOAD_TIMEOUT:P.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case pt.SUBTITLE_TRACK:h=i?P.SUBTITLE_TRACK_LOAD_TIMEOUT:P.SUBTITLE_LOAD_ERROR,l=!1;break}c&&this.resetInternalLoader(t.type);const u={type:et.NETWORK_ERROR,details:h,fatal:l,url:t.url,loader:c,context:t,error:o,networkDetails:e,stats:n};if(s){const d=(e==null?void 0:e.url)||t.url;u.response=xt({url:d,data:void 0},s)}this.hls.trigger(v.ERROR,u)}handlePlaylistLoaded(t,e,i,s,n,r){const o=this.hls,{type:h,level:l,id:c,groupId:u,deliveryDirectives:d}=s,f=Ar(e,s),m=sh(s),p=typeof s.level=="number"&&m===Z.MAIN?l:void 0;if(!t.fragments.length){const E=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(v.ERROR,{type:et.NETWORK_ERROR,details:P.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:e,context:s,level:p,parent:m,networkDetails:n,stats:i});return}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const g=t.playlistParsingError;if(g){if(this.hls.logger.warn(g),!o.config.ignorePlaylistParsingErrors){o.trigger(v.ERROR,{type:et.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:g,reason:g.message,response:e,context:s,level:p,parent:m,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)),h){case pt.MANIFEST:case pt.LEVEL:o.trigger(v.LEVEL_LOADED,{details:t,levelInfo:s.levelOrTrack||o.levels[0],level:p||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:d,withoutMultiVariant:h===pt.MANIFEST});break;case pt.AUDIO_TRACK:o.trigger(v.AUDIO_TRACK_LOADED,{details:t,track:s.levelOrTrack,id:c||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case pt.SUBTITLE_TRACK:o.trigger(v.SUBTITLE_TRACK_LOADED,{details:t,track:s.levelOrTrack,id:c||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d});break}}}class He{static get version(){return ys}static isMSESupported(){return Ba()}static isSupported(){return Ru()}static getMediaSource(){return Ve()}static get Events(){return v}static get MetadataSchema(){return ie}static get ErrorTypes(){return et}static get ErrorDetails(){return P}static get DefaultConfig(){return He.defaultConfig?He.defaultConfig:R_}static set DefaultConfig(t){He.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 Sa,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=Ry(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=P_(He.DefaultConfig,t,e);this.userConfig=t,i.progressive&&w_(i,e);const{abrController:s,bufferController:n,capLevelController:r,errorController:o,fpsController:h}=i,l=new o(this),c=this.abrController=new s(this),u=new gv(this),d=i.interstitialsController,f=d?this.interstitialsController=new d(this,He):null,m=this.bufferController=new n(this,u),p=this.capLevelController=new r(this),g=new h(this),E=new Y_(this),A=i.contentSteeringController,y=A?new A(this):null,T=this.levelController=new H_(this,y),_=new N_(this),C=new z_(this.config),S=this.streamController=new V_(this,u,C),I=this.gapController=new F_(this,u);p.setStreamController(S),g.setStreamController(S);const L=[E,T,S];f&&L.splice(1,0,f),y&&L.splice(1,0,y),this.networkControllers=L;const b=[c,m,I,p,g,_,u];this.audioTrackController=this.createController(i.audioTrackController,L);const w=i.audioStreamController;w&&L.push(this.audioStreamController=new w(this,u,C)),this.subtitleTrackController=this.createController(i.subtitleTrackController,L);const O=i.subtitleStreamController;O&&L.push(this.subtititleStreamController=new O(this,u,C)),this.createController(i.timelineController,b),C.emeController=this.emeController=this.createController(i.emeController,b),this.cmcdController=this.createController(i.cmcdController,b),this.latencyController=this.createController(G_,b),this.coreComponents=b,L.push(l);const H=l.onErrorOut;typeof H=="function"&&this.on(v.ERROR,H,l),this.on(v.MANIFEST_LOADED,E.onManifestLoaded,E)}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===v.ERROR;this.trigger(v.ERROR,{type:et.OTHER_ERROR,details:P.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(v.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(v.ERROR,{type:et.OTHER_ERROR,details:P.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(v.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(v.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=ma.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(v.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=GT()),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){iv(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=fc(e);return dc(t,i,navigator.mediaCapabilities)}}He.defaultConfig=void 0;const X_=Object.freeze(Object.defineProperty({__proto__:null,AbrController:mc,AttrList:Mt,AudioStreamController:Qc,AudioTrackController:Zc,BasePlaylistController:Mn,BaseSegment:pa,BaseStreamController:Pn,BufferController:eu,CMCDController:ou,CapLevelController:Bn,ChunkMetadata:Dn,ContentSteeringController:lu,Cues:bu,DateRange:va,EMEController:mi,ErrorActionFlags:de,ErrorController:Ec,ErrorDetails:P,ErrorTypes:et,Events:v,FPSController:cu,FetchLoader:Jr,Fragment:en,Hls:He,HlsSkip:ds,HlsUrlParameters:Ur,KeySystemFormats:Qt,KeySystems:_t,Level:Ui,LevelDetails:Ac,LevelKey:Ni,LoadStats:Ln,M3U8Parser:_e,MetadataSchema:ie,NetworkErrorAction:Xt,Part:qh,PlaylistLevelType:Z,SubtitleStreamController:pu,SubtitleTrackController:fu,TimelineController:xu,XhrLoader:Ma,default:He,fetchSupported:Iu,getMediaSource:Ve,isMSESupported:Ba,isSupported:Ru,requestMediaKeySystemAccess:_a},Symbol.toStringTag,{value:"Module"})),j_=((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 Tr=null;async function W_(...a){var t;(t=Tr)!==null&&t!==void 0||(Tr=await qg(()=>Promise.resolve().then(()=>X_),void 0));const e=Tr.default;return e.isSupported()?new e(...a):null}function Du(a,{unsuspend:t="loadedmetadata",start:e=!0,hls:i={},crossOrigin:s="anonymous",muted:n=!0,loop:r=!0,playsInline:o=!0,onVideoFrame:h,...l}={}){const c=Q(m=>m.gl),u=x.useRef(null),d=Ki(()=>new Promise(async m=>{let p,g;typeof a=="string"?p=a:g=a;const E=Object.assign(document.createElement("video"),{src:p,srcObject:g,crossOrigin:s,loop:r,muted:n,playsInline:o,...l});if(p&&j_&&p.endsWith(".m3u8")){const y=u.current=await W_(i);y&&(y.on(v.MEDIA_ATTACHED,()=>void y.loadSource(p)),y.attachMedia(E))}const A=new Ed(E);A.colorSpace=c.outputColorSpace,E.addEventListener(t,()=>m(A))}),[a]),f=d.source.data;return J_(f,h),x.useEffect(()=>(e&&d.image.play(),()=>{u.current&&(u.current.destroy(),u.current=null)}),[d,e]),d}const On=x.forwardRef(({children:a,src:t,...e},i)=>{const s=Du(t,e);return x.useEffect(()=>()=>void s.dispose(),[s]),x.useImperativeHandle(i,()=>s,[s]),x.createElement(x.Fragment,null,a==null?void 0:a(s))}),J_=(a,t)=>{x.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 Pu={exports:{}};(function(a,t){(function(e,i){a.exports=i()})(Qg,function(){var e=function(){function i(f){return r.appendChild(f.dom),f}function s(f){for(var m=0;m<r.children.length;m++)r.children[m].style.display=m===f?"block":"none";n=f}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(f){f.preventDefault(),s(++n%r.children.length)},!1);var o=(performance||Date).now(),h=o,l=0,c=i(new e.Panel("FPS","#0ff","#002")),u=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(){l++;var f=(performance||Date).now();if(u.update(f-o,200),f>h+1e3&&(c.update(1e3*l/(f-h),100),h=f,l=0,d)){var m=performance.memory;d.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return f},update:function(){o=this.end()},domElement:r,setMode:s}};return e.Panel=function(i,s,n){var r=1/0,o=0,h=Math.round,l=h(window.devicePixelRatio||1),c=80*l,u=48*l,d=3*l,f=2*l,m=3*l,p=15*l,g=74*l,E=30*l,A=document.createElement("canvas");A.width=c,A.height=u,A.style.cssText="width:80px;height:48px";var y=A.getContext("2d");return y.font="bold "+9*l+"px Helvetica,Arial,sans-serif",y.textBaseline="top",y.fillStyle=n,y.fillRect(0,0,c,u),y.fillStyle=s,y.fillText(i,d,f),y.fillRect(m,p,g,E),y.fillStyle=n,y.globalAlpha=.9,y.fillRect(m,p,g,E),{dom:A,update:function(T,_){r=Math.min(r,T),o=Math.max(o,T),y.fillStyle=n,y.globalAlpha=1,y.fillRect(0,0,c,p),y.fillStyle=s,y.fillText(h(T)+" "+i+" ("+h(r)+"-"+h(o)+")",d,f),y.drawImage(A,m+l,p,g-l,E,m,p,g-l,E),y.fillRect(m+g-l,p,l,E),y.fillStyle=n,y.globalAlpha=.9,y.fillRect(m+g-l,p,l,h((1-T/_)*E))}}},e})})(Pu);var Q_=Pu.exports;const q_=Jg(Q_);function Z_(a,t=[],e){const[i,s]=x.useState();return x.useLayoutEffect(()=>{const n=a();return s(n),()=>void 0},t),i}function tS({showPanel:a=0,className:t,parent:e}){const i=Z_(()=>new q_,[]);return x.useEffect(()=>{if(i){const s=e&&e.current||document.body;i.showPanel(a),s==null||s.appendChild(i.dom);const n=(t??"").split(" ").filter(h=>h);n.length&&i.dom.classList.add(...n);const r=Ah(()=>i.begin()),o=Th(()=>i.end());return()=>{n.length&&i.dom.classList.remove(...n),s==null||s.removeChild(i.dom),r(),o()}}},[e,i,t,a]),null}class eS{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 h=this.GRAPH_HEIGHT-(1-e/s)*this.GRAPH_HEIGHT;h>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-h,this.PR,h))}}const wu=class wi{constructor({trackGPU:t=!1,logsPerSecond:e=30,samplesLog:i=60,samplesGraph:s=10,precision:n=2,minimal:r=!1,horizontal:o=!0,mode:h=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=l=>{l.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=h,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 wi.Panel("FPS","#0ff","#002"),0),this.msPanel=this.addPanel(new wi.Panel("CPU","#0f0","#020"),1),this.setupEventListeners()}initializeDOM(){this.dom.style.cssText=`
48
+ position: fixed;
49
+ top: 0;
50
+ left: 0;
51
+ opacity: 0.9;
52
+ z-index: 10000;
53
+ ${this.minimal?"cursor: pointer;":""}
54
+ `}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 wi.Panel("GPU","#ff0","#220"),2),this.gpuPanelCompute=this.addPanel(new wi.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 wi.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 h=0;h<e.logs.length;h++)s+=e.logs[h],e.logs[h]>n&&(n=e.logs[h]);let r=0,o=.01;for(let h=0;h<e.graph.length;h++)r+=e.graph[h],e.graph[h]>o&&(o=e.graph[h]);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}};wu.Panel=eS;let iS=wu;const sS=x.forwardRef(function({className:t,parent:e,id:i,clearStatsGlStyle:s,...n},r){const o=Q(l=>l.gl),h=x.useMemo(()=>{const l=new iS({...n});return l.init(o),l},[o]);return x.useImperativeHandle(r,()=>h.domElement,[h]),x.useEffect(()=>{if(h){const l=e&&e.current||document.body;l==null||l.appendChild(h.domElement),h.domElement.querySelectorAll("canvas").forEach(d=>{d.style.removeProperty("position")}),i&&(h.domElement.id=i),s&&h.domElement.removeAttribute("style"),h.domElement.removeAttribute("style");const c=(t??"").split(" ").filter(d=>d);c.length&&h.domElement.classList.add(...c);const u=Th(()=>h.update());return()=>{c.length&&h.domElement.classList.remove(...c),l==null||l.removeChild(h.domElement),u()}}},[e,h,t,i,s]),null});function nS({size:a=256,frames:t=1/0}={}){const e=Q(c=>c.viewport.dpr),{width:i,height:s}=Q(c=>c.size),n=a||i*e,r=a||s*e,o=x.useMemo(()=>{const c=new yd(n,r);return c.format=vd,c.type=Ad,{depthTexture:c}},[n,r]);let h=0;const l=_h(n,r,o);return Ut(c=>{(t===1/0||h<t)&&(c.gl.setRenderTarget(l),c.gl.render(c.scene,c.camera),c.gl.setRenderTarget(null),h++)}),l.depthTexture}function rS(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 aS(a,t){const e=Q(s=>s.pointer),[i]=x.useState(()=>{const s=new xn;return t&&Sh(s,t),function(n,r){s.setFromCamera(e,a instanceof Td?a:a.current);const o=this.constructor.prototype.raycast.bind(this);o&&o(s,r)}});return i}function _r(a,t,e,i){return new(e||(e=Promise))(function(s,n){function r(l){try{h(i.next(l))}catch(c){n(c)}}function o(l){try{h(i.throw(l))}catch(c){n(c)}}function h(l){var c;l.done?s(l.value):(c=l.value,c instanceof e?c:new e(function(u){u(c)})).then(r,o)}h((i=i.apply(a,[])).next())})}const oS=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function nh(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 Mu=typeof window>"u",Le=(()=>{if(Mu)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 lS(a,t,e){if(!e)return[t];const i=function(l){const c=`
55
+ precision highp float;
56
+ attribute vec3 aPosition;
57
+ varying float vvv;
58
+ void main() {
59
+ vvv = 0.31622776601683794;
60
+ gl_Position = vec4(aPosition, 1.0);
61
+ }
62
+ `,u=`
63
+ precision highp float;
64
+ varying float vvv;
65
+ void main() {
66
+ vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv;
67
+ enc = fract(enc);
68
+ enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
69
+ gl_FragColor = enc;
70
+ }
71
+ `,d=l.createShader(35633),f=l.createShader(35632),m=l.createProgram();if(!(f&&d&&m))return;l.shaderSource(d,c),l.shaderSource(f,u),l.compileShader(d),l.compileShader(f),l.attachShader(m,d),l.attachShader(m,f),l.linkProgram(m),l.detachShader(m,d),l.detachShader(m,f),l.deleteShader(d),l.deleteShader(f),l.useProgram(m);const p=l.createBuffer();l.bindBuffer(34962,p),l.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const g=l.getAttribLocation(m,"aPosition");l.vertexAttribPointer(g,3,5126,!1,0,0),l.enableVertexAttribArray(g),l.clearColor(1,1,1,1),l.clear(16384),l.viewport(0,0,1,1),l.drawArrays(4,0,3);const E=new Uint8Array(4);return l.readPixels(0,0,1,1,6408,5121,E),l.deleteProgram(m),l.deleteBuffer(p),E.join("")}(a),s="801621810",n="8016218135",r="80162181161",o=Le!=null&&Le.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 h;return i==="80162181255"?h=o.filter(([,,l])=>l>=14):(h=o.filter(([,l])=>l===i),h.length||(h=o)),h.map(([l])=>`apple ${l} gpu`)}class rh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}const Sr=[],ah=[];function hS(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,h,l=0,c=0,u=0;for(;c<i;)ah[c]=a.charCodeAt(r+c),Sr[c]=++c;for(;u<s;)for(n=t.charCodeAt(r+u),o=u++,l=u,c=0;c<i;c++)h=n===ah[c]?o:o+1,o=Sr[c],l=Sr[c]=o>l?h>l?l+1:h:h>o?o+1:h;return l}function cS(a){return a!=null}const uS=({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"}={})=>_r(void 0,void 0,void 0,function*(){const r={};if(Mu)return{tier:0,type:"SSR"};const{isIpad:o=!!(Le!=null&&Le.isIpad),isMobile:h=!!(Le!=null&&Le.isMobile),screenSize:l=window.screen,loadBenchmarks:c=_=>_r(void 0,void 0,void 0,function*(){const C=yield fetch(`${n}/${_}`).then(S=>S.json());if(parseInt(C.shift().split(".")[0],10)<4)throw new rh("Detect GPU benchmark data is out of date. Please update to version 4x");return C})}=e;let{renderer:u}=e;const d=(_,C,S,I,L)=>({device:L,fps:I,gpu:S,isMobile:h,tier:_,type:C});let f,m="";if(u)u=nh(u),f=[u];else{const _=i||function(S,I=!1){const L={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:I,powerPreference:"high-performance",stencil:!1};S&&delete L.powerPreference;const b=window.document.createElement("canvas"),w=b.getContext("webgl",L)||b.getContext("experimental-webgl",L);return w??void 0}(Le==null?void 0:Le.isSafari12,s);if(!_)return d(0,"WEBGL_UNSUPPORTED");const C=Le!=null&&Le.isFirefox?null:_.getExtension("WEBGL_debug_renderer_info");if(u=C?_.getParameter(C.UNMASKED_RENDERER_WEBGL):_.getParameter(_.RENDERER),!u)return d(1,"FALLBACK");m=u,u=nh(u),f=function(S,I,L){return I==="apple gpu"?lS(S,I,L):[I]}(_,u,h)}const p=(yield Promise.all(f.map(function(_){var C;return _r(this,void 0,void 0,function*(){const S=(X=>{const R=h?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const tt of R)if(X.includes(tt))return tt})(_);if(!S)return;const I=`${h?"m":"d"}-${S}${o?"-ipad":""}.json`,L=r[I]=(C=r[I])!==null&&C!==void 0?C:c(I);let b;try{b=yield L}catch(X){if(X instanceof rh)throw X;return}const w=function(X){var R;const tt=(X=X.replace(/\([^)]+\)/,"")).match(/\d+/)||X.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:""}(_);let O=b.filter(([,X])=>X===w);O.length||(O=b.filter(([X])=>X.includes(_)));const H=O.length;if(H===0)return;const Y=_.split(/[.,()\[\]/\s]/g).sort().filter((X,R,tt)=>R===0||X!==tt[R-1]).join(" ");let $,[z,,,,W]=H>1?O.map(X=>[X,hS(Y,X[2])]).sort(([,X],[,R])=>X-R)[0][0]:O[0],J=Number.MAX_VALUE;const{devicePixelRatio:G}=window,U=l.width*G*l.height*G;for(const X of W){const[R,tt]=X,it=R*tt,lt=Math.abs(U-it);lt<J&&(J=lt,$=X)}if(!$)return;const[,,K,V]=$;return[J,K,z,V]})}))).filter(cS).sort(([_=Number.MAX_VALUE,C],[S=Number.MAX_VALUE,I])=>_===S?C-I:_-S);if(!p.length){const _=oS.find(C=>u.includes(C));return _?d(0,"BLOCKLISTED",_):d(1,"FALLBACK",`${u} (${m})`)}const[,g,E,A]=p[0];if(g===-1)return d(0,"BLOCKLISTED",E,g,A);const y=h?a:t;let T=0;for(let _=0;_<y.length;_++)g>=y[_]&&(T=_);return d(T,"BENCHMARK",E,g,A)}),Bu=a=>Ki(()=>uS(a),["useDetectGPU"]);function dS({children:a,...t}){const e=Bu(t);return x.createElement(x.Fragment,null,a==null?void 0:a(e))}function fS(...a){const t=x.useRef([]);return t.current=a.map(e=>x.useContext(e)),x.useMemo(()=>({children:e})=>a.reduceRight((i,s,n)=>x.createElement(s.Provider,{value:t.current[n],children:i}),e),[])}function mS(a,t){const e=x.useRef(null),[i]=x.useState(()=>t?t instanceof qt?{current:t}:t:e),[s]=x.useState(()=>new _d(void 0));x.useLayoutEffect(()=>{t&&(i.current=t instanceof qt?t:t.current),s._root=i.current});const n=x.useRef({}),r=x.useMemo(()=>{const o={};return a.forEach(h=>Object.defineProperty(o,h.name,{enumerable:!0,get(){if(i.current)return n.current[h.name]||(n.current[h.name]=s.clipAction(h,i.current))},configurable:!0})),{ref:i,clips:a,actions:o,names:a.map(h=>h.name),mixer:s}},[a]);return Ut((o,h)=>s.update(h)),x.useEffect(()=>{const o=i.current;return()=>{n.current={},s.stopAllAction(),Object.values(r.actions).forEach(h=>{o&&s.uncacheAction(h,o)})}},[a]),r}const pS=`
72
+ #if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )
73
+ vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );
74
+ #ifdef BOX_PROJECTED_ENV_MAP
75
+ vWorldPosition = worldPosition.xyz;
76
+ #endif
77
+ #endif
78
+ `,gS=`
79
+ #ifdef BOX_PROJECTED_ENV_MAP
80
+ uniform vec3 envMapSize;
81
+ uniform vec3 envMapPosition;
82
+ varying vec3 vWorldPosition;
83
+
84
+ vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) {
85
+ vec3 nDir = normalize( v );
86
+ vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir;
87
+ vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir;
88
+ vec3 rbminmax;
89
+ rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x;
90
+ rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y;
91
+ rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z;
92
+ float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z );
93
+ vec3 boxIntersection = vWorldPosition + nDir * correction;
94
+ return boxIntersection - cubePos;
95
+ }
96
+ #endif
97
+ `,ES=`
98
+ #ifdef BOX_PROJECTED_ENV_MAP
99
+ worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition );
100
+ #endif
101
+ `,yS=`
102
+ #ifdef BOX_PROJECTED_ENV_MAP
103
+ reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition );
104
+ #endif
105
+ `;function vS(a,t,e){a.defines.BOX_PROJECTED_ENV_MAP=!0,a.uniforms.envMapPosition={value:t},a.uniforms.envMapSize={value:e},a.vertexShader=`
106
+ varying vec3 vWorldPosition;
107
+ ${a.vertexShader.replace("#include <worldpos_vertex>",pS)}`,a.fragmentShader=`
108
+ ${gS}
109
+ ${a.fragmentShader.replace("#include <envmap_physical_pars_fragment>",Sd.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );",`vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
110
+ ${ES}
111
+ `).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );",`reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
112
+ ${yS}
113
+ `)}`}function AS(a=new k,t=new k){const[e]=x.useState(()=>({position:new k,size:new k}));Sh(e,{position:a,size:t});const i=x.useRef(null),s=x.useMemo(()=>({ref:i,onBeforeCompile:n=>vS(n,e.position,e.size),customProgramCacheKey:()=>JSON.stringify(e.position.toArray())+JSON.stringify(e.size.toArray())}),[...e.position.toArray(),...e.size.toArray()]);return x.useLayoutEffect(()=>void(i.current.needsUpdate=!0),[e]),s}function TS(a,t,e=.9){return t*e+a*(1-e)}const _S=a=>Math.sqrt(1-Math.pow(a-1,2));class SS{constructor({size:t=256,maxAge:e=750,radius:i=.3,intensity:s=.2,interpolate:n=0,smoothing:r=0,minForce:o=.3,blend:h="screen",ease:l=_S}={}){this.size=t,this.maxAge=e,this.radius=i,this.intensity=s,this.ease=l,this.interpolate=n,this.smoothing=r,this.minForce=o,this.blend=h,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 Lr(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=TS(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 h=1;h<o;h++)this.trail.push({x:e.x-i/o*h,y:e.y-s/o*h,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 Ou(a={}){const{size:t,maxAge:e,radius:i,intensity:s,interpolate:n,smoothing:r,minForce:o,blend:h,ease:l}=a,c=x.useMemo(()=>new SS(a),[t,e,i,s,n,r,o,h,l]);Ut((d,f)=>void c.update(f));const u=x.useCallback(d=>c.addTouch(d.uv),[c]);return[c.texture,u]}const xS=({children:a,...t})=>{const e=Ou(t);return x.createElement(x.Fragment,null,a==null?void 0:a(e))},CS=x.forwardRef(({font:a,color:t="#cbcbcb",bevelSize:e=.04,debug:i=!1,children:s,...n},r)=>{const[o,h]=x.useState(0),l=x.useCallback((d=1)=>h(o+d),[o]),c=x.useCallback((d=1)=>h(o-d),[o]),u=x.useMemo(()=>({incr:l,decr:c}),[l,c]);return x.useImperativeHandle(r,()=>u,[u]),x.createElement("group",n,x.createElement(x.Suspense,{fallback:null},x.createElement(xh,{top:!0,cacheKey:JSON.stringify({counter:o,font:a})},x.createElement(Ch,{bevelEnabled:!0,bevelSize:e,font:a},i?x.createElement("meshNormalMaterial",{wireframe:!0}):x.createElement("meshStandardMaterial",{color:t}),o))),s)});function bS(a){const t=x.useRef(null);return x.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}}}),x.createElement("group",wt({ref:t},a))}function IS(a){switch(a){case 64:return"-64px";case 128:return"-128px";case 256:return"-256px";case 512:return"-512px";default:return""}}const LS="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json",RS="https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d";function Fu(a=0,t=1024,e){const i=Ki(()=>fetch(LS).then(c=>c.json()),["matcapList"]),s=i[0],n=x.useMemo(()=>Object.keys(i).length,[]),o=`${x.useMemo(()=>typeof a=="string"?a:typeof a=="number"?i[a]:null,[a])||s}${IS(t)}.png`,h=`${RS}/${t}/${o}`;return[ra(h,e),h,n]}const DS=({children:a,id:t,format:e,onLoad:i})=>{const s=Fu(t,e,i);return x.createElement(x.Fragment,null,a==null?void 0:a(s))},PS="https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb",wS="https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json";function ku(a=0,t={},e){const{repeat:i=[1,1],anisotropy:s=1,offset:n=[0,0]}=t,r=Ki(()=>fetch(wS).then(d=>d.json()),["normalsList"]),o=x.useMemo(()=>Object.keys(r).length,[]),h=r[0],l=r[a]||h,c=`${PS}/normals/${l}`,u=ra(c,e);return x.useLayoutEffect(()=>{u&&(u.wrapS=u.wrapT=Ir,u.repeat=new Kt(i[0],i[1]),u.offset=new Kt(n[0],n[1]),u.anisotropy=s)},[u,s,i,n]),[u,c,o]}const MS=({children:a,id:t,onLoad:e,...i})=>{const s=ku(t,i,e);return x.createElement(x.Fragment,null,a==null?void 0:a(s))},Ze={uniforms:{strokeOpacity:1,fillOpacity:.25,fillMix:0,thickness:.05,colorBackfaces:!1,dashInvert:!0,dash:!1,dashRepeats:4,dashLength:.5,squeeze:!1,squeezeMin:.2,squeezeMax:1,stroke:new kt("#ff0000"),backfaceStroke:new kt("#0000ff"),fill:new kt("#00ff00")},vertex:`
114
+ attribute vec3 barycentric;
115
+
116
+ varying vec3 v_edges_Barycentric;
117
+ varying vec3 v_edges_Position;
118
+
119
+ void initWireframe() {
120
+ v_edges_Barycentric = barycentric;
121
+ v_edges_Position = position.xyz;
122
+ }
123
+ `,fragment:`
124
+ #ifndef PI
125
+ #define PI 3.1415926535897932384626433832795
126
+ #endif
127
+
128
+ varying vec3 v_edges_Barycentric;
129
+ varying vec3 v_edges_Position;
130
+
131
+ uniform float strokeOpacity;
132
+ uniform float fillOpacity;
133
+ uniform float fillMix;
134
+ uniform float thickness;
135
+ uniform bool colorBackfaces;
136
+
137
+ // Dash
138
+ uniform bool dashInvert;
139
+ uniform bool dash;
140
+ uniform bool dashOnly;
141
+ uniform float dashRepeats;
142
+ uniform float dashLength;
143
+
144
+ // Squeeze
145
+ uniform bool squeeze;
146
+ uniform float squeezeMin;
147
+ uniform float squeezeMax;
148
+
149
+ // Colors
150
+ uniform vec3 stroke;
151
+ uniform vec3 backfaceStroke;
152
+ uniform vec3 fill;
153
+
154
+ // This is like
155
+ float wireframe_aastep(float threshold, float dist) {
156
+ float afwidth = fwidth(dist) * 0.5;
157
+ return smoothstep(threshold - afwidth, threshold + afwidth, dist);
158
+ }
159
+
160
+ float wireframe_map(float value, float min1, float max1, float min2, float max2) {
161
+ return min2 + (value - min1) * (max2 - min2) / (max1 - min1);
162
+ }
163
+
164
+ float getWireframe() {
165
+ vec3 barycentric = v_edges_Barycentric;
166
+
167
+ // Distance from center of each triangle to its edges.
168
+ float d = min(min(barycentric.x, barycentric.y), barycentric.z);
169
+
170
+ // for dashed rendering, we can use this to get the 0 .. 1 value of the line length
171
+ float positionAlong = max(barycentric.x, barycentric.y);
172
+ if (barycentric.y < barycentric.x && barycentric.y < barycentric.z) {
173
+ positionAlong = 1.0 - positionAlong;
174
+ }
175
+
176
+ // the thickness of the stroke
177
+ float computedThickness = wireframe_map(thickness, 0.0, 1.0, 0.0, 0.34);
178
+
179
+ // if we want to shrink the thickness toward the center of the line segment
180
+ if (squeeze) {
181
+ computedThickness *= mix(squeezeMin, squeezeMax, (1.0 - sin(positionAlong * PI)));
182
+ }
183
+
184
+ // Create dash pattern
185
+ if (dash) {
186
+ // here we offset the stroke position depending on whether it
187
+ // should overlap or not
188
+ float offset = 1.0 / dashRepeats * dashLength / 2.0;
189
+ if (!dashInvert) {
190
+ offset += 1.0 / dashRepeats / 2.0;
191
+ }
192
+
193
+ // if we should animate the dash or not
194
+ // if (dashAnimate) {
195
+ // offset += time * 0.22;
196
+ // }
197
+
198
+ // create the repeating dash pattern
199
+ float pattern = fract((positionAlong + offset) * dashRepeats);
200
+ computedThickness *= 1.0 - wireframe_aastep(dashLength, pattern);
201
+ }
202
+
203
+ // compute the anti-aliased stroke edge
204
+ float edge = 1.0 - wireframe_aastep(computedThickness, d);
205
+
206
+ return edge;
207
+ }
208
+ `},BS=bh(Ze.uniforms,Ze.vertex+`
209
+ void main() {
210
+ initWireframe();
211
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
212
+ }
213
+ `,Ze.fragment+`
214
+ void main () {
215
+ // Compute color
216
+
217
+ float edge = getWireframe();
218
+ vec4 colorStroke = vec4(stroke, edge);
219
+
220
+ #ifdef FLIP_SIDED
221
+ colorStroke.rgb = backfaceStroke;
222
+ #endif
223
+
224
+ vec4 colorFill = vec4(fill, fillOpacity);
225
+ vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
226
+
227
+ gl_FragColor = outColor;
228
+ }
229
+ `);function OS(a,t){a.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...t},e.vertexShader=e.vertexShader.replace("void main() {",`
230
+ ${Ze.vertex}
231
+ void main() {
232
+ initWireframe();
233
+ `),e.fragmentShader=e.fragmentShader.replace("void main() {",`
234
+ ${Ze.fragment}
235
+ void main() {
236
+ `),e.fragmentShader=e.fragmentShader.replace("#include <color_fragment>",`
237
+ #include <color_fragment>
238
+ float edge = getWireframe();
239
+ vec4 colorStroke = vec4(stroke, edge);
240
+ #ifdef FLIP_SIDED
241
+ colorStroke.rgb = backfaceStroke;
242
+ #endif
243
+ vec4 colorFill = vec4(mix(diffuseColor.rgb, fill, fillMix), mix(diffuseColor.a, fillOpacity, fillMix));
244
+ vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity);
245
+
246
+ diffuseColor.rgb = outColor.rgb;
247
+ diffuseColor.a *= outColor.a;
248
+ `)},a.side=_s,a.transparent=!0}function FS(a,t){x.useEffect(()=>{var e;return void(a.fillOpacity.value=(e=t.fillOpacity)!==null&&e!==void 0?e:a.fillOpacity.value)},[t.fillOpacity]),x.useEffect(()=>{var e;return void(a.fillMix.value=(e=t.fillMix)!==null&&e!==void 0?e:a.fillMix.value)},[t.fillMix]),x.useEffect(()=>{var e;return void(a.strokeOpacity.value=(e=t.strokeOpacity)!==null&&e!==void 0?e:a.strokeOpacity.value)},[t.strokeOpacity]),x.useEffect(()=>{var e;return void(a.thickness.value=(e=t.thickness)!==null&&e!==void 0?e:a.thickness.value)},[t.thickness]),x.useEffect(()=>void(a.colorBackfaces.value=!!t.colorBackfaces),[t.colorBackfaces]),x.useEffect(()=>void(a.dash.value=!!t.dash),[t.dash]),x.useEffect(()=>void(a.dashInvert.value=!!t.dashInvert),[t.dashInvert]),x.useEffect(()=>{var e;return void(a.dashRepeats.value=(e=t.dashRepeats)!==null&&e!==void 0?e:a.dashRepeats.value)},[t.dashRepeats]),x.useEffect(()=>{var e;return void(a.dashLength.value=(e=t.dashLength)!==null&&e!==void 0?e:a.dashLength.value)},[t.dashLength]),x.useEffect(()=>void(a.squeeze.value=!!t.squeeze),[t.squeeze]),x.useEffect(()=>{var e;return void(a.squeezeMin.value=(e=t.squeezeMin)!==null&&e!==void 0?e:a.squeezeMin.value)},[t.squeezeMin]),x.useEffect(()=>{var e;return void(a.squeezeMax.value=(e=t.squeezeMax)!==null&&e!==void 0?e:a.squeezeMax.value)},[t.squeezeMax]),x.useEffect(()=>void(a.stroke.value=t.stroke?new kt(t.stroke):a.stroke.value),[t.stroke]),x.useEffect(()=>void(a.fill.value=t.fill?new kt(t.fill):a.fill.value),[t.fill]),x.useEffect(()=>void(a.backfaceStroke.value=t.backfaceStroke?new kt(t.backfaceStroke):a.backfaceStroke.value),[t.backfaceStroke])}function kS(a){return!!(a!=null&&a.geometry)}function US(a){return!!(a!=null&&a.isBufferGeometry)}function NS(a){return!!(a!=null&&a.current)}function oh(a){return(a==null?void 0:a.current)!==void 0}function lh(a){return a.type==="WireframeGeometry"}function GS(){const a={};for(const t in Ze.uniforms)a[t]={value:Ze.uniforms[t]};return a}function HS(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 xd(Float32Array.from(s),3)}function Uu(a){const t=NS(a)?a.current:a;if(US(t))return t;{if(lh(t))throw new Error("Wireframe: WireframeGeometry is not supported.");const e=t.parent;if(kS(e)){if(lh(e.geometry))throw new Error("Wireframe: WireframeGeometry is not supported.");return e.geometry}}}function Nu(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=HS(a,t);a.setAttribute("barycentric",e)}function $S({geometry:a,simplify:t=!1,...e}){yh({MeshWireframeMaterial:BS});const[i,s]=x.useState(null);x.useLayoutEffect(()=>{const r=Uu(a);if(!r)throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry.");Nu(r,t),oh(a)&&s(r)},[t,a]);const n=oh(a)?i:a;return x.createElement(x.Fragment,null,n&&x.createElement("mesh",{geometry:n},x.createElement("meshWireframeMaterial",wt({attach:"material",transparent:!0,side:_s,polygonOffset:!0,polygonOffsetFactor:-4},e,{extensions:{derivatives:!0,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1}}))))}function KS({simplify:a=!1,...t}){const e=x.useRef(null),i=x.useMemo(()=>GS(),[Ze.uniforms]);return FS(i,t),x.useLayoutEffect(()=>{const s=Uu(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 Nu(s,a),()=>{s.copy(n),n.dispose()}},[a]),x.useLayoutEffect(()=>{const s=e.current.parent,n=s.material.clone();return OS(s.material,i),()=>{s.material.dispose(),s.material=n}},[]),x.createElement("object3D",{ref:e})}function VS({geometry:a,...t}){return a?x.createElement($S,wt({geometry:a},t)):x.createElement(KS,t)}function zS({opacity:a,alphaMap:t}){const e=x.useRef(null),i=x.useRef(null),s=x.useRef({value:1}),n=x.useRef({value:null}),r=x.useRef({value:!1});return x.useLayoutEffect(()=>{e.current.onBeforeCompile=i.current.onBeforeCompile=o=>{const h=o.fragmentShader.indexOf("void main");let l="",c,u=h;for(;c!==`
249
+ `&&u<h+100;)c=o.fragmentShader.charAt(u),l+=c,u++;l=l.trim(),o.vertexShader=o.vertexShader.replace("void main() {",`
250
+ varying vec2 custom_vUv;
251
+
252
+ void main() {
253
+ custom_vUv = uv;
254
+
255
+ `),o.fragmentShader=o.fragmentShader.replace(l,`
256
+ uniform float uShadowOpacity;
257
+ uniform sampler2D uAlphaMap;
258
+ uniform bool uHasAlphaMap;
259
+
260
+ varying vec2 custom_vUv;
261
+
262
+ float bayerDither2x2( vec2 v ) {
263
+ return mod( 3.0 * v.y + 2.0 * v.x, 4.0 );
264
+ }
265
+
266
+ float bayerDither4x4( vec2 v ) {
267
+ vec2 P1 = mod( v, 2.0 );
268
+ vec2 P2 = mod( floor( 0.5 * v ), 2.0 );
269
+ return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );
270
+ }
271
+
272
+ void main() {
273
+ float alpha =
274
+ uHasAlphaMap ?
275
+ uShadowOpacity * texture2D(uAlphaMap, custom_vUv).x
276
+ : uShadowOpacity;
277
+
278
+ if( ( bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ) ) / 16.0 >= alpha ) discard;
279
+
280
+ `),o.uniforms.uShadowOpacity=s.current,o.uniforms.uAlphaMap=n.current,o.uniforms.uHasAlphaMap=r.current}},[]),Ut(()=>{var o;const h=(o=e.current.__r3f)==null||(o=o.parent)==null?void 0:o.object;if(h){const l=h.material;l&&(s.current.value=a??l.opacity,t===!1?(n.current.value=null,r.current.value=!1):(n.current.value=t||l.alphaMap,r.current.value=!!n.current.value))}}),x.createElement(x.Fragment,null,x.createElement("meshDepthMaterial",{ref:e,attach:"customDepthMaterial",depthPacking:Cd}),x.createElement("meshDistanceMaterial",{ref:i,attach:"customDistanceMaterial"}))}const hh=new mt,ch=new bd,xr=new ea,Cr=new k;function YS(a,t){const e=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(e.boundingSphere===null&&e.computeBoundingSphere(),xr.copy(e.boundingSphere),xr.applyMatrix4(s),a.ray.intersectsSphere(xr)!==!1&&(hh.copy(s).invert(),ch.copy(a.ray).applyMatrix4(hh),!(e.boundingBox!==null&&ch.intersectBox(e.boundingBox,Cr)===null)&&t.push({distance:Cr.distanceTo(a.ray.origin),point:Cr.clone(),object:this})))}const XS=x.forwardRef(({options:a={video:!0},...t},e)=>{const i=Ki(()=>navigator.mediaDevices.getDisplayMedia(a),[]);return x.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),Ih([])},[i]),x.createElement(On,wt({ref:e},t,{src:i}))}),Gu=x.forwardRef(({constraints:a={audio:!1,video:{facingMode:"user"}},...t},e)=>{const i=Ki(()=>navigator.mediaDevices.getUserMedia(a),[]);return x.useEffect(()=>()=>{i==null||i.getTracks().forEach(s=>s.stop()),Ih([])},[i]),x.createElement(On,wt({ref:e},t,{src:i}))});function uh(a,t){return a.clone().add(t).multiplyScalar(.5)}function Di(a,t,e){const i=a.localToWorld(t);return e.worldToLocal(i)}const Hu=x.createContext({}),jS=x.forwardRef(({camera:a,videoTexture:t={start:!0},manualDetect:e=!1,faceLandmarkerResult:i,manualUpdate:s=!1,makeDefault:n,smoothTime:r=.25,offset:o=!0,offsetScalar:h=80,eyes:l=!1,eyesAsOrigin:c=!0,depth:u=.15,debug:d=!1,facemesh:f},m)=>{var p,g;const E=Q(it=>it.scene),A=Q(it=>it.camera),y=Q(it=>it.set),T=Q(it=>it.get),_=a||A,C=x.useRef(null),[S]=x.useState(()=>new qt),[I]=x.useState(()=>new k),[L]=x.useState(()=>new k),[b]=x.useState(()=>new k),[w]=x.useState(()=>new k),O=x.useCallback(()=>{S.parent=_.parent;const it=C.current;if(it){const{outerRef:lt,eyeRightRef:It,eyeLeftRef:Wt}=it;if(It.current&&Wt.current){const{irisDirRef:Xe}=It.current,{irisDirRef:Vi}=Wt.current;Xe.current&&Vi.current&&lt.current&&(I.copy(Di(Xe.current,new k(0,0,0),lt.current)),L.copy(Di(Vi.current,new k(0,0,0),lt.current)),S.position.copy(Di(lt.current,uh(I,L),_.parent||E)),b.copy(Di(Xe.current,new k(0,0,1),lt.current)),w.copy(Di(Vi.current,new k(0,0,1),lt.current)),S.lookAt(lt.current.localToWorld(uh(b,w))))}else lt.current&&(S.position.copy(Di(lt.current,new k(0,0,0),_.parent||E)),S.lookAt(lt.current.localToWorld(new k(0,0,1))))}return S},[_,L,w,I,b,E,S]),[H]=x.useState(()=>new qt),Y=x.useCallback(function(it,lt){if(_){var It;(It=lt)!==null&&It!==void 0||(lt=O()),r>0?(ti.damp3(H.position,lt.position,r,it,void 0,void 0,1e-9),ti.dampE(H.rotation,lt.rotation,r,it,void 0,void 0,1e-9)):(H.position.copy(lt.position),H.rotation.copy(lt.rotation)),_.position.copy(H.position),_.rotation.copy(H.rotation)}},[_,O,r,H.position,H.rotation]);Ut((it,lt)=>{s||Y(lt)});const $=x.useRef(null),[z,W]=x.useState(),J=Lh(),G=x.useCallback((it,lt)=>{const It=$.current;if(!It)return;const Wt=It.source.data,Xe=J==null?void 0:J.detectForVideo(Wt,it);W(Xe)},[J]),U=x.useMemo(()=>Object.assign(Object.create(Id.prototype),{computeTarget:O,update:Y,facemeshApiRef:C}),[O,Y]);x.useImperativeHandle(m,()=>U,[U]),x.useEffect(()=>{if(n){const it=T().controls;return y({controls:U}),()=>y({controls:it})}},[n,U,T,y]);const K=i??z,V=K==null?void 0:K.faceLandmarks[0],X=K==null||(p=K.facialTransformationMatrixes)==null?void 0:p[0],R=K==null||(g=K.faceBlendshapes)==null?void 0:g[0],tt={onVideoFrame:G,...t};return x.createElement(Hu.Provider,{value:U},!e&&x.createElement(x.Suspense,{fallback:null},"src"in tt?x.createElement(On,wt({ref:$},tt)):x.createElement(Gu,wt({ref:$},tt))),x.createElement(Rh,wt({ref:C,children:x.createElement("meshNormalMaterial",{side:_s})},f,{points:V,depth:u,facialTransformationMatrix:X,faceBlendshapes:R,eyes:l,eyesAsOrigin:c,offset:o,offsetScalar:h,debug:d,"rotation-z":Math.PI,visible:d})))}),WS=()=>x.useContext(Hu),Ax=Object.freeze(Object.defineProperty({__proto__:null,AccumulativeShadows:Ld,AdaptiveDpr:Rd,AdaptiveEvents:Dd,ArcballControls:oy,AsciiRenderer:Pd,BBAnchor:wd,Backdrop:Md,BakeShadows:Bd,Billboard:Od,Bounds:Fd,Box:kd,Bvh:Ud,CameraControls:my,CameraControlsImpl:tn,CameraShake:Nd,Capsule:Gd,CatmullRomLine:Hd,Caustics:$d,Center:xh,Circle:Kd,Clone:ia,Cloud:Vd,CloudInstance:zd,Clouds:Yd,ComputedAttribute:Xd,Cone:jd,ContactShadows:Wd,CubeCamera:Jd,CubeTexture:yy,CubicBezierLine:Qd,CurveModifier:qd,CycleRaycast:Zd,Cylinder:tf,Decal:ef,Detailed:sf,DetectGPU:dS,DeviceOrientationControls:sy,Dodecahedron:nf,DragControls:s0,Edges:rf,Effects:af,Environment:of,EnvironmentCube:lf,EnvironmentMap:hf,EnvironmentPortal:cf,Example:CS,Extrude:uf,FaceControls:jS,FaceLandmarker:df,FaceLandmarkerDefaults:ff,Facemesh:Rh,FacemeshDatas:mf,FacemeshEye:pf,FacemeshEyeDefaults:gf,Fbo:Ef,Fbx:vy,FirstPersonControls:cy,Fisheye:yf,Float:vf,FlyControls:ny,GizmoHelper:Af,GizmoViewcube:Tf,GizmoViewport:_f,Gltf:iy,GradientTexture:Sf,GradientType:xf,Grid:Cf,Helper:bf,Html:If,Hud:Lf,Icosahedron:Rf,Image:Df,Instance:Pf,InstancedAttribute:wf,Instances:Mf,IsObject:Rr,KeyboardControls:lE,Ktx2:Ay,Lathe:Bf,Lightformer:Of,Line:Ff,Loader:i0,MapControls:ry,MarchingCube:kf,MarchingCubes:Uf,MarchingPlane:Nf,Mask:Gf,MatcapTexture:DS,Merged:Hf,MeshDiscardMaterial:$f,MeshDistortMaterial:Kf,MeshPortalMaterial:Vf,MeshReflectorMaterial:zf,MeshRefractionMaterial:Yf,MeshTransmissionMaterial:Xf,MeshWobbleMaterial:jf,MotionPathControls:Ey,MultiMaterial:bS,NormalTexture:MS,Octahedron:Wf,OrbitControls:Jf,OrthographicCamera:Qf,Outlines:qf,PerformanceMonitor:Zf,PerspectiveCamera:tm,PivotControls:em,Plane:im,Point:sm,PointMaterial:nm,PointMaterialImpl:rm,PointerLockControls:hy,Points:am,PointsBuffer:om,Polyhedron:lm,PositionMesh:hm,PositionPoint:cm,PositionalAudio:um,Preload:dm,PresentationControls:rE,Progress:t0,QuadraticBezierLine:fm,RandomizedLight:mm,RenderCubeTexture:pm,RenderTexture:gm,Resize:Em,Ring:ym,RoundedBox:vm,Sampler:Am,ScreenQuad:Tm,ScreenSizer:ey,ScreenSpace:_m,ScreenVideoTexture:XS,Scroll:nE,ScrollControls:eE,Segment:Sm,SegmentObject:xm,Segments:Cm,Select:bm,Shadow:Im,ShadowAlpha:zS,Shape:Lm,Sky:Rm,SoftShadows:Dm,Sparkles:Pm,Sphere:wm,Splat:Mm,SpotLight:Bm,SpotLightShadow:Om,SpriteAnimator:Fm,Stage:km,Stars:Um,Stats:tS,StatsGl:sS,Svg:Nm,Tetrahedron:Gm,Text:Hm,Text3D:Ch,Texture:$m,Torus:Km,TorusKnot:Vm,TrackballControls:ay,Trail:zm,TrailTexture:xS,TransformControls:ly,Tube:Ym,VideoTexture:On,View:Xm,WebcamVideoTexture:Gu,Wireframe:VS,accumulativeContext:jm,calcPosFromAngles:Wm,calculateScaleFactor:Eh,checkIfFrameIsEmpty:Jm,createInstances:Qm,getFirstFrame:qm,isWebGL2Available:Zm,meshBounds:YS,shaderMaterial:bh,useAnimations:mS,useAspect:rS,useBVH:tp,useBounds:ep,useBoxProjectedEnv:AS,useCamera:aS,useContextBridge:fS,useCubeCamera:ip,useCubeTexture:fa,useCursor:Zg,useDepthBuffer:nS,useDetectGPU:Bu,useEnvironment:sp,useFBO:_h,useFBX:bn,useFaceControls:WS,useFaceLandmarker:Lh,useFont:np,useGLTF:Ss,useGizmoContext:rp,useHelper:ap,useIntersect:op,useKTX2:In,useKeyboardControls:hE,useMask:lp,useMatcapTexture:Fu,useMotion:Wh,useNormalTexture:ku,usePerformanceMonitor:hp,useProgress:ha,useScroll:ua,useSelect:cp,useSpriteAnimator:up,useSpriteLoader:dp,useSurfaceSampler:fp,useTexture:ra,useTrail:mp,useTrailTexture:Ou,useVideoTexture:Du},Symbol.toStringTag,{value:"Module"}));function $u(a,t,e,i){const s=Q(n=>n.camera);Ut(()=>{a.current!=null&&t(pp(s,a.current,e,i))})}function JS({children:a,direction:t,angle:e=Math.PI/2}){const i=x.useRef(null);return $u(i,s=>{i.current!=null&&(i.current.visible=s)},t,e),Ke.jsx("group",{ref:i,children:a})}function QS({children:a,direction:t,angle:e=Math.PI/2}){const i=x.useRef(null),[s,n]=x.useState(!1);return $u(i,n,t,e),s?Ke.jsx(Ke.Fragment,{children:a}):null}function qS({children:a,mode:t}){const e=aa(t);return Ke.jsx("group",{visible:e,children:a})}function ZS({children:a,mode:t}){return aa(t)?Ke.jsx(Ke.Fragment,{children:a}):null}function tx({children:a}){const t=oa();return Ke.jsx("group",{visible:t==null||t==="visible",children:a})}function ex({children:a}){const t=oa();return t!="visible"&&t!=null?null:Ke.jsx(Ke.Fragment,{children:a})}function ix(){const a=Cn();return x.useMemo(()=>la.bind(null,a),[a])}function sx(){const[a,t]=x.useState(void 0),e=x.useRef(()=>{}),i=Cn(),s=x.useCallback(async n=>{var h;(h=e.current)==null||h.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 x.useEffect(()=>()=>{var n;return void((n=e.current)==null?void 0:n.call(e))},[]),[a,s]}function nx(a,t={},e={},i="left"){const s=Cn(),n=x.useMemo(()=>gp(),[]);Ut((r,o,h)=>n(typeof a=="function"?a:a.current,s,r.camera,o,t,e,i,o,r,h))}function rx({batchEvents:a,clickThesholdMs:t,clickThresholdMs:e,contextMenuButton:i,customSort:s,dblClickThresholdMs:n,filter:r,forwardPointerCapture:o,intersectEveryFrame:h,pointerTypePrefix:l}){const c=Q(m=>m.gl.domElement),u=Q(m=>m.frameloop==="always"),d=Q(m=>m.camera),f=Q(m=>m.scene);return x.useEffect(()=>{const{destroy:m,update:p}=Ep(c,()=>d,f,{batchEvents:a??u,clickThesholdMs:t,clickThresholdMs:e,contextMenuButton:i,customSort:s,dblClickThresholdMs:n,filter:r,forwardPointerCapture:o,intersectEveryFrame:h,pointerTypePrefix:l}),g=Ah(p);return()=>{g(),m()}},[c,d,f,u,a,e,t,i,s,n,r,o,h,l]),null}const ax=()=>({enabled:!1,priority:0}),Tx=Object.freeze(Object.defineProperty({__proto__:null,ARButton:yp,CombinedPointer:vp,DefaultXRController:Ap,DefaultXRControllerGrabPointer:Tp,DefaultXRGaze:_p,DefaultXRHand:Sp,DefaultXRHandGrabPointer:xp,DefaultXRHandTouchPointer:Cp,DefaultXRInputSourceRayPointer:bp,DefaultXRInputSourceTeleportPointer:Ip,DefaultXRScreenInput:Lp,DefaultXRTransientPointer:Rp,FallbackXRLayerImplementation:Dp,IfFacingCamera:QS,IfInSessionMode:Pp,IfSessionModeSupported:ZS,IfSessionVisible:ex,Interactive:wp,NotInXR:Mp,PointerCursorModel:Bp,PointerEvents:rx,PointerRayModel:Op,RayGrab:Fp,RootCombinedPointer:kp,ShowIfFacingCamera:JS,ShowIfInSessionMode:Up,ShowIfSessionModeSupported:qS,ShowIfSessionVisible:tx,TeleportPointerRayModel:Np,TeleportTarget:Gp,UNSAFE_useXRStore:Hp,VRButton:$p,XR:Kp,XRButton:Vp,XRControllerComponent:zp,XRControllerModel:Yp,XRDomOverlay:Xp,XRHandJoint:jp,XRHandModel:Wp,XRHitTest:Jp,XRLayer:Qp,XRLayerImplementation:qp,XRMeshModel:Zp,XROrigin:tg,XRPlaneModel:eg,XRSpace:ig,createXRHitTestSource:sg,createXRStore:ng,defaultGrabPointerOpacity:rg,defaultRayPointerOpacity:ag,defaultTouchPointerOpacity:og,isAppleVisionPro:lg,isXRInputSourceState:hg,noEvents:ax,privateKeys:cg,requestXRAnchor:la,requestXRHitTest:ug,useApplyXRSpaceMatrix:dg,useGetXRSpaceMatrix:fg,useGrabPointer:mg,useHover:pg,useInitRoomCapture:gg,useInteraction:Eg,useLayerStore:yg,useLinesPointer:vg,useLoadXRControllerLayout:Ag,useLoadXRControllerModel:Tg,usePointerXRInputSourceEvents:_g,useRayPointer:Sg,useRequestXRAnchor:ix,useSessionFeatureEnabled:xg,useSessionModeSupported:Cg,useTouchPointer:bg,useXR:Ig,useXRAnchor:sx,useXRControllerButtonEvent:Lg,useXRControllerLocomotion:nx,useXRControllerState:Rg,useXREvent:Dg,useXRGazeState:Pg,useXRHandState:wg,useXRHitTest:Mg,useXRHitTestSource:Bg,useXRInputSourceEvent:Og,useXRInputSourceState:Fg,useXRInputSourceStateContext:kg,useXRInputSourceStates:Ug,useXRMeshGeometry:Ng,useXRMeshes:Gg,useXRPlaneGeometry:Hg,useXRPlanes:$g,useXRReferenceSpace:Kg,useXRRequestHitTest:Vg,useXRScreenInputState:zg,useXRSessionFeatureEnabled:Yg,useXRSessionModeSupported:aa,useXRSessionVisibilityState:oa,useXRSpace:Xg,useXRStore:Cn,useXRTransientPointerState:jg},Symbol.toStringTag,{value:"Module"}));export{Ax as D,Tx as X};
281
+ //# sourceMappingURL=chunk-BhBOHBDA.js.map