You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
NewEduCoderBuild/p__Classrooms__Lists__Learn...

42 lines
768 KiB

!(function(){var fl=Math.pow;(self.webpackChunk=self.webpackChunk||[]).push([[4928],{65030:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return Oi}});var b=$(27247),de=$(11913),Be=$(43079),Z=$(43403),A=$(92310),g=$.n(A),xe=$(29301),ae=$(76846),he=$(96452),ot=$(6089),at=$(80402),Re=$(34280),D=$(49658),z=$(59301),Zt=$(32855),ft=$(77900),De=$(8654);function fe(Q){var Te=Q.prefixCls,B=Q.align,Pe=Q.arrow,Oe=Q.arrowPos,Ze=Pe||{},mt=Ze.className,G=Ze.content,ee=Oe.x,se=ee===void 0?0:ee,w=Oe.y,Ae=w===void 0?0:w,Je=z.useRef();if(!B||!B.points)return null;var je={position:"absolute"};if(B.autoArrow!==!1){var Vt=B.points[0],Bt=B.points[1],Lt=Vt[0],Ht=Vt[1],jt=Bt[0],Xt=Bt[1];Lt===jt||!["t","b"].includes(Lt)?je.top=Ae:Lt==="t"?je.top=0:je.bottom=0,Ht===Xt||!["l","r"].includes(Ht)?je.left=se:Ht==="l"?je.left=0:je.right=0}return z.createElement("div",{ref:Je,className:g()("".concat(Te,"-arrow"),mt),style:je},G)}function M(Q){var Te=Q.prefixCls,B=Q.open,Pe=Q.zIndex,Oe=Q.mask,Ze=Q.motion;return Oe?z.createElement(ft.default,(0,Zt.Z)({},Ze,{motionAppear:!0,visible:B,removeOnLeave:!0}),function(mt){var G=mt.className;return z.createElement("div",{style:{zIndex:Pe},className:g()("".concat(Te,"-mask"),G)})}):null}var C=z.memo(function(Q){var Te=Q.children;return Te},function(Q,Te){return Te.cache}),W=C,ie=z.forwardRef(function(Q,Te){var B=Q.popup,Pe=Q.className,Oe=Q.prefixCls,Ze=Q.style,mt=Q.target,G=Q.onVisibleChanged,ee=Q.open,se=Q.keepDom,w=Q.fresh,Ae=Q.onClick,Je=Q.mask,je=Q.arrow,Vt=Q.arrowPos,Bt=Q.align,Lt=Q.motion,Ht=Q.maskMotion,jt=Q.forceRender,Xt=Q.getPopupContainer,Ii=Q.autoDestroy,pe=Q.portal,Ft=Q.zIndex,qi=Q.onMouseEnter,Ki=Q.onMouseLeave,Mi=Q.onPointerEnter,rs=Q.onPointerDownCapture,cs=Q.ready,Hi=Q.offsetX,Ti=Q.offsetY,Ji=Q.offsetR,Wi=Q.offsetB,Qe=Q.onAlign,Nt=Q.onPrepare,kt=Q.stretch,gi=Q.targetWidth,_i=Q.targetHeight,yi=typeof B=="function"?B():B,Rt=ee||se,Bi=(Xt==null?void 0:Xt.length)>0,Qt=z.useState(!Xt||!Bi),Si=(0,de.Z)(Qt,2),Ui=Si[0],Ee=Si[1];if((0,Re.Z)(function(){!Ui&&Bi&&mt&&Ee(!0)},[Ui,Bi,mt]),!Ui)return null;var d="auto",f={left:"-1000vw",top:"-1000vh",right:d,bottom:d};if(cs||!ee){var p,_=Bt.points,T=Bt.dynamicInset||((p=Bt._experimental)===null||p===void 0?void 0:p.dynamicInset),I=T&&_[0][1]==="r",O=T&&_[0][0]==="b";I?(f.right=Ji,f.left=d):(f.left=Hi,f.right=d),O?(f.bottom=Wi,f.top=d):(f.top=Ti,f.bottom=d)}var be={};return kt&&(kt.includes("height")&&_i?be.height=_i:kt.includes("minHeight")&&_i&&(be.minHeight=_i),kt.includes("width")&&gi?be.width=gi:kt.includes("minWidth")&&gi&&(be.minWidth=gi)),ee||(be.pointerEvents="none"),z.createElement(pe,{open:jt||Rt,getContainer:Xt&&function(){return Xt(mt)},autoDestroy:Ii},z.createElement(M,{prefixCls:Oe,open:ee,zIndex:Ft,mask:Je,motion:Ht}),z.createElement(xe.Z,{onResize:Qe,disabled:!ee},function(_e){return z.createElement(ft.default,(0,Zt.Z)({motionAppear:!0,motionEnter:!0,motionLeave:!0,removeOnLeave:!1,forceRender:jt,leavedClassName:"".concat(Oe,"-hidden")},Lt,{onAppearPrepare:Nt,onEnterPrepare:Nt,visible:ee,onVisibleChanged:function(It){var ht;Lt==null||(ht=Lt.onVisibleChanged)===null||ht===void 0||ht.call(Lt,It),G(It)}}),function(Me,It){var ht=Me.className,we=Me.style,gt=g()(Oe,ht,Pe);return z.createElement("div",{ref:(0,De.sQ)(_e,Te,It),className:gt,style:(0,b.Z)((0,b.Z)((0,b.Z)((0,b.Z)({"--arrow-x":"".concat(Vt.x||0,"px"),"--arrow-y":"".concat(Vt.y||0,"px")},f),be),we),{},{boxSizing:"border-box",zIndex:Ft},Ze),onMouseEnter:qi,onMouseLeave:Ki,onPointerEnter:Mi,onClick:Ae,onPointerDownCapture:rs},je&&z.createElement(fe,{prefixCls:Oe,arrow:je,arrowPos:Vt,align:Bt}),z.createElement(W,{cache:!ee&&!w},yi))})}))}),ge=ie,Xe=z.forwardRef(function(Q,Te){var B=Q.children,Pe=Q.getTriggerDOMNode,Oe=(0,De.Yr)(B),Ze=z.useCallback(function(G){(0,De.mH)(Te,Pe?Pe(G):G)},[Pe]),mt=(0,De.x1)(Ze,(0,De.C4)(B));return Oe?z.cloneElement(B,{ref:mt}):B}),J=Xe,dt=z.createContext(null),Et=dt;function Gt(Q){return Q?Array.isArray(Q)?Q:[Q]:[]}function _t(Q,Te,B,Pe){return z.useMemo(function(){var Oe=Gt(B!=null?B:Te),Ze=Gt(Pe!=null?Pe:Te),mt=new Set(Oe),G=new Set(Ze);return Q&&(mt.has("hover")&&(mt.delete("hover"),mt.add("click")),G.has("hover")&&(G.delete("hover"),G.add("click"))),[mt,G]},[Q,Te,B,Pe])}var te=$(29194);function X(){var Q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],Te=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],B=arguments.length>2?arguments[2]:void 0;return B?Q[0]===Te[0]:Q[0]===Te[0]&&Q[1]===Te[1]}function oe(Q,Te,B,Pe){for(var Oe=B.points,Ze=Object.keys(Q),mt=0;mt<Ze.length;mt+=1){var G,ee=Ze[mt];if(X((G=Q[ee])===null||G===void 0?void 0:G.points,Oe,Pe))return"".concat(Te,"-placement-").concat(ee)}return""}function F(Q,Te,B,Pe){return Te||(B?{motionName:"".concat(Q,"-").concat(B)}:Pe?{motionName:Pe}:null)}function ke(Q){return Q.ownerDocument.defaultView}function lt(Q){for(var Te=[],B=Q==null?void 0:Q.parentElement,Pe=["hidden","scroll","clip","auto"];B;){var Oe=ke(B).getComputedStyle(B),Ze=Oe.overflowX,mt=Oe.overflowY,G=Oe.overflow;[Ze,mt,G].some(function(ee){return Pe.includes(ee)})&&Te.push(B),B=B.parentElement}return Te}function me(Q){var Te=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return Number.isNaN(Q)?Te:Q}function Ye(Q){return me(parseFloat(Q),0)}function Fe(Q,Te){var B=(0,b.Z)({},Q);return(Te||[]).forEach(function(Pe){if(!(Pe instanceof HTMLBodyElement||Pe instanceof HTMLHtmlElement)){var Oe=ke(Pe).getComputedStyle(Pe),Ze=Oe.overflow,mt=Oe.overflowClipMargin,G=Oe.borderTopWidth,ee=Oe.borderBottomWidth,se=Oe.borderLeftWidth,w=Oe.borderRightWidth,Ae=Pe.getBoundingClientRect(),Je=Pe.offsetHeight,je=Pe.clientHeight,Vt=Pe.offsetWidth,Bt=Pe.clientWidth,Lt=Ye(G),Ht=Ye(ee),jt=Ye(se),Xt=Ye(w),Ii=me(Math.round(Ae.width/Vt*1e3)/1e3),pe=me(Math.round(Ae.height/Je*1e3)/1e3),Ft=(Vt-Bt-jt-Xt)*Ii,qi=(Je-je-Lt-Ht)*pe,Ki=Lt*pe,Mi=Ht*pe,rs=jt*Ii,cs=Xt*Ii,Hi=0,Ti=0;if(Ze==="clip"){var Ji=Ye(mt);Hi=Ji*Ii,Ti=Ji*pe}var Wi=Ae.x+rs-Hi,Qe=Ae.y+Ki-Ti,Nt=Wi+Ae.width+2*Hi-rs-cs-Ft,kt=Qe+Ae.height+2*Ti-Ki-Mi-qi;B.left=Math.max(B.left,Wi),B.top=Math.max(B.top,Qe),B.right=Math.min(B.right,Nt),B.bottom=Math.min(B.bottom,kt)}}),B}function Ne(Q){var Te=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,B="".concat(Te),Pe=B.match(/^(.*)\%$/);return Pe?Q*(parseFloat(Pe[1])/100):parseFloat(B)}function Ie(Q,Te){var B=Te||[],Pe=(0,de.Z)(B,2),Oe=Pe[0],Ze=Pe[1];return[Ne(Q.width,Oe),Ne(Q.height,Ze)]}function st(){var Q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"";return[Q[0],Q[1]]}function xt(Q,Te){var B=Te[0],Pe=Te[1],Oe,Ze;return B==="t"?Ze=Q.y:B==="b"?Ze=Q.y+Q.height:Ze=Q.y+Q.height/2,Pe==="l"?Oe=Q.x:Pe==="r"?Oe=Q.x+Q.width:Oe=Q.x+Q.width/2,{x:Oe,y:Ze}}function ei(Q,Te){var B={t:"b",b:"t",l:"r",r:"l"};return Q.map(function(Pe,Oe){return Oe===Te?B[Pe]||"c":Pe}).join("")}function si(Q,Te,B,Pe,Oe,Ze,mt){var G=z.useState({ready:!1,offsetX:0,offsetY:0,offsetR:0,offsetB:0,arrowX:0,arrowY:0,scaleX:1,scaleY:1,align:Oe[Pe]||{}}),ee=(0,de.Z)(G,2),se=ee[0],w=ee[1],Ae=z.useRef(0),Je=z.useMemo(function(){return Te?lt(Te):[]},[Te]),je=z.useRef({}),Vt=function(){je.current={}};Q||Vt();var Bt=(0,ot.Z)(function(){if(Te&&B&&Q){let Qi=function(is,Rs){var Ks=arguments.length>2&&arguments[2]!==void 0?arguments[2]:et,an=Rt.x+is,Xs=Rt.y+Rs,ki=an+O,ss=Xs+I,on=Math.max(an,Ks.left),rt=Math.max(Xs,Ks.top),Tt=Math.min(ki,Ks.right),Li=Math.min(ss,Ks.bottom);return Math.max(0,(Tt-on)*(Li-rt))},wi=function(){Jt=Rt.y+Ot,es=Jt+I,Xi=Rt.x+At,Ci=Xi+O};var jt,Xt,Ii,pe,Ft=Te,qi=Ft.ownerDocument,Ki=ke(Ft),Mi=Ki.getComputedStyle(Ft),rs=Mi.position,cs=Ft.style.left,Hi=Ft.style.top,Ti=Ft.style.right,Ji=Ft.style.bottom,Wi=Ft.style.overflow,Qe=(0,b.Z)((0,b.Z)({},Oe[Pe]),Ze),Nt=qi.createElement("div");(jt=Ft.parentElement)===null||jt===void 0||jt.appendChild(Nt),Nt.style.left="".concat(Ft.offsetLeft,"px"),Nt.style.top="".concat(Ft.offsetTop,"px"),Nt.style.position=rs,Nt.style.height="".concat(Ft.offsetHeight,"px"),Nt.style.width="".concat(Ft.offsetWidth,"px"),Ft.style.left="0",Ft.style.top="0",Ft.style.right="auto",Ft.style.bottom="auto",Ft.style.overflow="hidden";var kt;if(Array.isArray(B))kt={x:B[0],y:B[1],width:0,height:0};else{var gi,_i,yi=B.getBoundingClientRect();yi.x=(gi=yi.x)!==null&&gi!==void 0?gi:yi.left,yi.y=(_i=yi.y)!==null&&_i!==void 0?_i:yi.top,kt={x:yi.x,y:yi.y,width:yi.width,height:yi.height}}var Rt=Ft.getBoundingClientRect(),Bi=Ki.getComputedStyle(Ft),Qt=Bi.height,Si=Bi.width;Rt.x=(Xt=Rt.x)!==null&&Xt!==void 0?Xt:Rt.left,Rt.y=(Ii=Rt.y)!==null&&Ii!==void 0?Ii:Rt.top;var Ui=qi.documentElement,Ee=Ui.clientWidth,d=Ui.clientHeight,f=Ui.scrollWidth,p=Ui.scrollHeight,_=Ui.scrollTop,T=Ui.scrollLeft,I=Rt.height,O=Rt.width,be=kt.height,_e=kt.width,Me={left:0,top:0,right:Ee,bottom:d},It={left:-T,top:-_,right:f-T,bottom:p-_},ht=Qe.htmlRegion,we="visible",gt="visibleFirst";ht!=="scroll"&&ht!==gt&&(ht=we);var $e=ht===gt,Se=Fe(It,Je),ve=Fe(Me,Je),et=ht===we?ve:Se,qe=$e?ve:et;Ft.style.left="auto",Ft.style.top="auto",Ft.style.right="0",Ft.style.bottom="0";var Yt=Ft.getBoundingClientRect();Ft.style.left=cs,Ft.style.top=Hi,Ft.style.right=Ti,Ft.style.bottom=Ji,Ft.style.overflow=Wi,(pe=Ft.parentElement)===null||pe===void 0||pe.removeChild(Nt);var fi=me(Math.round(O/parseFloat(Si)*1e3)/1e3),mi=me(Math.round(I/parseFloat(Qt)*1e3)/1e3);if(fi===0||mi===0||(0,ae.Sh)(B)&&!(0,te.Z)(B))return;var Ce=Qe.offset,ze=Qe.targetOffset,it=Ie(Rt,Ce),k=(0,de.Z)(it,2),H=k[0],ne=k[1],q=Ie(kt,ze),le=(0,de.Z)(q,2),ye=le[0],Le=le[1];kt.x-=ye,kt.y-=Le;var Ke=Qe.points||[],Ut=(0,de.Z)(Ke,2),nt=Ut[0],Pt=Ut[1],Ct=st(Pt),Dt=st(nt),$t=xt(kt,Ct),zt=xt(Rt,Dt),ni=(0,b.Z)({},Qe),At=$t.x-zt.x+H,Ot=$t.y-zt.y+ne,pi=Qi(At,Ot),Wt=Qi(At,Ot,ve),Kt=xt(kt,["t","l"]),Ei=xt(Rt,["t","l"]),ti=xt(kt,["b","r"]),oi=xt(Rt,["b","r"]),ji=Qe.overflow||{},bi=ji.adjustX,li=ji.adjustY,ui=ji.shiftX,zi=ji.shiftY,$i=function(Rs){return typeof Rs=="boolean"?Rs:Rs>=0},Jt,es,Xi,Ci;wi();var fs=$i(li),ci=Dt[0]===Ct[0];if(fs&&Dt[0]==="t"&&(es>qe.bottom||je.current.bt)){var ds=Ot;ci?ds-=I-be:ds=Kt.y-oi.y-ne;var Cs=Qi(At,ds),Ds=Qi(At,ds,ve);Cs>pi||Cs===pi&&(!$e||Ds>=Wt)?(je.current.bt=!0,Ot=ds,ne=-ne,ni.points=[ei(Dt,0),ei(Ct,0)]):je.current.bt=!1}if(fs&&Dt[0]==="b"&&(Jt<qe.top||je.current.tb)){var vs=Ot;ci?vs+=I-be:vs=ti.y-Ei.y-ne;var ws=Qi(At,vs),as=Qi(At,vs,ve);ws>pi||ws===pi&&(!$e||as>=Wt)?(je.current.tb=!0,Ot=vs,ne=-ne,ni.points=[ei(Dt,0),ei(Ct,0)]):je.current.tb=!1}var os=$i(bi),ks=Dt[1]===Ct[1];if(os&&Dt[1]==="l"&&(Ci>qe.right||je.current.rl)){var ys=At;ks?ys-=O-_e:ys=Kt.x-oi.x-H;var gs=Qi(ys,Ot),Gi=Qi(ys,Ot,ve);gs>pi||gs===pi&&(!$e||Gi>=Wt)?(je.current.rl=!0,At=ys,H=-H,ni.points=[ei(Dt,1),ei(Ct,1)]):je.current.rl=!1}if(os&&Dt[1]==="r"&&(Xi<qe.left||je.current.lr)){var hs=At;ks?hs+=O-_e:hs=ti.x-Ei.x-H;var Vi=Qi(hs,Ot),Ps=Qi(hs,Ot,ve);Vi>pi||Vi===pi&&(!$e||Ps>=Wt)?(je.current.lr=!0,At=hs,H=-H,ni.points=[ei(Dt,1),ei(Ct,1)]):je.current.lr=!1}wi();var ts=ui===!0?0:ui;typeof ts=="number"&&(Xi<ve.left&&(At-=Xi-ve.left-H,kt.x+_e<ve.left+ts&&(At+=kt.x-ve.left+_e-ts)),Ci>ve.right&&(At-=Ci-ve.right-H,kt.x>ve.right-ts&&(At+=kt.x-ve.right+ts)));var ls=zi===!0?0:zi;typeof ls=="number"&&(Jt<ve.top&&(Ot-=Jt-ve.top-ne,kt.y+be<ve.top+ls&&(Ot+=kt.y-ve.top+be-ls)),es>ve.bottom&&(Ot-=es-ve.bottom-ne,kt.y>ve.bottom-ls&&(Ot+=kt.y-ve.bottom+ls)));var Ls=Rt.x+At,bt=Ls+O,Us=Rt.y+Ot,$s=Us+I,Ms=kt.x,Bs=Ms+_e,rn=kt.y,fn=rn+be,Gs=Math.max(Ls,Ms),ai=Math.min(bt,Bs),mn=(Gs+ai)/2,gn=mn-Ls,Ys=Math.max(Us,rn),Zs=Math.min($s,fn),qs=(Ys+Zs)/2,Vs=qs-Us;mt==null||mt(Te,ni);var us=Yt.right-Rt.x-(At+Rt.width),_s=Yt.bottom-Rt.y-(Ot+Rt.height);fi===1&&(At=Math.round(At),us=Math.round(us)),mi===1&&(Ot=Math.round(Ot),_s=Math.round(_s));var Ss={ready:!0,offsetX:At/fi,offsetY:Ot/mi,offsetR:us/fi,offsetB:_s/mi,arrowX:gn/fi,arrowY:Vs/mi,scaleX:fi,scaleY:mi,align:ni};w(Ss)}}),Lt=function(){Ae.current+=1;var Xt=Ae.current;Promise.resolve().then(function(){Ae.current===Xt&&Bt()})},Ht=function(){w(function(Xt){return(0,b.Z)((0,b.Z)({},Xt),{},{ready:!1})})};return(0,Re.Z)(Ht,[Pe]),(0,Re.Z)(function(){Q||Ht()},[Q]),[se.ready,se.offsetX,se.offsetY,se.offsetR,se.offsetB,se.arrowX,se.arrowY,se.scaleX,se.scaleY,se.align,Lt]}var di=$(3300);function Ai(Q,Te,B,Pe,Oe){(0,Re.Z)(function(){if(Q&&Te&&B){let Ae=function(){Pe(),Oe()};var Ze=Te,mt=B,G=lt(Ze),ee=lt(mt),se=ke(mt),w=new Set([se].concat((0,di.Z)(G),(0,di.Z)(ee)));return w.forEach(function(Je){Je.addEventListener("scroll",Ae,{passive:!0})}),se.addEventListener("resize",Ae,{passive:!0}),Pe(),function(){w.forEach(function(Je){Je.removeEventListener("scroll",Ae),se.removeEventListener("resize",Ae)})}}},[Q,Te,B])}var hi=$(48736);function St(Q,Te,B,Pe,Oe,Ze,mt,G){var ee=z.useRef(Q);ee.current=Q;var se=z.useRef(!1);z.useEffect(function(){if(Te&&Pe&&(!Oe||Ze)){var Ae=function(){se.current=!1},Je=function(Ii){var pe;ee.current&&!mt(((pe=Ii.composedPath)===null||pe===void 0||(pe=pe.call(Ii))===null||pe===void 0?void 0:pe[0])||Ii.target)&&!se.current&&G(!1)},je=ke(Pe);je.addEventListener("pointerdown",Ae,!0),je.addEventListener("mousedown",Je,!0),je.addEventListener("contextmenu",Je,!0);var Vt=(0,he.A)(B);if(Vt&&(Vt.addEventListener("mousedown",Je,!0),Vt.addEventListener("contextmenu",Je,!0)),0)var Bt,Lt,Ht,jt;return function(){je.removeEventListener("pointerdown",Ae,!0),je.removeEventListener("mousedown",Je,!0),je.removeEventListener("contextmenu",Je,!0),Vt&&(Vt.removeEventListener("mousedown",Je,!0),Vt.removeEventListener("contextmenu",Je,!0))}}},[Te,B,Pe,Oe,Ze]);function w(){se.current=!0}return w}var qt=["prefixCls","children","action","showAction","hideAction","popupVisible","defaultPopupVisible","onPopupVisibleChange","afterPopupVisibleChange","mouseEnterDelay","mouseLeaveDelay","focusDelay","blurDelay","mask","maskClosable","getPopupContainer","forceRender","autoDestroy","destroyPopupOnHide","popup","popupClassName","popupStyle","popupPlacement","builtinPlacements","popupAlign","zIndex","stretch","getPopupClassNameFromAlign","fresh","alignPoint","onPopupClick","onPopupAlign","arrow","popupMotion","maskMotion","popupTransitionName","popupAnimation","maskTransitionName","maskAnimation","className","getTriggerDOMNode"];function We(){var Q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Z.Z,Te=z.forwardRef(function(B,Pe){var Oe=B.prefixCls,Ze=Oe===void 0?"rc-trigger-popup":Oe,mt=B.children,G=B.action,ee=G===void 0?"hover":G,se=B.showAction,w=B.hideAction,Ae=B.popupVisible,Je=B.defaultPopupVisible,je=B.onPopupVisibleChange,Vt=B.afterPopupVisibleChange,Bt=B.mouseEnterDelay,Lt=B.mouseLeaveDelay,Ht=Lt===void 0?.1:Lt,jt=B.focusDelay,Xt=B.blurDelay,Ii=B.mask,pe=B.maskClosable,Ft=pe===void 0?!0:pe,qi=B.getPopupContainer,Ki=B.forceRender,Mi=B.autoDestroy,rs=B.destroyPopupOnHide,cs=B.popup,Hi=B.popupClassName,Ti=B.popupStyle,Ji=B.popupPlacement,Wi=B.builtinPlacements,Qe=Wi===void 0?{}:Wi,Nt=B.popupAlign,kt=B.zIndex,gi=B.stretch,_i=B.getPopupClassNameFromAlign,yi=B.fresh,Rt=B.alignPoint,Bi=B.onPopupClick,Qt=B.onPopupAlign,Si=B.arrow,Ui=B.popupMotion,Ee=B.maskMotion,d=B.popupTransitionName,f=B.popupAnimation,p=B.maskTransitionName,_=B.maskAnimation,T=B.className,I=B.getTriggerDOMNode,O=(0,Be.Z)(B,qt),be=Mi||rs||!1,_e=z.useState(!1),Me=(0,de.Z)(_e,2),It=Me[0],ht=Me[1];(0,Re.Z)(function(){ht((0,D.Z)())},[]);var we=z.useRef({}),gt=z.useContext(Et),$e=z.useMemo(function(){return{registerSubPopup:function(Tt,Li){we.current[Tt]=Li,gt==null||gt.registerSubPopup(Tt,Li)}}},[gt]),Se=(0,at.Z)(),ve=z.useState(null),et=(0,de.Z)(ve,2),qe=et[0],Yt=et[1],fi=z.useRef(null),mi=(0,ot.Z)(function(rt){fi.current=rt,(0,ae.Sh)(rt)&&qe!==rt&&Yt(rt),gt==null||gt.registerSubPopup(Se,rt)}),Ce=z.useState(null),ze=(0,de.Z)(Ce,2),it=ze[0],k=ze[1],H=z.useRef(null),ne=(0,ot.Z)(function(rt){(0,ae.Sh)(rt)&&it!==rt&&(k(rt),H.current=rt)}),q=z.Children.only(mt),le=(q==null?void 0:q.props)||{},ye={},Le=(0,ot.Z)(function(rt){var Tt,Li,Yi=it;return(Yi==null?void 0:Yi.contains(rt))||((Tt=(0,he.A)(Yi))===null||Tt===void 0?void 0:Tt.host)===rt||rt===Yi||(qe==null?void 0:qe.contains(rt))||((Li=(0,he.A)(qe))===null||Li===void 0?void 0:Li.host)===rt||rt===qe||Object.values(we.current).some(function(Ni){return(Ni==null?void 0:Ni.contains(rt))||rt===Ni})}),Ke=F(Ze,Ui,f,d),Ut=F(Ze,Ee,_,p),nt=z.useState(Je||!1),Pt=(0,de.Z)(nt,2),Ct=Pt[0],Dt=Pt[1],$t=Ae!=null?Ae:Ct,zt=(0,ot.Z)(function(rt){Ae===void 0&&Dt(rt)});(0,Re.Z)(function(){Dt(Ae||!1)},[Ae]);var ni=z.useRef($t);ni.current=$t;var At=z.useRef([]);At.current=[];var Ot=(0,ot.Z)(function(rt){var Tt;zt(rt),((Tt=At.current[At.current.length-1])!==null&&Tt!==void 0?Tt:$t)!==rt&&(At.current.push(rt),je==null||je(rt))}),pi=z.useRef(),Wt=function(){clearTimeout(pi.current)},Kt=function(Tt){var Li=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;Wt(),Li===0?Ot(Tt):pi.current=setTimeout(function(){Ot(Tt)},Li*1e3)};z.useEffect(function(){return Wt},[]);var Ei=z.useState(!1),ti=(0,de.Z)(Ei,2),oi=ti[0],ji=ti[1];(0,Re.Z)(function(rt){(!rt||$t)&&ji(!0)},[$t]);var bi=z.useState(null),li=(0,de.Z)(bi,2),ui=li[0],zi=li[1],$i=z.useState(null),Jt=(0,de.Z)($i,2),es=Jt[0],Xi=Jt[1],Ci=function(Tt){Xi([Tt.clientX,Tt.clientY])},fs=si($t,qe,Rt&&es!==null?es:it,Ji,Qe,Nt,Qt),ci=(0,de.Z)(fs,11),ds=ci[0],Cs=ci[1],Ds=ci[2],vs=ci[3],ws=ci[4],as=ci[5],os=ci[6],ks=ci[7],ys=ci[8],gs=ci[9],Gi=ci[10],hs=_t(It,ee,se,w),Vi=(0,de.Z)(hs,2),Ps=Vi[0],ts=Vi[1],ls=Ps.has("click"),Ls=ts.has("click")||ts.has("contextMenu"),bt=(0,ot.Z)(function(){oi||Gi()}),Us=function(){ni.current&&Rt&&Ls&&Kt(!1)};Ai($t,it,qe,bt,Us),(0,Re.Z)(function(){bt()},[es,Ji]),(0,Re.Z)(function(){$t&&!(Qe!=null&&Qe[Ji])&&bt()},[JSON.stringify(Nt)]);var $s=z.useMemo(function(){var rt=oe(Qe,Ze,gs,Rt);return g()(rt,_i==null?void 0:_i(gs))},[gs,_i,Qe,Ze,Rt]);z.useImperativeHandle(Pe,function(){return{nativeElement:H.current,popupElement:fi.current,forceAlign:bt}});var Ms=z.useState(0),Bs=(0,de.Z)(Ms,2),rn=Bs[0],fn=Bs[1],Gs=z.useState(0),ai=(0,de.Z)(Gs,2),mn=ai[0],gn=ai[1],Ys=function(){if(gi&&it){var Tt=it.getBoundingClientRect();fn(Tt.width),gn(Tt.height)}},Zs=function(){Ys(),bt()},qs=function(Tt){ji(!1),Gi(),Vt==null||Vt(Tt)},Vs=function(){return new Promise(function(Tt){Ys(),zi(function(){return Tt})})};(0,Re.Z)(function(){ui&&(Gi(),ui(),zi(null))},[ui]);function us(rt,Tt,Li,Yi){ye[rt]=function(Ni){var pn;Yi==null||Yi(Ni),Kt(Tt,Li);for(var Os=arguments.length,vn=new Array(Os>1?Os-1:0),Qs=1;Qs<Os;Qs++)vn[Qs-1]=arguments[Qs];(pn=le[rt])===null||pn===void 0||pn.call.apply(pn,[le,Ni].concat(vn))}}(ls||Ls)&&(ye.onClick=function(rt){var Tt;ni.current&&Ls?Kt(!1):!ni.current&&ls&&(Ci(rt),Kt(!0));for(var Li=arguments.length,Yi=new Array(Li>1?Li-1:0),Ni=1;Ni<Li;Ni++)Yi[Ni-1]=arguments[Ni];(Tt=le.onClick)===null||Tt===void 0||Tt.call.apply(Tt,[le,rt].concat(Yi))});var _s=St($t,Ls,it,qe,Ii,Ft,Le,Kt),Ss=Ps.has("hover"),Qi=ts.has("hover"),wi,is;Ss&&(us("onMouseEnter",!0,Bt,function(rt){Ci(rt)}),us("onPointerEnter",!0,Bt,function(rt){Ci(rt)}),wi=function(Tt){($t||oi)&&qe!==null&&qe!==void 0&&qe.contains(Tt.target)&&Kt(!0,Bt)},Rt&&(ye.onMouseMove=function(rt){var Tt;(Tt=le.onMouseMove)===null||Tt===void 0||Tt.call(le,rt)})),Qi&&(us("onMouseLeave",!1,Ht),us("onPointerLeave",!1,Ht),is=function(){Kt(!1,Ht)}),Ps.has("focus")&&us("onFocus",!0,jt),ts.has("focus")&&us("onBlur",!1,Xt),Ps.has("contextMenu")&&(ye.onContextMenu=function(rt){var Tt;ni.current&&ts.has("contextMenu")?Kt(!1):(Ci(rt),Kt(!0)),rt.preventDefault();for(var Li=arguments.length,Yi=new Array(Li>1?Li-1:0),Ni=1;Ni<Li;Ni++)Yi[Ni-1]=arguments[Ni];(Tt=le.onContextMenu)===null||Tt===void 0||Tt.call.apply(Tt,[le,rt].concat(Yi))}),T&&(ye.className=g()(le.className,T));var Rs=z.useRef(!1);Rs.current||(Rs.current=Ki||$t||oi);var Ks=(0,b.Z)((0,b.Z)({},le),ye),an={},Xs=["onContextMenu","onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"];Xs.forEach(function(rt){O[rt]&&(an[rt]=function(){for(var Tt,Li=arguments.length,Yi=new Array(Li),Ni=0;Ni<Li;Ni++)Yi[Ni]=arguments[Ni];(Tt=Ks[rt])===null||Tt===void 0||Tt.call.apply(Tt,[Ks].concat(Yi)),O[rt].apply(O,Yi)})});var ki=z.cloneElement(q,(0,b.Z)((0,b.Z)({},Ks),an)),ss={x:as,y:os},on=Si?(0,b.Z)({},Si!==!0?Si:{}):null;return z.createElement(z.Fragment,null,z.createElement(xe.Z,{disabled:!$t,ref:ne,onResize:Zs},z.createElement(J,{getTriggerDOMNode:I},ki)),Rs.current&&z.createElement(Et.Provider,{value:$e},z.createElement(ge,{portal:Q,ref:mi,prefixCls:Ze,popup:cs,className:g()(Hi,$s),style:Ti,target:it,onMouseEnter:wi,onMouseLeave:is,onPointerEnter:wi,zIndex:kt,open:$t,keepDom:oi,fresh:yi,onClick:Bi,onPointerDownCapture:_s,mask:Ii,motion:Ke,maskMotion:Ut,onVisibleChanged:qs,onPrepare:Vs,forceRender:Ki,autoDestroy:be,getPopupContainer:qi,align:gs,arrow:on,arrowPos:ss,ready:ds,offsetX:Cs,offsetY:Ds,offsetR:vs,offsetB:ws,onAlign:bt,stretch:gi,targetWidth:rn/ks,targetHeight:mn/ys})))});return Te}var Oi=We(Z.Z)},93152:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return Zt}});var b=$(59301),de=$(6767),Be=$(75727),Z=$(60513),A=$(68535),g=$(34055),xe=$(56102),ae=$(2610),he={watermark:"watermark___hNYlv",videovideo:"videovideo___ovOkV",animate__loop:"animate__loop___mvL6s",upDown:"upDown___SlgHv",container:"container___g1WYG","video-container":"video-container___XPkWR","video-controls":"video-controls___to0Zq",hide:"hide___NA3DV","video-progress":"video-progress___gqHsd",seek:"seek___iZHBm","seek-tooltip":"seek-tooltip___uWyXx","bottom-controls":"bottom-controls___uoIBm","left-controls":"left-controls___mBEx4","right-controls":"right-controls___e9L6r",rateOverlay:"rateOverlay___HHBWe",controlText:"controlText___M_BWR","volume-controls":"volume-controls___fa3mE","fullscreen-button":"fullscreen-button___ur0es","fullscreen-button1":"fullscreen-button1___rfaXm","pip-button":"pip-button___GFO8W","playback-animation":"playback-animation___ndURq",volume:"volume___OTmpP",hidden:"hidden___o7GkT"},ot=(ft,De,fe)=>new Promise((M,C)=>{var W=Xe=>{try{ge(fe.next(Xe))}catch(J){C(J)}},ie=Xe=>{try{ge(fe.throw(Xe))}catch(J){C(J)}},ge=Xe=>Xe.done?M(Xe.value):Promise.resolve(Xe.value).then(W,ie);ge((fe=fe.apply(ft,De)).next())});function at(ft){if(isNaN(ft))return{minutes:"00",seconds:"00"};const De=new Date(ft*1e3).toISOString().substr(11,8);return{hour:De.substr(0,2),minutes:De.substr(3,2),seconds:De.substr(6,2)}}Object.defineProperty(HTMLMediaElement.prototype,"playing",{get:function(){return this.currentTime>0&&!this.paused&&!this.ended&&this.readyState>2}});function Re(ft,De){return ft-De}function D(ft){ft.sort(Re);let De=0;for(let fe=0;fe<ft.length-1;fe++){let M=Math.abs(ft[fe+1]-ft[fe]);M<21&&(De+=M)}return De}const z=/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i;var Zt=(0,b.forwardRef)(({allow_skip:ft,src:De,toLog:fe,videoId:M,logWatchHistory:C,courseId:W=null,startTime:ie,handlePause:ge=()=>{},handlePlay:Xe=()=>{},handlePlayEnded:J=()=>{},autoPlay:dt=!1,onPlayEnded:Et=()=>{},isShowWaterMark:Gt=!0},_t)=>{var te;De=De==null?void 0:De.replace("http://","https://");const oe=((te=De==null?void 0:De.split("."))==null?void 0:te.pop())==="flv",F=(0,b.useRef)(),ke=(0,b.useRef)(),lt=(0,b.useRef)(),me=(0,b.useRef)(),Ye=(0,b.useRef)(),Fe=(0,b.useRef)(),Ne=(0,b.useRef)(),Ie=(0,b.useRef)(),st=(0,b.useRef)(),xt=(0,b.useRef)(),ei=(0,b.useRef)(),si=(0,b.useRef)(),di=(0,b.useRef)(),Ai=(0,b.useRef)(),hi=navigator.userAgent.toLowerCase().match(z),St=hi?hi[0]:"pc",qt=(0,b.useRef)(!1),We=(0,g.eY)();let Oi=0,Q=0,Te=0,B=null,Pe=!1,Oe=20,Ze=1,mt=!1,G=!1,ee=[];(0,b.useImperativeHandle)(_t,()=>({getLastUpdatedTime:()=>F.current.currentTime,getDuration:()=>F.current.duration})),de.ZP.config({maxCount:1,getContainer:()=>lt.current});const se=(0,b.useCallback)((Lt,Ht=!1)=>{let jt={point:F.current.currentTime};B?(jt.log_id=B,jt.watch_duration=D(ee),jt.total_duration=Q):(W?(jt.video_id=parseInt(M,10),jt.course_id=W):jt.video_id=M,jt.duration=Oi,jt.device=St),Ht&&(jt.ed="1");function Xt(){return ot(this,null,function*(){mt=!0,B=yield C==null?void 0:C(jt),mt=!1,Lt&&Lt()})}Xt()},[M,W]);(0,b.useEffect)(()=>{F.current&&(me.current.style.display="none",Ye.current.style.display="block"),de.ZP.destroy();let Lt=null;return Z.Z.isSupported&&oe&&De&&(De==null?void 0:De.indexOf(".m3u8"))<0?(Lt=Z.Z.createPlayer({type:"flv",volume:.8,cors:!0,url:De,muted:!1}),F.current&&(Lt.attachMediaElement(F.current),Lt.load())):F.current.setAttribute("src",De),Ae(),()=>{Lt&&(Lt.unload(),Lt.pause(),Lt.destroy(),Lt=null)}},[F,oe,De]);function w(){F.current.paused?(me.current.style.display="none",Ye.current.style.display="block"):(me.current.style.display="block",Ye.current.style.display="none")}function Ae(){ei.current.style.display="none",di.current.style.display="none",si.current.style.display="none",F.current.muted||F.current.volume===0?ei.current.style.display="block":F.current.volume>0&&F.current.volume<=.5?di.current.style.display="block":si.current.style.display="block"}(0,b.useEffect)(()=>{const Lt=document.getElementById("play"),Ht=document.querySelectorAll(".playback-icons use");function jt(){Xe(),ie&&!qt.current&&(F.current.currentTime=ie),qt.current=!0,ee.push(F.current.currentTime),Pe||(Pe=!0,fe&&se())}function Xt(){return ot(this,null,function*(){w(),ee.push(F.current.currentTime),fe&&se(()=>{B=null,Te=0,Pe=!1,mt=!1,G=!1,ee=[],Q=0,Ze=1},!0),Et()})}function Ii(){Fe.current.value=Math.round(F.current.currentTime),Ne.current.value=Math.round(F.current.currentTime)}function pe(){const Qe=at(Math.round(F.current.currentTime));st.current.innerText=`${Qe.hour>0?Qe.hour+":":""}${Qe.minutes}:${Qe.seconds}`,st.current.setAttribute("datetime",`${Qe.hour>0?" "+Qe.hour+" ":""}${Qe.minutes}m ${Qe.seconds}s`)}function Ft(){var Qe,Nt,kt,gi,_i,yi,Rt;const Bi=Math.round((Qe=F.current)==null?void 0:Qe.duration);(kt=(Nt=Fe.current)==null?void 0:Nt.setAttribute)==null||kt.call(Nt,"max",Bi),(_i=(gi=Ne.current)==null?void 0:gi.setAttribute)==null||_i.call(gi,"max",Bi);const Qt=at(Bi);Ie.current&&(Ie.current.innerText=`${Qt.hour>0?Qt.hour+":":""}${Qt.minutes}:${Qt.seconds}`,(Rt=(yi=Ie.current).setAttribute)==null||Rt.call(yi,"datetime",`${Qt.hour>0?" "+Qt.hour+" ":""}${Qt.minutes}m ${Qt.seconds}s`))}function qi(){try{const Qe=Math.round(F.current.duration);Fe.current.setAttribute("max",Qe),Ne.current.setAttribute("max",Qe);const Nt=at(Qe);Ie.current.innerText=`${Nt.hour>0?Nt.hour+":":""}${Nt.minutes}:${Nt.seconds}`,Ie.current.setAttribute("datetime",`${Nt.hour>0?" "+Nt.hour+" ":""}${Nt.minutes}m ${Nt.seconds}s`),Ii(),pe();const{width:kt,height:gi,x:_i,y:yi}=ke.current.getBoundingClientRect();if(_i<0||yi<0,!G){let Rt=F.current.currentTime,Bi=Rt-Te;Math.abs(Bi)<10?(Q+=Math.abs(Bi),Te=Rt,mt||Q-Ze*Oe>=0&&(Ze++,ee.push(Te),fe&&se())):(Te=Rt,fe&&se())}}catch(Qe){console.log("videoplaying:",Qe)}}function Ki(){G=!0}function Mi(){F.current.playing&&ee.push(F.current.currentTime,Te),Te=F.current.currentTime,G=!1}function rs(){Oi=F.current.duration,Oi<=20&&(Oe=Oi/3),F.current.addEventListener("play",jt)}function cs(Qe){Qe.preventDefault(),(0,ae.vp)()?(F.current.style.width="100%",F.current.style.height="100%"):F.current.style.cssText=""}function Hi(){ge()}function Ti(Qe){if(!ft){de.ZP.warning("\u8BE5\u89C6\u9891\u7981\u6B62\u5FEB\u8FDB/\u540E\u9000\u64AD\u653E");return}const Nt=Qe.target.dataset.seek?Qe.target.dataset.seek:Qe.target.value;F.current.currentTime=Nt,Ne.current.value=Nt,Fe.current.value=Nt}function Ji(Qe){const Nt=Math.round(Qe.offsetX/Qe.target.clientWidth*parseInt(Qe.target.getAttribute("max"),10));Fe.current.setAttribute("data-seek",Nt);const kt=at(Nt);xt.current.textContent=`${kt.hour>0?kt.hour+":":""}${kt.minutes}:${kt.seconds}`;const gi=F.current.getBoundingClientRect();xt.current.style.left=`${Qe.pageX-gi.left}px`}function Wi(Qe){switch(Qe.code){case"Space":Qe.preventDefault(),Vt();break;case"ArrowRight":if(Qe.preventDefault(),!ft){de.ZP.warning("\u8BE5\u89C6\u9891\u7981\u6B62\u5FEB\u8FDB/\u540E\u9000\u64AD\u653E");break}if(F.current.currentTime>=F.current.duration)break;F.current.currentTime=parseInt(F.current.currentTime)+5,Ii();break;case"ArrowLeft":if(Qe.preventDefault(),!ft){de.ZP.warning("\u8BE5\u89C6\u9891\u7981\u6B62\u5FEB\u8FDB/\u540E\u9000\u64AD\u653E");break}if(F.current.currentTime===0)break;F.current.currentTime=parseInt(F.current.currentTime)-5,Ii();break;case"ArrowUp":Qe.preventDefault(),F.current.volume<1&&(F.current.volume=(parseInt(F.current.volume*10)+1)/10);break;case"ArrowDown":Qe.preventDefault(),F.current.volume>0&&(F.current.volume=(parseInt(F.current.volume*10)-1)/10);break}}return lt.current.addEventListener((0,ae.gH)(),cs),F.current.addEventListener("canplay",rs),F.current.addEventListener("ended",Xt),F.current.addEventListener("seeking",Ki),F.current.addEventListener("seeked",Mi),F.current.addEventListener("loadedmetadata",Ft),Fe.current.addEventListener("mousemove",Ji),Fe.current.addEventListener("input",Ti),F.current.addEventListener("timeupdate",qi),F.current.addEventListener("pause",Hi),F.current.addEventListener("volumechange",Ae),document.addEventListener("keydown",Wi),()=>{var Qe,Nt,kt,gi,_i,yi,Rt,Bi,Qt,Si,Ui,Ee;(Qe=F.current)==null||Qe.removeEventListener("canplay",rs),(Nt=F.current)==null||Nt.removeEventListener("play",jt),(kt=F.current)==null||kt.removeEventListener("ended",Xt),(gi=F.current)==null||gi.removeEventListener("seeking",Ki),(_i=F.current)==null||_i.removeEventListener("seeked",Mi),(yi=Fe.current)==null||yi.removeEventListener("mousemove",Ji),(Rt=Fe.current)==null||Rt.removeEventListener("input",Ti),(Bi=F.current)==null||Bi.removeEventListener("timeupdate",qi),(Qt=F.current)==null||Qt.removeEventListener("pause",Hi),(Si=F.current)==null||Si.removeEventListener("loadedmetadata",Ft),(Ui=F.current)==null||Ui.removeEventListener("volumechange",Ae),document.removeEventListener("keydown",Wi),(Ee=F.current)!=null&&Ee.playing&&(ee.push(Te,F.current.currentTime),fe&&se())}},[F,De]),(0,b.useEffect)(()=>{if(F.current.onended=()=>{J(F)},F.current.oncontextmenu=()=>!1,(De==null?void 0:De.indexOf(".m3u8"))>-1){if(F.current.canPlayType("application/vnd.apple.mpegurl"))F.current.src=De;else if(A.ZP.isSupported()){var Lt=new A.ZP;Lt.loadSource(De),Lt.attachMedia(F.current)}}},[De]);const[Je,je]=(0,b.useState)(1),Vt=()=>{F.current.paused||F.current.ended?F.current.play():F.current.pause(),w()};function Bt(){F.current.muted=!F.current.muted,F.current.muted?(Ai.current.setAttribute("data-volume",volume.value),Ai.current.value=0):Ai.current.value=Ai.current.dataset.volume}return b.createElement("div",{style:{position:"relative"},ref:lt},b.createElement("div",{ref:ke,className:`${he.watermark} animated_alternate animate__animated_10s animate__infinite animate__stepstart ${he.animate__loop}`},Gt&&We?We.login:" "),b.createElement("div",{className:he.container},b.createElement("div",{className:he["video-container"],id:"video-container"},b.createElement("div",{className:he["playback-animation"],id:"playback-animation"},b.createElement("svg",{className:he["playback-icons"]},b.createElement("use",{className:"hidden",href:"#play-icon"}),b.createElement("use",{href:"#pause"}))),b.createElement("video",{className:he.video,id:"video",preload:"auto",disablePictureInPicture:!0,ref:F,autoPlay:dt}),b.createElement("div",{className:`${he["video-controls"]} `,id:"video-controls"},b.createElement("div",{className:he["bottom-controls"]},b.createElement("div",{className:he["left-controls"]},b.createElement("button",{"data-title":"\u64AD\u653E/\u6682\u505C",id:"play",onClick:Vt},b.createElement("svg",{className:he["playback-icons"]},b.createElement("use",{ref:Ye,href:"#play-icon"}),b.createElement("use",{ref:me,style:{display:"none"},href:"#pause"}))),b.createElement("div",{className:he.time},b.createElement("time",{id:"time-elapsed",ref:st},"00:00"),b.createElement("span",null," / "),b.createElement("time",{id:"duration",ref:Ie},"00:00"))),b.createElement("div",{className:he["right-controls"]},ft&&b.createElement(Be.Z,{placement:"top",overlayClassName:he.rateOverlay,getPopupContainer:Lt=>Lt.parentNode,menu:{items:[{key:"1",label:b.createElement("span",{onClick:()=>{je(1),F.current.playbackRate=1}},"1.0x")},{key:"2",label:b.createElement("span",{onClick:()=>{je(1.5),F.current.playbackRate=1.5}},"1.5x")},{key:"3",label:b.createElement("span",{onClick:()=>{je(2),F.current.playbackRate=2}},"2.0x")}]}},b.createElement("div",{className:`${he.controlText} mr5`},"\u500D\u901F")),b.createElement(xe.CopyToClipboard,{text:De,onCopy:()=>de.ZP.success("\u590D\u5236\u6210\u529F")},b.createElement("button",{"data-title":"\u590D\u5236\u94FE\u63A5"},b.createElement("i",{className:"icon-lianjie2 iconfont",style:{fontSize:"12px",color:"white"}}))),b.createElement("div",{className:he["volume-controls"]},b.createElement("button",{"data-title":"\u5F00\u542F/\u5173\u95ED\u58F0\u97F3",className:he["volume-button"],id:"volume-button",onClick:Bt},b.createElement("i",{ref:ei,className:"icon-a-bianzu8 iconfont",style:{fontSize:"14px",color:"white"}}),b.createElement("i",{ref:di,className:"icon-shengyinkaibeifen iconfont",style:{fontSize:"14px",color:"white"}}),b.createElement("i",{ref:si,className:"icon-shengyinkai iconfont",style:{fontSize:"14px",color:"white"}})),b.createElement("input",{className:he.volume,id:"volume",value:"1","data-mute":"0.5",type:"range",max:"1",min:"0",step:"0.01",ref:Ai,style:{display:"none"},onClick:Ae})),b.createElement("button",{"data-title":"\u5168\u5C4F/\u9000\u51FA\u5168\u5C4F",className:he["fullscreen-button"],onClick:()=>{(0,ae.vp)()?(0,ae.BU)():(0,ae.Dj)(lt.current)}},b.createElement("i",{className:"icon-fangda1 iconfont",style:{fontSize:"12px",color:"white"}})))),b.createElement("div",{className:he["video-progress"]},b.createElement("progress",{ref:Ne,value:"0",min:"0"}),b.createElement("input",{className:he.seek,ref:Fe,value:"0",min:"0",type:"range",step:"1"}),b.createElement("div",{className:he["seek-tooltip"],ref:xt,id:"seek-tooltip"},"00:00"))))),b.createElement("svg",{style:{display:"none"}},b.createElement("defs",null,b.createElement("symbol",{id:"pause",viewBox:"0 0 24 24"},b.createElement("path",{d:"M14.016 5.016h3.984v13.969h-3.984v-13.969zM6 18.984v-13.969h3.984v13.969h-3.984z"})),b.createElement("symbol",{id:"play-icon",viewBox:"0 0 24 24"},b.createElement("path",{d:"M8.016 5.016l10.969 6.984-10.969 6.984v-13.969z"})),b.createElement("symbol",{id:"volume-high",viewBox:"0 0 24 24"},b.createElement("path",{d:"M14.016 3.234q3.047 0.656 5.016 3.117t1.969 5.648-1.969 5.648-5.016 3.117v-2.063q2.203-0.656 3.586-2.484t1.383-4.219-1.383-4.219-3.586-2.484v-2.063zM16.5 12q0 2.813-2.484 4.031v-8.063q1.031 0.516 1.758 1.688t0.727 2.344zM3 9h3.984l5.016-5.016v16.031l-5.016-5.016h-3.984v-6z"})),b.createElement("symbol",{id:"volume-low",viewBox:"0 0 24 24"},b.createElement("path",{d:"M5.016 9h3.984l5.016-5.016v16.031l-5.016-5.016h-3.984v-6zM18.516 12q0 2.766-2.531 4.031v-8.063q1.031 0.516 1.781 1.711t0.75 2.32z"})),b.createElement("symbol",{id:"volume-mute",viewBox:"0 0 24 24"},b.createElement("path",{d:"M12 3.984v4.219l-2.109-2.109zM4.266 3l16.734 16.734-1.266 1.266-2.063-2.063q-1.547 1.313-3.656 1.828v-2.063q1.172-0.328 2.25-1.172l-4.266-4.266v6.75l-5.016-5.016h-3.984v-6h4.734l-4.734-4.734zM18.984 12q0-2.391-1.383-4.219t-3.586-2.484v-2.063q3.047 0.656 5.016 3.117t1.969 5.648q0 2.203-1.031 4.172l-1.5-1.547q0.516-1.266 0.516-2.625zM16.5 12q0 0.422-0.047 0.609l-2.438-2.438v-2.203q1.031 0.516 1.758 1.688t0.727 2.344z"})),b.createElement("symbol",{id:"fullscreen",viewBox:"0 0 24 24"},b.createElement("path",{d:"M14.016 5.016h4.969v4.969h-1.969v-3h-3v-1.969zM17.016 17.016v-3h1.969v4.969h-4.969v-1.969h3zM5.016 9.984v-4.969h4.969v1.969h-3v3h-1.969zM6.984 14.016v3h3v1.969h-4.969v-4.969h1.969z"})),b.createElement("symbol",{id:"fullscreen-exit",viewBox:"0 0 24 24"},b.createElement("path",{d:"M15.984 8.016h3v1.969h-4.969v-4.969h1.969v3zM14.016 18.984v-4.969h4.969v1.969h-3v3h-1.969zM8.016 8.016v-3h1.969v4.969h-4.969v-1.969h3zM5.016 15.984v-1.969h4.969v4.969h-1.969v-3h-3z"})),b.createElement("symbol",{id:"pip",viewBox:"0 0 24 24"},b.createElement("path",{d:"M21 19.031v-14.063h-18v14.063h18zM23.016 18.984q0 0.797-0.609 1.406t-1.406 0.609h-18q-0.797 0-1.406-0.609t-0.609-1.406v-14.016q0-0.797 0.609-1.383t1.406-0.586h18q0.797 0 1.406 0.586t0.609 1.383v14.016zM18.984 11.016v6h-7.969v-6h7.969z"})))))})},35207:function(Pi,wt,$){"use strict";$.r(wt),$.d(wt,{default:function(){return De}});var b=$(59301),de=$(76560),Be=$(458),Z=$(62957),A={flex_box_center:"flex_box_center___yF0Vb",flex_space_between:"flex_space_between___vsNYO",flex_box_vertical_center:"flex_box_vertical_center___C4UqH",flex_box_center_end:"flex_box_center_end___EGtmE",flex_box_column:"flex_box_column___uX9g9",bg:"bg___sRga2",menu:"menu___s8xQl",desc:"desc___poG1Z",listItem:"listItem___ml9kN",info:"info___Z8R2Z",add:"add___jH8te",addForm:"addForm___O999t",attendanceCode:"attendanceCode___hPKyl",signInStatus:"signInStatus___usMPT",colorE02020:"colorE02020___hZvSz",color0152d9:"color0152d9___RgXzd",colorFA6400:"colorFA6400___g2yU6",iframe:"iframe___HRzMh"},g=$(34055);const xe={init:[{stage_name:"\u521D\u59CB\u5B66\u4E60",parent:9999999,key:0},{stage_name:"\u7EEA\u8BBA",parent:0,key:1},{discipline_name:"\u7EEA\u8BBA",shixun_count:"1",video_count:"2",parent:1,key:"11"},{shixun_name:"\u7EEA\u8BBA1",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/f066ae1a9a8f418f837e5bf8d02b2690/76df907c20efd95bea0fa23424f10693-hd.m3u8",parent:"11",key:"111"},{shixun_name:"\u7EEA\u8BBA2",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/068ca7853da448c794eeffb0dee8bed4/5bb446a882043683e37474ff408f601b-hd.m3u8",parent:"11",key:"112"},{shixun_name:"C++\u5F00\u53D1\u73AF\u5883\u5E94\u7528\u5165\u95E8",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/zxb937qn/challenges",parent:"11",key:"113"},{stage_name:"\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",parent:0,key:2},{discipline_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_count:"1",video_count:"1",parent:2,key:"21"},{shixun_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/f5f9c87860cb4a98ba86da37b5bfac70/8d50a9c4d5d4d3382c09bad3f4c5dcb6-hd.m3u8",parent:"21",key:"211"},{shixun_name:"C++\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/lg5afhzv/challenges",parent:"21",key:"212"},{discipline_name:"\u5224\u65AD\u8BED\u53E5",shixun_count:"2",video_count:"2",parent:2,key:"22"},{shixun_name:"if\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/3b4e821b200443948c553e4c6b51d940/b9601216238e60440192c2deb58adc53-hd.m3u8",parent:"22",key:"221"},{shixun_name:"C++\u9009\u62E9\u7ED3\u6784\u2014\u2014\uFF08if\u591A\u91CD\u9009\u62E9\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/23xkyrmn/challenges",parent:"22",key:"222"},{shixun_name:"switch\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/3b4e821b200443948c553e4c6b51d940/b9601216238e60440192c2deb58adc53-hd.m3u8",parent:"22",key:"223"},{shixun_name:"C++\u9009\u62E9\u7ED3\u6784\u2014\u2014\uFF08\u5DE7\u7528switch\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/sm3c5a7v/challenges",parent:"22",key:"224"},{discipline_name:"\u5FAA\u73AF",shixun_count:"2",video_count:"2",parent:2,key:"23"},{shixun_name:"while\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/dda06371a1594f5d865479a0fadc77bb/cb504e3af36ebe2ba979e8fe5fbb2222-hd.m3u8",parent:"23",key:"231"},{shixun_name:"C++\u5FAA\u73AF\u7ED3\u6784\u2014\u2014\uFF08\u719F\u6089while\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/8yhf4sn6/challenges",parent:"23",key:"232"},{shixun_name:"for\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/503194c483f44ccfacc7f9ee14cda70a/36cbd964c6657d1bbc43eb33b98f0c51-hd.m3u8",parent:"23",key:"233"},{shixun_name:"C++\u9009\u62E9\u7ED3\u6784\u2014\u2014\uFF08\u5DE7\u7528switch\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/sm3c5a7v/challenges",parent:"23",key:"234"},{stage_name:"\u51FD\u6570",parent:0,key:3},{discipline_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_count:"2",video_count:"1",parent:3,key:"31"},{shixun_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c10e39b3afb14ad0b890368aa1751821/ef361445294452e1d9bfacae80b3ec2f-hd.m3u8",parent:"31",key:"311"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75281",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/3q4isevr/challenges",parent:"31",key:"312"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75282",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/tlhxwo64/challenges",parent:"31",key:"313"},{discipline_name:"\u4F20\u8F93\u4F20\u9012",shixun_count:"2",video_count:"1",parent:3,key:"32"},{shixun_name:"\u51FD\u6570\u7684\u53C2\u6570",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"32",key:"321"},{shixun_name:"C++\u53C2\u6570\u4F20\u90121",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/2phrn8yk/challenges",parent:"32",key:"322"},{shixun_name:"C++\u53C2\u6570\u4F20\u90122",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/xsq7p4a6/challenges",parent:"32",key:"323"},{discipline_name:"\u51FD\u6570\u91CD\u8F7D",shixun_count:"1",video_count:"1",parent:3,key:"33"},{shixun_name:"\u51FD\u6570\u91CD\u8F7D",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"33",key:"331"},{shixun_name:"C++\u51FD\u6570\u91CD\u8F7D",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/6hbqpv7e/challenges",parent:"33",key:"332"},{discipline_name:"\u9012\u5F52\u51FD\u6570",shixun_count:"2",video_count:"1",parent:3,key:"34"},{shixun_name:"\u51FD\u6570\u7684\u9012\u5F52\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/51a0935ddc884f1b9f6c1395f2011425/7308cd65a7fe1d13eebe2600054d29c7-hd.m3u8",parent:"34",key:"341"},{shixun_name:"\u9012\u5F52\u51FD\u6570\u7F16\u5199\u5165\u95E8",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4qjw9t32/challenges",parent:"34",key:"342"},{shixun_name:"\u9006\u5E8F\u8F93\u51FA\uFF08\u4F7F\u7528\u9012\u5F52\u89E3\u51B3\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/oxtrf27l/challenges",parent:"34",key:"343"},{stage_name:"\u7C7B\u548C\u5BF9\u8C61",parent:0,key:4},{discipline_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_count:"2",video_count:"1",parent:4,key:"41"},{shixun_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/b4e17c1e8c8d449f862af9ea94fa9522/bad9e739addf73679a70e38a9d2cc32c-hd.m3u8",parent:"41",key:"411"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/igwom4hs/challenges",parent:"41",key:"412"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784\u4F53",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/5yo6rw3f/challenges",parent:"41",key:"413"},{stage_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",parent:0,key:5},{discipline_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_count:"1",video_count:"1",parent:5,key:"51"},{shixun_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fde33b24ff2b4bf5bc5e238dc473df8e/3cf407a74af29554226084d17fa17858-hd.m3u8",parent:"51",key:"511"},{shixun_name:"C++\u7A0B\u5E8F\u7684\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/yqbh3fx5/challenges",parent:"51",key:"512"},{stage_name:"\u6570\u7EC4\u3001\u6307\u9488\u4E0E\u5B57\u7B26\u4E32",parent:0,key:6},{discipline_name:"\u6570\u7EC4",shixun_count:"1",video_count:"1",parent:6,key:"61"},{shixun_name:"\u6570\u7EC4",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"61",key:"611"},{shixun_name:"\u5E73\u5747\u6210\u7EE9\u4E0E\u7B80\u5355\u7EDF\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4wcfgm5q/challenges",parent:"61",key:"612"},{discipline_name:"\u6307\u9488",shixun_count:"3",video_count:"1",parent:6,key:"62"},{shixun_name:"\u6307\u9488",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/00a5448862c84c42b1a369ac2be88ae9/9b9627710a725e570ede478663c2589d-hd.m3u8",parent:"62",key:"621"},{shixun_name:"\u6307\u9488\u7EC3\u624B-\u5B57\u7B26\u4E32\u5012\u5E8F",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/lkn6xuc3/challenges",parent:"62",key:"622"},{shixun_name:"\u6307\u9488\u6570\u7EC4-\u5355\u8BCD\u5012\u5E8F",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/vtk73ny2/challenges",parent:"62",key:"623"},{shixun_name:"\u7528\u6307\u9488\u89E3\u51B3\u95EE\u9898-\u6587\u672C\u683C\u5F0F\u5904\u7406",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/xfnp73fz/challenges",parent:"62",key:"624"},{stage_name:"\u7C7B\u7684\u7EE7\u627F",parent:0,key:7},{discipline_name:"\u7C7B\u7684\u7EE7\u627F",shixun_count:"1",video_count:"3",parent:7,key:"71"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/1eedcdb9ec43442c93780f04859c9aa9/631b8c88eb263877d24637d5b8d54dc5-hd.m3u8",parent:"71",key:"711"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fc1e7d8d8140469ba1bc01ee64fcc3c1/9256d13f4a14ae17ba9cac9f895b8a9d-hd.m3u8",parent:"71",key:"712"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(3)",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7806?subject_id=jpl5vs26",parent:"71",key:"713"},{shixun_name:"\u7EE7\u627F\u4E0E\u6D3E\u751F",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/f83ipgyo/challenges",parent:"71",key:"714"},{stage_name:"\u591A\u6001\u6027",parent:0,key:8},{discipline_name:"\u591A\u6001\u6027",shixun_count:"1",video_count:"2",parent:8,key:"81"},{shixun_name:"\u591A\u6001\u6027(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/5a960b51ebf346d2b77afb3b70d00768/73d6fa00824f4c73b885d33f688c3294-hd.m3u8",parent:"81",key:"811"},{shixun_name:"\u591A\u6001\u6027(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/08fe97a36e184cf1bf27cdd7a24794c9/625c4e9e863840443f5332ccc02761fc-hd.m3u8",parent:"81",key:"812"},{shixun_name:"\u865A\u51FD\u6570\u4E0E\u591A\u6001\u6027",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/9pjmg7uf/challenges",parent:"81",key:"813"},{stage_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",parent:0,key:9},{discipline_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",shixun_count:"1",video_count:"3",parent:9,key:"91"},{shixun_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/8dcf418d2d16404d91af1780f669e549/eb538592d8a3b98e1c2f7f844f85b778-hd.m3u8",parent:"91",key:"911"},{shixun_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/459f2693af7b48f8b854033e666a77f8/f5b140c5adc0f24ac56b72492373306a-hd.m3u8",parent:"91",key:"912"},{shixun_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E(3)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/ccea50bc15d2468aab99aff19eb69e16/a5ecac1ee0c07360d07880187a787085-hd.m3u8",parent:"91",key:"913"},{shixun_name:"\u7FA4\u4F53\u7C7B\u548C\u7FA4\u4F53\u6570\u636E\u7684\u7EC4\u7EC7",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/kfv3my9o/challenges",parent:"91",key:"914"},{stage_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",parent:0,key:10},{discipline_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",shixun_count:"1",video_count:"3",parent:10,key:"101"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/2f3154d695a542fbaba5c483d8d7f7a9/aea4302c51501634469ed4b91462c810-hd.m3u8",parent:"101",key:"1011"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/23be6a61e4e54db398b9172b1213a1f2/3f1e88f97957369e29ef2bde63640004-hd.m3u8",parent:"101",key:"1012"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(3)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/a5887adcc34445bba695de7dcadb781e/0fb3a6a6ad38f7a107054c5f2f0de262-hd.m3u8",parent:"101",key:"1013"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/hmtw5iq6/challenges",parent:"101",key:"1014"},{stage_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA11",parent:0,key:1911},{discipline_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",shixun_count:"1",video_count:"2",parent:1911,key:9111},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165\u8F93\u51FA(1)22222",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c9e76b949ee847fbb89a926220526692/b80ff8d09a87bfde1064f5b73ae7c34b-hd.m3u8",parent:9111,key:"91111"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165\u8F93\u51FA(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/65c02365a4ad40858b69b8cbe3ca4aa1/18a2c5697d4a84a971c500565509f038-hd.m3u8",parent:"9111",key:"91112"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/hsvuixpm/challenges",parent:"9111",key:"91113"},{stage_name:"\u5F02\u5E38\u5904\u7406",parent:0,key:12},{discipline_name:"\u5F02\u5E38\u5904\u7406",shixun_count:"1",video_count:"1",parent:12,key:"121"},{shixun_name:"\u5F02\u5E38\u5904\u7406",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c95499dd4c064584914e32fca9563717/98a8be24326e3eb35375713f5ccbb8bb-hd.m3u8",parent:"121",key:"1211"},{shixun_name:"\u7F16\u5199\u5F02\u5E38\u5904\u7406\u7684\u7C7B",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/nlt6f7ae/challenges",parent:"121",key:"1212"}].map(fe=>(fe.parent=Number(fe.parent),fe.key=Number(fe.key),fe)),review:[{stage_name:"\u590D\u4E60\u5B66\u4E60",parent:9999999,key:0},{stage_name:"\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",parent:0,key:1},{discipline_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_count:"1",video_count:"1",parent:1,key:"11"},{shixun_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/f5f9c87860cb4a98ba86da37b5bfac70/8d50a9c4d5d4d3382c09bad3f4c5dcb6-hd.m3u8",parent:"11",key:"111"},{shixun_name:"C++\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/lg5afhzv/challenges",parent:"11",key:"112"},{discipline_name:"\u5FAA\u73AF",shixun_count:"2",video_count:"2",parent:1,key:"12"},{shixun_name:"while\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/dda06371a1594f5d865479a0fadc77bb/cb504e3af36ebe2ba979e8fe5fbb2222-hd.m3u8",parent:"12",key:"121"},{shixun_name:"C++\u5FAA\u73AF\u7ED3\u6784\u2014\u2014\uFF08\u719F\u6089while\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/8yhf4sn6/challenges",parent:"12",key:"122"},{shixun_name:"for\u8BED\u53E5",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/503194c483f44ccfacc7f9ee14cda70a/36cbd964c6657d1bbc43eb33b98f0c51-hd.m3u8",parent:"12",key:"123"},{shixun_name:"C++\u9009\u62E9\u7ED3\u6784\u2014\u2014\uFF08\u5DE7\u7528switch\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/sm3c5a7v/challenges",parent:"12",key:"124"},{stage_name:"\u51FD\u6570",parent:0,key:2},{discipline_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_count:"2",video_count:"1",parent:2,key:"21"},{shixun_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c10e39b3afb14ad0b890368aa1751821/ef361445294452e1d9bfacae80b3ec2f-hd.m3u8",parent:"21",key:"211"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75281",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/3q4isevr/challenges",parent:"21",key:"212"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75282",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/tlhxwo64/challenges",parent:"21",key:"213"},{discipline_name:"\u4F20\u8F93\u4F20\u9012",shixun_count:"2",video_count:"1",parent:2,key:"22"},{shixun_name:"\u51FD\u6570\u7684\u53C2\u6570",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"22",key:"221"},{shixun_name:"C++\u53C2\u6570\u4F20\u90121",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/2phrn8yk/challenges",parent:"22",key:"222"},{shixun_name:"C++\u53C2\u6570\u4F20\u90122",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/xsq7p4a6/challenges",parent:"22",key:"223"},{discipline_name:"\u9012\u5F52\u51FD\u6570",shixun_count:"2",video_count:"2",parent:2,key:"23"},{shixun_name:"\u51FD\u6570\u7684\u9012\u5F52\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/51a0935ddc884f1b9f6c1395f2011425/7308cd65a7fe1d13eebe2600054d29c7-hd.m3u8",parent:"23",key:"231"},{shixun_name:"\u9012\u5F52\u51FD\u6570\u7F16\u5199\u5165\u95E8",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4qjw9t32/challenges",parent:"23",key:"232"},{shixun_name:"\u9006\u5E8F\u8F93\u51FA\uFF08\u4F7F\u7528\u9012\u5F52\u89E3\u51B3\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/oxtrf27l/challenges",parent:"23",key:"233"},{stage_name:"\u7C7B\u548C\u5BF9\u8C61",parent:0,key:3},{discipline_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_count:"2",video_count:"1",parent:3,key:"31"},{shixun_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/b4e17c1e8c8d449f862af9ea94fa9522/bad9e739addf73679a70e38a9d2cc32c-hd.m3u8",parent:"31",key:"311"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/igwom4hs/challenges",parent:"31",key:"312"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784\u4F53",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/5yo6rw3f/challenges",parent:"31",key:"313"},{stage_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",parent:0,key:4},{discipline_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_count:"1",video_count:"1",parent:4,key:"41"},{shixun_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fde33b24ff2b4bf5bc5e238dc473df8e/3cf407a74af29554226084d17fa17858-hd.m3u8",parent:"41",key:"411"},{shixun_name:"C++\u7A0B\u5E8F\u7684\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/yqbh3fx5/challenges",parent:"41",key:"412"},{stage_name:"\u6570\u7EC4\u3001\u6307\u9488\u4E0E\u5B57\u7B26\u4E32",parent:0,key:5},{discipline_name:"\u6570\u7EC4",shixun_count:"1",video_count:"1",parent:5,key:"51"},{shixun_name:"\u6570\u7EC4",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"51",key:"511"},{shixun_name:"\u5E73\u5747\u6210\u7EE9\u4E0E\u7B80\u5355\u7EDF\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4wcfgm5q/challenges",parent:"51",key:"512"},{discipline_name:"\u6307\u9488",shixun_count:"1",video_count:"1",parent:5,key:"52"},{shixun_name:"\u6307\u9488",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/00a5448862c84c42b1a369ac2be88ae9/9b9627710a725e570ede478663c2589d-hd.m3u8",parent:"52",key:"521"},{shixun_name:"\u7528\u6307\u9488\u89E3\u51B3\u95EE\u9898-\u6587\u672C\u683C\u5F0F\u5904\u7406",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/xfnp73fz/challenges",parent:"52",key:"522"},{stage_name:"\u7C7B\u7684\u7EE7\u627F",parent:0,key:6},{discipline_name:"\u7C7B\u7684\u7EE7\u627F",shixun_count:"0",video_count:"2",parent:6,key:"61"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/1eedcdb9ec43442c93780f04859c9aa9/631b8c88eb263877d24637d5b8d54dc5-hd.m3u8",parent:"61",key:"611"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fc1e7d8d8140469ba1bc01ee64fcc3c1/9256d13f4a14ae17ba9cac9f895b8a9d-hd.m3u8",parent:"61",key:"612"},{stage_name:"\u591A\u6001\u6027",parent:0,key:7},{discipline_name:"\u591A\u6001\u6027",shixun_count:"1",video_count:"2",parent:7,key:"71"},{shixun_name:"\u591A\u6001\u6027(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/5a960b51ebf346d2b77afb3b70d00768/73d6fa00824f4c73b885d33f688c3294-hd.m3u8",parent:"71",key:"711"},{shixun_name:"\u591A\u6001\u6027(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/08fe97a36e184cf1bf27cdd7a24794c9/625c4e9e863840443f5332ccc02761fc-hd.m3u8",parent:"71",key:"712"},{shixun_name:"\u865A\u51FD\u6570\u4E0E\u591A\u6001\u6027",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/9pjmg7uf/challenges",parent:"71",key:"713"},{stage_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",parent:0,key:8},{discipline_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",shixun_count:"1",video_count:"1",parent:8,key:"81"},{shixun_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/8dcf418d2d16404d91af1780f669e549/eb538592d8a3b98e1c2f7f844f85b778-hd.m3u8",parent:"81",key:"811"},{shixun_name:"\u7FA4\u4F53\u7C7B\u548C\u7FA4\u4F53\u6570\u636E\u7684\u7EC4\u7EC7",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/kfv3my9o/challenges",parent:"81",key:"812"},{stage_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",parent:0,key:9},{discipline_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",shixun_count:"1",video_count:"1",parent:9,key:"91"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/2f3154d695a542fbaba5c483d8d7f7a9/aea4302c51501634469ed4b91462c810-hd.m3u8",parent:"91",key:"911"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/hmtw5iq6/challenges",parent:"91",key:"912"},{stage_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",parent:0,key:10},{discipline_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",shixun_count:"0",video_count:"2",parent:10,key:"101"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165\u8F93\u51FA(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c9e76b949ee847fbb89a926220526692/b80ff8d09a87bfde1064f5b73ae7c34b-hd.m3u8",parent:"101",key:"1011"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165\u8F93\u51FA(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/65c02365a4ad40858b69b8cbe3ca4aa1/18a2c5697d4a84a971c500565509f038-hd.m3u8",parent:"101",key:"1012"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/hsvuixpm/challenges",parent:"101",key:"1013"},{stage_name:"\u5F02\u5E38\u5904\u7406",parent:0,key:9911},{discipline_name:"\u5F02\u5E38\u5904\u7406",shixun_count:"1",video_count:"1",parent:9911,key:"99111"},{shixun_name:"\u5F02\u5E38\u5904\u7406",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c95499dd4c064584914e32fca9563717/98a8be24326e3eb35375713f5ccbb8bb-hd.m3u8",parent:"99111",key:"991111"},{shixun_name:"\u7F16\u5199\u5F02\u5E38\u5904\u7406\u7684\u7C7B",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/nlt6f7ae/challenges",parent:"99111",key:"991112"}].map(fe=>(fe.parent=Number(fe.parent),fe.key=Number(fe.key),fe)),before:[{stage_name:"\u8003\u524D\u5B66\u4E60",parent:9999999,key:0},{stage_name:"\u7EEA\u8BBA",parent:0,key:1},{discipline_name:"\u7EEA\u8BBA",shixun_count:"1",video_count:"2",parent:1,key:"11"},{shixun_name:"\u7EEA\u8BBA1",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/f066ae1a9a8f418f837e5bf8d02b2690/76df907c20efd95bea0fa23424f10693-hd.m3u8",parent:"11",key:"111"},{shixun_name:"\u7EEA\u8BBA2",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/068ca7853da448c794eeffb0dee8bed4/5bb446a882043683e37474ff408f601b-hd.m3u8",parent:"11",key:"112"},{shixun_name:"C++\u5F00\u53D1\u73AF\u5883\u5E94\u7528\u5165\u95E8",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/zxb937qn/challenges",parent:"11",key:"113"},{stage_name:"\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",parent:0,key:2},{discipline_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_count:"1",video_count:"1",parent:2,key:"21"},{shixun_name:"\u57FA\u7840\u6570\u636E\u7C7B\u578B\u548C\u8868\u8FBE\u5F0F",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/f5f9c87860cb4a98ba86da37b5bfac70/8d50a9c4d5d4d3382c09bad3f4c5dcb6-hd.m3u8",parent:"21",key:"211"},{shixun_name:"C++\u7B80\u5355\u7A0B\u5E8F\u8BBE\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/lg5afhzv/challenges",parent:"21",key:"212"},{stage_name:"\u51FD\u6570",parent:0,key:3},{discipline_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_count:"2",video_count:"1",parent:3,key:"31"},{shixun_name:"\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c10e39b3afb14ad0b890368aa1751821/ef361445294452e1d9bfacae80b3ec2f-hd.m3u8",parent:"31",key:"311"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75281",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/3q4isevr/challenges",parent:"31",key:"312"},{shixun_name:"C++\u51FD\u6570\u7684\u5B9A\u4E49\u4E0E\u8C03\u75282",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/tlhxwo64/challenges",parent:"31",key:"313"},{discipline_name:"\u9012\u5F52\u51FD\u6570",shixun_count:"2",video_count:"1",parent:3,key:"32"},{shixun_name:"\u51FD\u6570\u7684\u9012\u5F52\u8C03\u7528",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/51a0935ddc884f1b9f6c1395f2011425/7308cd65a7fe1d13eebe2600054d29c7-hd.m3u8",parent:"32",key:"321"},{shixun_name:"\u9012\u5F52\u51FD\u6570\u7F16\u5199\u5165\u95E8",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4qjw9t32/challenges",parent:"32",key:"322"},{shixun_name:"\u9006\u5E8F\u8F93\u51FA\uFF08\u4F7F\u7528\u9012\u5F52\u89E3\u51B3\uFF09",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/oxtrf27l/challenges",parent:"32",key:"323"},{stage_name:"\u7C7B\u548C\u5BF9\u8C61",parent:0,key:4},{discipline_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_count:"2",video_count:"1",parent:4,key:"41"},{shixun_name:"\u6784\u9020\u51FD\u6570\u548C\u6790\u6784\u51FD\u6570",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/b4e17c1e8c8d449f862af9ea94fa9522/bad9e739addf73679a70e38a9d2cc32c-hd.m3u8",parent:"41",key:"411"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/igwom4hs/challenges",parent:"41",key:"412"},{shixun_name:"\u5B9A\u4E49\u548C\u4F7F\u7528\u7ED3\u6784\u4F53",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/5yo6rw3f/challenges",parent:"41",key:"413"},{stage_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",parent:0,key:5},{discipline_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_count:"1",video_count:"1",parent:5,key:"51"},{shixun_name:"\u6570\u636E\u7684\u5171\u4EAB\u4E0E\u4FDD\u62A4",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fde33b24ff2b4bf5bc5e238dc473df8e/3cf407a74af29554226084d17fa17858-hd.m3u8",parent:"51",key:"511"},{shixun_name:"C++\u7A0B\u5E8F\u7684\u7ED3\u6784",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/yqbh3fx5/challenges",parent:"51",key:"512"},{stage_name:"\u6570\u7EC4\u3001\u6307\u9488\u4E0E\u5B57\u7B26\u4E32",parent:0,key:6},{discipline_name:"\u6570\u7EC4",shixun_count:"1",video_count:"1",parent:6,key:"61"},{shixun_name:"\u6570\u7EC4",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7785?subject_id=jpl5vs26",parent:"61",key:"611"},{shixun_name:"\u5E73\u5747\u6210\u7EE9\u4E0E\u7B80\u5355\u7EDF\u8BA1",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/4wcfgm5q/challenges",parent:"61",key:"612"},{stage_name:"\u7C7B\u7684\u7EE7\u627F",parent:0,key:7},{discipline_name:"\u7C7B\u7684\u7EE7\u627F",shixun_count:"1",video_count:"3",parent:7,key:"71"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/1eedcdb9ec43442c93780f04859c9aa9/631b8c88eb263877d24637d5b8d54dc5-hd.m3u8",parent:"71",key:"711"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/fc1e7d8d8140469ba1bc01ee64fcc3c1/9256d13f4a14ae17ba9cac9f895b8a9d-hd.m3u8",parent:"71",key:"712"},{shixun_name:"\u7C7B\u7684\u7EE7\u627F(3)",shixun_type:"\u89C6\u9891",url:"https://www.educoder.net/video/7806?subject_id=jpl5vs26",parent:"71",key:"713"},{shixun_name:"\u7EE7\u627F\u4E0E\u6D3E\u751F",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/f83ipgyo/challenges",parent:"71",key:"714"},{stage_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",parent:0,key:8},{discipline_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E",shixun_count:"0",video_count:"1",parent:8,key:"81"},{shixun_name:"\u6A21\u677F\u4E0E\u7FA4\u4F53\u6570\u636E(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/8dcf418d2d16404d91af1780f669e549/eb538592d8a3b98e1c2f7f844f85b778-hd.m3u8",parent:"81",key:"811"},{stage_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",parent:0,key:9},{discipline_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93",shixun_count:"0",video_count:"1",parent:9,key:"91"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/2f3154d695a542fbaba5c483d8d7f7a9/aea4302c51501634469ed4b91462c810-hd.m3u8",parent:"91",key:"911"},{shixun_name:"\u6CDB\u578B\u7A0B\u5E8F\u8BBE\u8BA1\u4E0EC++\u6807\u51C6\u6A21\u677F\u5E93(2)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/23be6a61e4e54db398b9172b1213a1f2/3f1e88f97957369e29ef2bde63640004-hd.m3u8",parent:"91",key:"912"},{stage_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",parent:0,key:10},{discipline_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165/\u8F93\u51FA",shixun_count:"0",video_count:"1",parent:10,key:"101"},{shixun_name:"\u6D41\u7C7B\u5E93\u4E0E\u8F93\u5165\u8F93\u51FA(1)",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c9e76b949ee847fbb89a926220526692/b80ff8d09a87bfde1064f5b73ae7c34b-hd.m3u8",parent:"101",key:"1011"},{stage_name:"\u5F02\u5E38\u5904\u7406",parent:0,key:9911},{discipline_name:"\u5F02\u5E38\u5904\u7406",shixun_count:"1",video_count:"1",parent:9911,key:"99111"},{shixun_name:"\u5F02\u5E38\u5904\u7406",shixun_type:"\u89C6\u9891",url:"https://video.educoder.net/c95499dd4c064584914e32fca9563717/98a8be24326e3eb35375713f5ccbb8bb-hd.m3u8",parent:"99111",key:"991111"},{shixun_name:"\u7F16\u5199\u5F02\u5E38\u5904\u7406\u7684\u7C7B",shixun_type:"\u5B9E\u8BAD",url:"https://www.educoder.net/shixuns/nlt6f7ae/challenges",parent:"99111",key:"991112"}].map(fe=>(fe.parent=Number(fe.parent),fe.key=Number(fe.key),fe))};var ae=$(96877),he=$(93152),ot=Object.defineProperty,at=Object.getOwnPropertySymbols,Re=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,z=(fe,M,C)=>M in fe?ot(fe,M,{enumerable:!0,configurable:!0,writable:!0,value:C}):fe[M]=C,Zt=(fe,M)=>{for(var C in M||(M={}))Re.call(M,C)&&z(fe,C,M[C]);if(at)for(var C of at(M))D.call(M,C)&&z(fe,C,M[C]);return fe};const ft=({classroomList:fe,loading:M,dispatch:C})=>{const[W]=(0,de.useSearchParams)(),[ie]=(0,b.useState)(Zt({},(0,de.useParams)())),[ge,Xe]=(0,b.useState)("init"),[J,dt]=(0,b.useState)(""),Et=(0,b.useRef)();(0,b.useEffect)(()=>{const oe=W.get("tabId");oe&&(Xe(oe),ie.status=oe)},[ie.categoryId,W.get("tabId")]);const Gt=oe=>{Xe(oe.key)},_t=[{name:"\u521D\u59CB\u5B66\u4E60",id:"init"},{name:"\u590D\u4E60\u5B66\u4E60",id:"review"},{name:"\u8003\u524D\u5B66\u4E60",id:"before"}],te=oe=>{oe.data.type==="playVideo"&&dt(oe.data.url)};(0,b.useEffect)(()=>{ge&&X(),window.addEventListener("message",te)},[ge]);const X=()=>{var oe;(oe=Et.current.contentWindow)==null||oe.postMessage({data:xe[ge]},"*")};return b.createElement("section",null,b.createElement(ae.Z,{isLoading:M["classroomList/getClassroomAttendancesList"],tabDataSource:_t,isAdmin:(0,g.GJ)(),onTabMenuClick:Gt,defaultSelectedKeys:[ge]}),b.createElement("section",null,b.createElement(Be.Z,{loading:M["classroomList/getClassroomAttendancesList"],active:!0,avatar:{size:40},paragraph:{rows:5},className:"mt30"},b.createElement("iframe",{src:"/knowledgegraph/parseTree.html",onLoad:X,className:A.iframe,ref:Et}))),b.createElement(Z.default,{open:!!J,onCancel:()=>dt(""),width:800,footer:null,bodyStyle:{padding:0},centered:!0,destroyOnClose:!0},b.createElement(he.Z,{src:J,autoPlay:!0,toLog:!1})))};var De=(0,de.connect)(({classroomList:fe,loading:M,globalSetting:C})=>({classroomList:fe,globalSetting:C,loading:M.effects}))(ft)},96877:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return D}});var b=$(59301),de=$(77019),Be=$(5269),Z=$(93041),A=$(75727),g=$(6767),xe=$(25399),ae={tabMenuContainer:"tabMenuContainer___uf5IP",control:"control___GheLs",iconH:"iconH___Wzw_r",selectBtn:"selectBtn___mfEnI",selectBtn1:"selectBtn1___rJF8S"},he=$(76560),ot=$(34055),at=$(49661),D=({isLoading:z,addText:Zt,tabDataSource:ft,isAdmin:De,dispatch:fe,classroomList:M,type:C,isExercise:W,defaultSelectedKeys:ie,onTabMenuClick:ge,getDropdownMenu:Xe,showControlButton:J,buttonText:dt,buttonIcon:Et="icon-tianjiadaohang",extraNode:Gt,user:_t,onButtonClick:te,isModelUser:X,menuItemWidth:oe=125})=>{var F,ke,lt,me,Ye;const Fe=(0,he.useParams)();return b.createElement("div",{className:ae.tabMenuContainer},b.createElement(de.Z,null,b.createElement(Be.Z,{flex:"1"},b.createElement(Z.default,{onSelect:Ne=>z?{}:ge(Ne),mode:"horizontal",selectedKeys:ie},ft.map(Ne=>b.createElement(Z.default.Item,{style:{width:oe},key:typeof Ne.index=="number"?Ne.index:Ne.id},b.createElement("span",{className:"c-grey-666"},Ne.name),Ne.total!==void 0&&De&&b.createElement("span",{className:"c-grey-999 ml20"},Ne.total||0))))),De&&W&&b.createElement("i",{className:"iconfont icon-shezhi8",style:{display:"flex",alignItems:"center",cursor:"pointer"},onClick:()=>{fe({type:"classroomList/setActionTabs",payload:{key:"\u5728\u7EBF\u8003\u8BD5\u8BBE\u7F6E"}})}}),De&&b.createElement(Be.Z,{className:"mr20 gutter-row",style:{display:"flex",alignItems:"center",color:"#0152d9",paddingBottom:3}},W&&b.createElement(A.Z,{className:"mr15",placement:"bottom",arrow:!0,dropdownRender:()=>b.createElement(Z.default,null,b.createElement(Z.default.Item,{key:1,onClick:()=>{var Ne;if(!(0,at.Ye)(fe)){if((0,ot.Rm)()&&!((Ne=M.AssistantObject.exercise)!=null&&Ne.can_download)){g.ZP.warning("\u60A8\u672A\u83B7\u53D6\u6B64\u6743\u9650\uFF0C\u9700\u5411\u8BFE\u5802\u7BA1\u7406\u5458\u7533\u8BF7\u6743\u9650\u624D\u80FD\u4F7F\u7528\u6B64\u529F\u80FD");return}fe({type:"classroomList/setActionTabs",payload:{key:"\u5BFC\u51FA\u6210\u7EE9",type:C,exportType:"exercise",category_id:Fe.categoryId}})}}},"\u5B66\u751F\u6210\u7EE9"),b.createElement(Z.default.Item,{key:3,onClick:()=>{var Ne;if(!(0,at.Ye)(fe)){if((0,ot.Rm)()&&!((Ne=M.AssistantObject.exercise)!=null&&Ne.can_download)){g.ZP.warning("\u60A8\u672A\u83B7\u53D6\u6B64\u6743\u9650\uFF0C\u9700\u5411\u8BFE\u5802\u7BA1\u7406\u5458\u7533\u8BF7\u6743\u9650\u624D\u80FD\u4F7F\u7528\u6B64\u529F\u80FD");return}he.history.push(`/classrooms/${Fe==null?void 0:Fe.coursesId}/exportlist/exercise_score,export_exercise_users`)}}},"\u5386\u53F2\u5BFC\u51FA"))},b.createElement("div",{className:"c-blue font16 ml20 current",style:{marginTop:2}},b.createElement("span",{style:{color:"#666666",cursor:"pointer"}},b.createElement("i",{className:"iconfont icon-xiazai6"})))),b.createElement("div",{className:ae.control},b.createElement("div",{className:ae.extra},Gt),J&&(dt=="\u6DFB\u52A0\u76F4\u64AD"?b.createElement(A.Z,{menu:{items:(ke=(F=[{label:b.createElement("div",{onClick:()=>{te("\u5916\u94FE")}},"\u5916\u94FE\u76F4\u64AD"),key:"1",show:!0},X&&{label:b.createElement("div",{onClick:()=>{te("\u5934\u6B4C")}},"\u5934\u6B4C\u76F4\u64AD"),key:"2",show:!0}])==null?void 0:F.filter(Ne=>Ne==null?void 0:Ne.show))==null?void 0:ke.map(Ne=>({label:Ne==null?void 0:Ne.label,key:Ne==null?void 0:Ne.key}))}},b.createElement("span",{className:ae.selectBtn},b.createElement("span",null,b.createElement("i",{className:`iconfont ${Et}`})),b.createElement("span",null,dt))):b.createElement("span",{onClick:te,style:{cursor:"pointer"},className:ae.selectBtn},b.createElement("span",null,b.createElement("i",{className:`iconfont ${Et}`})),b.createElement("span",null,dt))),!!Xe&&b.createElement(A.Z,{disabled:((lt=_t==null?void 0:_t.userInfo)==null?void 0:lt.user_status)===2,className:"ml10",dropdownRender:Xe},b.createElement("span",{className:((me=_t==null?void 0:_t.userInfo)==null?void 0:me.user_status)===2?ae.selectBtn1:ae.selectBtn},b.createElement("span",null,b.createElement("i",{className:"iconfont icon-tianjiadaohang"})),b.createElement(xe.Z,{title:((Ye=_t==null?void 0:_t.userInfo)==null?void 0:Ye.user_status)===2&&"\u6559\u5B66\u8BFE\u5802\u8BD5\u7528\u671F\u5DF2\u7ED3\u675F\uFF0C\u5E73\u53F0\u5DF2\u6682\u505C\u63D0\u4F9B\u5728\u7EBF\u8003\u8BD5\u521B\u5EFA\u529F\u80FD"},b.createElement("span",null,Zt||"\u521B\u5EFA\u8BD5\u5377"))))))))}},2610:function(Pi,wt,$){"use strict";$.d(wt,{BU:function(){return de},Dj:function(){return b},gH:function(){return Be},vp:function(){return Z}});function b(A){try{A.mozRequestFullScreen?A.mozRequestFullScreen():A.webkitRequestFullScreen&&A.webkitRequestFullScreen()}catch(g){console.log(g,":e")}}function de(){window.top.document.webkitExitFullscreen?window.top.document.webkitExitFullscreen():document.exitFullscreen?window.top.document.exitFullscreen():document.msExitFullscreen?window.top.document.msExitFullscreen():document.mozCancelFullScreen&&window.top.document.mozCancelFullScreen()}const Be=()=>{if(document.webkitExitFullscreen)return"webkitfullscreenchange";if(document.exitFullscreen)return"fullscreenchange";if(document.msExitFullscreen)return"msfullscreenchange";if(document.mozCancelFullScreen)return"mozfullscreenchange"};function Z(){var A=window.top.document.fullscreenElement||window.top.document.mozFullscreenElement||window.top.document.webkitFullscreenElement,g=document.fullscreenEnabled||document.mozFullscreenEnabled||document.webkitFullscreenEnabled;return console.log("fullscreenElement",A),window.isFullScreen?window.isFullScreen:A!=null}},60513:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return Ui}});class b{static install(){Object.setPrototypeOf=Object.setPrototypeOf||function(d,f){return d.__proto__=f,d},Object.assign=Object.assign||function(d){if(d==null)throw new TypeError("Cannot convert undefined or null to object");let f=Object(d);for(let p=1;p<arguments.length;p++){let _=arguments[p];if(_!=null)for(let T in _)_.hasOwnProperty(T)&&(f[T]=_[T])}return f},typeof self.Promise!="function"&&$(3867).polyfill()}}b.install();var de=b,Be=$(86204),Z=$.n(Be);class A{static e(d,f){(!d||A.FORCE_GLOBAL_TAG)&&(d=A.GLOBAL_TAG);let p=`[${d}] > ${f}`;A.ENABLE_CALLBACK&&A.emitter.emit("log","error",p),A.ENABLE_ERROR&&(console.error?console.error(p):console.warn?console.warn(p):console.log(p))}static i(d,f){(!d||A.FORCE_GLOBAL_TAG)&&(d=A.GLOBAL_TAG);let p=`[${d}] > ${f}`;A.ENABLE_CALLBACK&&A.emitter.emit("log","info",p),A.ENABLE_INFO&&(console.info?console.info(p):console.log(p))}static w(d,f){(!d||A.FORCE_GLOBAL_TAG)&&(d=A.GLOBAL_TAG);let p=`[${d}] > ${f}`;A.ENABLE_CALLBACK&&A.emitter.emit("log","warn",p),A.ENABLE_WARN&&(console.warn?console.warn(p):console.log(p))}static d(d,f){(!d||A.FORCE_GLOBAL_TAG)&&(d=A.GLOBAL_TAG);let p=`[${d}] > ${f}`;A.ENABLE_CALLBACK&&A.emitter.emit("log","debug",p),A.ENABLE_DEBUG&&(console.debug?console.debug(p):console.log(p))}static v(d,f){(!d||A.FORCE_GLOBAL_TAG)&&(d=A.GLOBAL_TAG);let p=`[${d}] > ${f}`;A.ENABLE_CALLBACK&&A.emitter.emit("log","verbose",p),A.ENABLE_VERBOSE&&console.log(p)}}A.GLOBAL_TAG="flv.js",A.FORCE_GLOBAL_TAG=!1,A.ENABLE_ERROR=!0,A.ENABLE_INFO=!0,A.ENABLE_WARN=!0,A.ENABLE_DEBUG=!0,A.ENABLE_VERBOSE=!0,A.ENABLE_CALLBACK=!1,A.emitter=new(Z());var g=A;class xe{constructor(){this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now}reset(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0}addBytes(d){this._firstCheckpoint===0?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=d,this._totalBytes+=d):this._now()-this._lastCheckpoint<1e3?(this._intervalBytes+=d,this._totalBytes+=d):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=d,this._totalBytes+=d,this._lastCheckpoint=this._now())}get currentKBps(){this.addBytes(0);let d=(this._now()-this._lastCheckpoint)/1e3;return d==0&&(d=1),this._intervalBytes/d/1024}get lastSecondKBps(){return this.addBytes(0),this._lastSecondBytes!==0?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0}get averageKBps(){let d=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/d/1024}}var ae=xe;class he{constructor(d){this._message=d}get name(){return"RuntimeException"}get message(){return this._message}toString(){return this.name+": "+this.message}}class ot extends he{constructor(d){super(d)}get name(){return"IllegalStateException"}}class at extends he{constructor(d){super(d)}get name(){return"InvalidArgumentException"}}class Re extends he{constructor(d){super(d)}get name(){return"NotImplementedException"}}const D={kIdle:0,kConnecting:1,kBuffering:2,kError:3,kComplete:4},z={OK:"OK",EXCEPTION:"Exception",HTTP_STATUS_CODE_INVALID:"HttpStatusCodeInvalid",CONNECTING_TIMEOUT:"ConnectingTimeout",EARLY_EOF:"EarlyEof",UNRECOVERABLE_EARLY_EOF:"UnrecoverableEarlyEof"};class Zt{constructor(d){this._type=d||"undefined",this._status=D.kIdle,this._needStash=!1,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}destroy(){this._status=D.kIdle,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}isWorking(){return this._status===D.kConnecting||this._status===D.kBuffering}get type(){return this._type}get status(){return this._status}get needStashBuffer(){return this._needStash}get onContentLengthKnown(){return this._onContentLengthKnown}set onContentLengthKnown(d){this._onContentLengthKnown=d}get onURLRedirect(){return this._onURLRedirect}set onURLRedirect(d){this._onURLRedirect=d}get onDataArrival(){return this._onDataArrival}set onDataArrival(d){this._onDataArrival=d}get onError(){return this._onError}set onError(d){this._onError=d}get onComplete(){return this._onComplete}set onComplete(d){this._onComplete=d}open(d,f){throw new Re("Unimplemented abstract function!")}abort(){throw new Re("Unimplemented abstract function!")}}let ft={};function De(){let Ee=self.navigator.userAgent.toLowerCase(),d=/(edge)\/([\w.]+)/.exec(Ee)||/(opr)[\/]([\w.]+)/.exec(Ee)||/(chrome)[ \/]([\w.]+)/.exec(Ee)||/(iemobile)[\/]([\w.]+)/.exec(Ee)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(Ee)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(Ee)||/(webkit)[ \/]([\w.]+)/.exec(Ee)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(Ee)||/(msie) ([\w.]+)/.exec(Ee)||Ee.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(Ee)||Ee.indexOf("compatible")<0&&/(firefox)[ \/]([\w.]+)/.exec(Ee)||[],f=/(ipad)/.exec(Ee)||/(ipod)/.exec(Ee)||/(windows phone)/.exec(Ee)||/(iphone)/.exec(Ee)||/(kindle)/.exec(Ee)||/(android)/.exec(Ee)||/(windows)/.exec(Ee)||/(mac)/.exec(Ee)||/(linux)/.exec(Ee)||/(cros)/.exec(Ee)||[],p={browser:d[5]||d[3]||d[1]||"",version:d[2]||d[4]||"0",majorVersion:d[4]||d[2]||"0",platform:f[0]||""},_={};if(p.browser){_[p.browser]=!0;let T=p.majorVersion.split(".");_.version={major:parseInt(p.majorVersion,10),string:p.version},T.length>1&&(_.version.minor=parseInt(T[1],10)),T.length>2&&(_.version.build=parseInt(T[2],10))}if(p.platform&&(_[p.platform]=!0),(_.chrome||_.opr||_.safari)&&(_.webkit=!0),_.rv||_.iemobile){_.rv&&delete _.rv;let T="msie";p.browser=T,_[T]=!0}if(_.edge){delete _.edge;let T="msedge";p.browser=T,_[T]=!0}if(_.opr){let T="opera";p.browser=T,_[T]=!0}if(_.safari&&_.android){let T="android";p.browser=T,_[T]=!0}_.name=p.browser,_.platform=p.platform;for(let T in ft)ft.hasOwnProperty(T)&&delete ft[T];Object.assign(ft,_)}De();var fe=ft;class M extends Zt{static isSupported(){try{let d=fe.msedge&&fe.version.minor>=15048,f=fe.msedge?d:!0;return self.fetch&&self.ReadableStream&&f}catch(d){return!1}}constructor(d,f){super("fetch-stream-loader"),this.TAG="FetchStreamLoader",this._seekHandler=d,this._config=f,this._needStash=!0,this._requestAbort=!1,this._contentLength=null,this._receivedLength=0}destroy(){this.isWorking()&&this.abort(),super.destroy()}open(d,f){this._dataSource=d,this._range=f;let p=d.url;this._config.reuseRedirectedURL&&d.redirectedURL!=null&&(p=d.redirectedURL);let _=this._seekHandler.getConfig(p,f),T=new self.Headers;if(typeof _.headers=="object"){let O=_.headers;for(let be in O)O.hasOwnProperty(be)&&T.append(be,O[be])}let I={method:"GET",headers:T,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if(typeof this._config.headers=="object")for(let O in this._config.headers)T.append(O,this._config.headers[O]);d.cors===!1&&(I.mode="same-origin"),d.withCredentials&&(I.credentials="include"),d.referrerPolicy&&(I.referrerPolicy=d.referrerPolicy),this._status=D.kConnecting,self.fetch(_.url,I).then(O=>{if(this._requestAbort){this._requestAbort=!1,this._status=D.kIdle;return}if(O.ok&&O.status>=200&&O.status<=299){if(O.url!==_.url&&this._onURLRedirect){let _e=this._seekHandler.removeURLParameters(O.url);this._onURLRedirect(_e)}let be=O.headers.get("Content-Length");return be!=null&&(this._contentLength=parseInt(be),this._contentLength!==0&&this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)),this._pump.call(this,O.body.getReader())}else if(this._status=D.kError,this._onError)this._onError(z.HTTP_STATUS_CODE_INVALID,{code:O.status,msg:O.statusText});else throw new he("FetchStreamLoader: Http code invalid, "+O.status+" "+O.statusText)}).catch(O=>{if(this._status=D.kError,this._onError)this._onError(z.EXCEPTION,{code:-1,msg:O.message});else throw O})}abort(){this._requestAbort=!0}_pump(d){return d.read().then(f=>{if(f.done)if(this._contentLength!==null&&this._receivedLength<this._contentLength){this._status=D.kError;let p=z.EARLY_EOF,_={code:-1,msg:"Fetch stream meet Early-EOF"};if(this._onError)this._onError(p,_);else throw new he(_.msg)}else this._status=D.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1);else{if(this._requestAbort===!0)return this._requestAbort=!1,this._status=D.kComplete,d.cancel();this._status=D.kBuffering;let p=f.value.buffer,_=this._range.from+this._receivedLength;this._receivedLength+=p.byteLength,this._onDataArrival&&this._onDataArrival(p,_,this._receivedLength),this._pump(d)}}).catch(f=>{if(f.code===11&&fe.msedge)return;this._status=D.kError;let p=0,_=null;if((f.code===19||f.message==="network error")&&(this._contentLength===null||this._contentLength!==null&&this._receivedLength<this._contentLength)?(p=z.EARLY_EOF,_={code:f.code,msg:"Fetch stream meet Early-EOF"}):(p=z.EXCEPTION,_={code:f.code,msg:f.message}),this._onError)this._onError(p,_);else throw new he(_.msg)})}}var C=M;class W extends Zt{static isSupported(){try{let d=new XMLHttpRequest;return d.open("GET","https://example.com",!0),d.responseType="moz-chunked-arraybuffer",d.responseType==="moz-chunked-arraybuffer"}catch(d){return g.w("MozChunkedLoader",d.message),!1}}constructor(d,f){super("xhr-moz-chunked-loader"),this.TAG="MozChunkedLoader",this._seekHandler=d,this._config=f,this._needStash=!0,this._xhr=null,this._requestAbort=!1,this._contentLength=null,this._receivedLength=0}destroy(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onloadend=null,this._xhr.onerror=null,this._xhr=null),super.destroy()}open(d,f){this._dataSource=d,this._range=f;let p=d.url;this._config.reuseRedirectedURL&&d.redirectedURL!=null&&(p=d.redirectedURL);let _=this._seekHandler.getConfig(p,f);this._requestURL=_.url;let T=this._xhr=new XMLHttpRequest;if(T.open("GET",_.url,!0),T.responseType="moz-chunked-arraybuffer",T.onreadystatechange=this._onReadyStateChange.bind(this),T.onprogress=this._onProgress.bind(this),T.onloadend=this._onLoadEnd.bind(this),T.onerror=this._onXhrError.bind(this),d.withCredentials&&(T.withCredentials=!0),typeof _.headers=="object"){let I=_.headers;for(let O in I)I.hasOwnProperty(O)&&T.setRequestHeader(O,I[O])}if(typeof this._config.headers=="object"){let I=this._config.headers;for(let O in I)I.hasOwnProperty(O)&&T.setRequestHeader(O,I[O])}this._status=D.kConnecting,T.send()}abort(){this._requestAbort=!0,this._xhr&&this._xhr.abort(),this._status=D.kComplete}_onReadyStateChange(d){let f=d.target;if(f.readyState===2){if(f.responseURL!=null&&f.responseURL!==this._requestURL&&this._onURLRedirect){let p=this._seekHandler.removeURLParameters(f.responseURL);this._onURLRedirect(p)}if(f.status!==0&&(f.status<200||f.status>299))if(this._status=D.kError,this._onError)this._onError(z.HTTP_STATUS_CODE_INVALID,{code:f.status,msg:f.statusText});else throw new he("MozChunkedLoader: Http code invalid, "+f.status+" "+f.statusText);else this._status=D.kBuffering}}_onProgress(d){if(this._status===D.kError)return;this._contentLength===null&&d.total!==null&&d.total!==0&&(this._contentLength=d.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));let f=d.target.response,p=this._range.from+this._receivedLength;this._receivedLength+=f.byteLength,this._onDataArrival&&this._onDataArrival(f,p,this._receivedLength)}_onLoadEnd(d){if(this._requestAbort===!0){this._requestAbort=!1;return}else if(this._status===D.kError)return;this._status=D.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)}_onXhrError(d){this._status=D.kError;let f=0,p=null;if(this._contentLength&&d.loaded<this._contentLength?(f=z.EARLY_EOF,p={code:-1,msg:"Moz-Chunked stream meet Early-Eof"}):(f=z.EXCEPTION,p={code:-1,msg:d.constructor.name+" "+d.type}),this._onError)this._onError(f,p);else throw new he(p.msg)}}var ie=W;class ge extends null{static isSupported(){try{if(typeof self.MSStream=="undefined"||typeof self.MSStreamReader=="undefined")return!1;let d=new XMLHttpRequest;return d.open("GET","https://example.com",!0),d.responseType="ms-stream",d.responseType==="ms-stream"}catch(d){return Log.w("MSStreamLoader",d.message),!1}}constructor(d,f){super("xhr-msstream-loader"),this.TAG="MSStreamLoader",this._seekHandler=d,this._config=f,this._needStash=!0,this._xhr=null,this._reader=null,this._totalRange=null,this._currentRange=null,this._currentRequestURL=null,this._currentRedirectedURL=null,this._contentLength=null,this._receivedLength=0,this._bufferLimit=16*1024*1024,this._lastTimeBufferSize=0,this._isReconnecting=!1}destroy(){this.isWorking()&&this.abort(),this._reader&&(this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr=null),super.destroy()}open(d,f){this._internalOpen(d,f,!1)}_internalOpen(d,f,p){this._dataSource=d,p?this._currentRange=f:this._totalRange=f;let _=d.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?_=this._currentRedirectedURL:d.redirectedURL!=null&&(_=d.redirectedURL));let T=this._seekHandler.getConfig(_,f);this._currentRequestURL=T.url;let I=this._reader=new self.MSStreamReader;I.onprogress=this._msrOnProgress.bind(this),I.onload=this._msrOnLoad.bind(this),I.onerror=this._msrOnError.bind(this);let O=this._xhr=new XMLHttpRequest;if(O.open("GET",T.url,!0),O.responseType="ms-stream",O.onreadystatechange=this._xhrOnReadyStateChange.bind(this),O.onerror=this._xhrOnError.bind(this),d.withCredentials&&(O.withCredentials=!0),typeof T.headers=="object"){let be=T.headers;for(let _e in be)be.hasOwnProperty(_e)&&O.setRequestHeader(_e,be[_e])}if(typeof this._config.headers=="object"){let be=this._config.headers;for(let _e in be)be.hasOwnProperty(_e)&&O.setRequestHeader(_e,be[_e])}this._isReconnecting?this._isReconnecting=!1:this._status=LoaderStatus.kConnecting,O.send()}abort(){this._internalAbort(),this._status=LoaderStatus.kComplete}_internalAbort(){this._reader&&(this._reader.readyState===1&&this._reader.abort(),this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.abort(),this._xhr.onreadystatechange=null,this._xhr=null)}_xhrOnReadyStateChange(d){let f=d.target;if(f.readyState===2)if(f.status>=200&&f.status<=299){if(this._status=LoaderStatus.kBuffering,f.responseURL!=null){let _=this._seekHandler.removeURLParameters(f.responseURL);f.responseURL!==this._currentRequestURL&&_!==this._currentRedirectedURL&&(this._currentRedirectedURL=_,this._onURLRedirect&&this._onURLRedirect(_))}let p=f.getResponseHeader("Content-Length");if(p!=null&&this._contentLength==null){let _=parseInt(p);_>0&&(this._contentLength=_,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength))}}else if(this._status=LoaderStatus.kError,this._onError)this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:f.status,msg:f.statusText});else throw new RuntimeException("MSStreamLoader: Http code invalid, "+f.status+" "+f.statusText);else if(f.readyState===3&&f.status>=200&&f.status<=299){this._status=LoaderStatus.kBuffering;let p=f.response;this._reader.readAsArrayBuffer(p)}}_xhrOnError(d){this._status=LoaderStatus.kError;let f=LoaderErrors.EXCEPTION,p={code:-1,msg:d.constructor.name+" "+d.type};if(this._onError)this._onError(f,p);else throw new RuntimeException(p.msg)}_msrOnProgress(d){let p=d.target.result;if(p==null){this._doReconnectIfNeeded();return}let _=p.slice(this._lastTimeBufferSize);this._lastTimeBufferSize=p.byteLength;let T=this._totalRange.from+this._receivedLength;this._receivedLength+=_.byteLength,this._onDataArrival&&this._onDataArrival(_,T,this._receivedLength),p.byteLength>=this._bufferLimit&&(Log.v(this.TAG,`MSStream buffer exceeded max size near ${T+_.byteLength}, reconnecting...`),this._doReconnectIfNeeded())}_doReconnectIfNeeded(){if(this._contentLength==null||this._receivedLength<this._contentLength){this._isReconnecting=!0,this._lastTimeBufferSize=0,this._internalAbort();let d={from:this._totalRange.from+this._receivedLength,to:-1};this._internalOpen(this._dataSource,d,!0)}}_msrOnLoad(d){this._status=LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._totalRange.from,this._totalRange.from+this._receivedLength-1)}_msrOnError(d){this._status=LoaderStatus.kError;let f=0,p=null;if(this._contentLength&&this._receivedLength<this._contentLength?(f=LoaderErrors.EARLY_EOF,p={code:-1,msg:"MSStream meet Early-Eof"}):(f=LoaderErrors.EARLY_EOF,p={code:-1,msg:d.constructor.name+" "+d.type}),this._onError)this._onError(f,p);else throw new RuntimeException(p.msg)}}var Xe=null;class J extends Zt{static isSupported(){try{let d=new XMLHttpRequest;return d.open("GET","https://example.com",!0),d.responseType="arraybuffer",d.responseType==="arraybuffer"}catch(d){return g.w("RangeLoader",d.message),!1}}constructor(d,f){super("xhr-range-loader"),this.TAG="RangeLoader",this._seekHandler=d,this._config=f,this._needStash=!1,this._chunkSizeKBList=[128,256,384,512,768,1024,1536,2048,3072,4096,5120,6144,7168,8192],this._currentChunkSizeKB=384,this._currentSpeedNormalized=0,this._zeroSpeedChunkCount=0,this._xhr=null,this._speedSampler=new ae,this._requestAbort=!1,this._waitForTotalLength=!1,this._totalLengthReceived=!1,this._currentRequestURL=null,this._currentRedirectedURL=null,this._currentRequestRange=null,this._totalLength=null,this._contentLength=null,this._receivedLength=0,this._lastTimeLoaded=0}destroy(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr=null),super.destroy()}get currentSpeed(){return this._speedSampler.lastSecondKBps}open(d,f){this._dataSource=d,this._range=f,this._status=D.kConnecting;let p=!1;this._dataSource.filesize!=null&&this._dataSource.filesize!==0&&(p=!0,this._totalLength=this._dataSource.filesize),!this._totalLengthReceived&&!p?(this._waitForTotalLength=!0,this._internalOpen(this._dataSource,{from:0,to:-1})):this._openSubRange()}_openSubRange(){let d=this._currentChunkSizeKB*1024,f=this._range.from+this._receivedLength,p=f+d;this._contentLength!=null&&p-this._range.from>=this._contentLength&&(p=this._range.from+this._contentLength-1),this._currentRequestRange={from:f,to:p},this._internalOpen(this._dataSource,this._currentRequestRange)}_internalOpen(d,f){this._lastTimeLoaded=0;let p=d.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?p=this._currentRedirectedURL:d.redirectedURL!=null&&(p=d.redirectedURL));let _=this._seekHandler.getConfig(p,f);this._currentRequestURL=_.url;let T=this._xhr=new XMLHttpRequest;if(T.open("GET",_.url,!0),T.responseType="arraybuffer",T.onreadystatechange=this._onReadyStateChange.bind(this),T.onprogress=this._onProgress.bind(this),T.onload=this._onLoad.bind(this),T.onerror=this._onXhrError.bind(this),d.withCredentials&&(T.withCredentials=!0),typeof _.headers=="object"){let I=_.headers;for(let O in I)I.hasOwnProperty(O)&&T.setRequestHeader(O,I[O])}if(typeof this._config.headers=="object"){let I=this._config.headers;for(let O in I)I.hasOwnProperty(O)&&T.setRequestHeader(O,I[O])}T.send()}abort(){this._requestAbort=!0,this._internalAbort(),this._status=D.kComplete}_internalAbort(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)}_onReadyStateChange(d){let f=d.target;if(f.readyState===2){if(f.responseURL!=null){let p=this._seekHandler.removeURLParameters(f.responseURL);f.responseURL!==this._currentRequestURL&&p!==this._currentRedirectedURL&&(this._currentRedirectedURL=p,this._onURLRedirect&&this._onURLRedirect(p))}if(f.status>=200&&f.status<=299){if(this._waitForTotalLength)return;this._status=D.kBuffering}else if(this._status=D.kError,this._onError)this._onError(z.HTTP_STATUS_CODE_INVALID,{code:f.status,msg:f.statusText});else throw new he("RangeLoader: Http code invalid, "+f.status+" "+f.statusText)}}_onProgress(d){if(this._status===D.kError)return;if(this._contentLength===null){let p=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,p=!0;let _=d.total;this._internalAbort(),_!=null&_!==0&&(this._totalLength=_)}if(this._range.to===-1?this._contentLength=this._totalLength-this._range.from:this._contentLength=this._range.to-this._range.from+1,p){this._openSubRange();return}this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}let f=d.loaded-this._lastTimeLoaded;this._lastTimeLoaded=d.loaded,this._speedSampler.addBytes(f)}_normalizeSpeed(d){let f=this._chunkSizeKBList,p=f.length-1,_=0,T=0,I=p;if(d<f[0])return f[0];for(;T<=I;){if(_=T+Math.floor((I-T)/2),_===p||d>=f[_]&&d<f[_+1])return f[_];f[_]<d?T=_+1:I=_-1}}_onLoad(d){if(this._status===D.kError)return;if(this._waitForTotalLength){this._waitForTotalLength=!1;return}this._lastTimeLoaded=0;let f=this._speedSampler.lastSecondKBps;if(f===0&&(this._zeroSpeedChunkCount++,this._zeroSpeedChunkCount>=3&&(f=this._speedSampler.currentKBps)),f!==0){let I=this._normalizeSpeed(f);this._currentSpeedNormalized!==I&&(this._currentSpeedNormalized=I,this._currentChunkSizeKB=I)}let p=d.target.response,_=this._range.from+this._receivedLength;this._receivedLength+=p.byteLength;let T=!1;this._contentLength!=null&&this._receivedLength<this._contentLength?this._openSubRange():T=!0,this._onDataArrival&&this._onDataArrival(p,_,this._receivedLength),T&&(this._status=D.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1))}_onXhrError(d){this._status=D.kError;let f=0,p=null;if(this._contentLength&&this._receivedLength>0&&this._receivedLength<this._contentLength?(f=z.EARLY_EOF,p={code:-1,msg:"RangeLoader meet Early-Eof"}):(f=z.EXCEPTION,p={code:-1,msg:d.constructor.name+" "+d.type}),this._onError)this._onError(f,p);else throw new he(p.msg)}}var dt=J;class Et extends Zt{static isSupported(){try{return typeof self.WebSocket!="undefined"}catch(d){return!1}}constructor(){super("websocket-loader"),this.TAG="WebSocketLoader",this._needStash=!0,this._ws=null,this._requestAbort=!1,this._receivedLength=0}destroy(){this._ws&&this.abort(),super.destroy()}open(d){try{let f=this._ws=new self.WebSocket(d.url);f.binaryType="arraybuffer",f.onopen=this._onWebSocketOpen.bind(this),f.onclose=this._onWebSocketClose.bind(this),f.onmessage=this._onWebSocketMessage.bind(this),f.onerror=this._onWebSocketError.bind(this),this._status=D.kConnecting}catch(f){this._status=D.kError;let p={code:f.code,msg:f.message};if(this._onError)this._onError(z.EXCEPTION,p);else throw new he(p.msg)}}abort(){let d=this._ws;d&&(d.readyState===0||d.readyState===1)&&(this._requestAbort=!0,d.close()),this._ws=null,this._status=D.kComplete}_onWebSocketOpen(d){this._status=D.kBuffering}_onWebSocketClose(d){if(this._requestAbort===!0){this._requestAbort=!1;return}this._status=D.kComplete,this._onComplete&&this._onComplete(0,this._receivedLength-1)}_onWebSocketMessage(d){if(d.data instanceof ArrayBuffer)this._dispatchArrayBuffer(d.data);else if(d.data instanceof Blob){let f=new FileReader;f.onload=()=>{this._dispatchArrayBuffer(f.result)},f.readAsArrayBuffer(d.data)}else{this._status=D.kError;let f={code:-1,msg:"Unsupported WebSocket message type: "+d.data.constructor.name};if(this._onError)this._onError(z.EXCEPTION,f);else throw new he(f.msg)}}_dispatchArrayBuffer(d){let f=d,p=this._receivedLength;this._receivedLength+=f.byteLength,this._onDataArrival&&this._onDataArrival(f,p,this._receivedLength)}_onWebSocketError(d){this._status=D.kError;let f={code:d.code,msg:d.message};if(this._onError)this._onError(z.EXCEPTION,f);else throw new he(f.msg)}}var Gt=Et;class _t{constructor(d){this._zeroStart=d||!1}getConfig(d,f){let p={};if(f.from!==0||f.to!==-1){let _;f.to!==-1?_=`bytes=${f.from.toString()}-${f.to.toString()}`:_=`bytes=${f.from.toString()}-`,p.Range=_}else this._zeroStart&&(p.Range="bytes=0-");return{url:d,headers:p}}removeURLParameters(d){return d}}var te=_t;class X{constructor(d,f){this._startName=d,this._endName=f}getConfig(d,f){let p=d;if(f.from!==0||f.to!==-1){let _=!0;p.indexOf("?")===-1&&(p+="?",_=!1),_&&(p+="&"),p+=`${this._startName}=${f.from.toString()}`,f.to!==-1&&(p+=`&${this._endName}=${f.to.toString()}`)}return{url:p,headers:{}}}removeURLParameters(d){let f=d.split("?")[0],p,_=d.indexOf("?");_!==-1&&(p=d.substring(_+1));let T="";if(p!=null&&p.length>0){let I=p.split("&");for(let O=0;O<I.length;O++){let be=I[O].split("="),_e=O>0;be[0]!==this._startName&&be[0]!==this._endName&&(_e&&(T+="&"),T+=I[O])}}return T.length===0?f:f+"?"+T}}var oe=X;class F{constructor(d,f,p){this.TAG="IOController",this._config=f,this._extraData=p,this._stashInitialSize=1024*384,f.stashInitialSize!=null&&f.stashInitialSize>0&&(this._stashInitialSize=f.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=1024*1024*3,this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,f.enableStashBuffer===!1&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=d,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(d.url),this._refTotalLength=d.filesize?d.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new ae,this._speedNormalizeList=[64,128,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}destroy(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null}isWorking(){return this._loader&&this._loader.isWorking()&&!this._paused}isPaused(){return this._paused}get status(){return this._loader.status}get extraData(){return this._extraData}set extraData(d){this._extraData=d}get onDataArrival(){return this._onDataArrival}set onDataArrival(d){this._onDataArrival=d}get onSeeked(){return this._onSeeked}set onSeeked(d){this._onSeeked=d}get onError(){return this._onError}set onError(d){this._onError=d}get onComplete(){return this._onComplete}set onComplete(d){this._onComplete=d}get onRedirect(){return this._onRedirect}set onRedirect(d){this._onRedirect=d}get onRecoveredEarlyEof(){return this._onRecoveredEarlyEof}set onRecoveredEarlyEof(d){this._onRecoveredEarlyEof=d}get currentURL(){return this._dataSource.url}get hasRedirect(){return this._redirectedURL!=null||this._dataSource.redirectedURL!=null}get currentRedirectedURL(){return this._redirectedURL||this._dataSource.redirectedURL}get currentSpeed(){return this._loaderClass===dt?this._loader.currentSpeed:this._speedSampler.lastSecondKBps}get loaderType(){return this._loader.type}_selectSeekHandler(){let d=this._config;if(d.seekType==="range")this._seekHandler=new te(this._config.rangeLoadZeroStart);else if(d.seekType==="param"){let f=d.seekParamStart||"bstart",p=d.seekParamEnd||"bend";this._seekHandler=new oe(f,p)}else if(d.seekType==="custom"){if(typeof d.customSeekHandler!="function")throw new at("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new d.customSeekHandler}else throw new at(`Invalid seekType in config: ${d.seekType}`)}_selectLoader(){if(this._config.customLoader!=null)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=Gt;else if(C.isSupported())this._loaderClass=C;else if(ie.isSupported())this._loaderClass=ie;else if(dt.isSupported())this._loaderClass=dt;else throw new he("Your browser doesn't support xhr with arraybuffer responseType!")}_createLoader(){this._loader=new this._loaderClass(this._seekHandler,this._config),this._loader.needStashBuffer===!1&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)}open(d){this._currentRange={from:0,to:-1},d&&(this._currentRange.from=d),this._speedSampler.reset(),d||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))}abort(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)}pause(){this.isWorking()&&(this._loader.abort(),this._stashUsed!==0?(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1):this._resumeFrom=this._currentRange.to+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)}resume(){if(this._paused){this._paused=!1;let d=this._resumeFrom;this._resumeFrom=0,this._internalSeek(d,!0)}}seek(d){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(d,!0)}_internalSeek(d,f){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(f),this._loader.destroy(),this._loader=null;let p={from:d,to:-1};this._currentRange={from:p.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,p),this._onSeeked&&this._onSeeked()}updateUrl(d){if(!d||typeof d!="string"||d.length===0)throw new at("Url must be a non-empty string!");this._dataSource.url=d}_expandBuffer(d){let f=this._stashSize;for(;f+1024*1024*1<d;)f*=2;if(f+=1024*1024*1,f===this._bufferSize)return;let p=new ArrayBuffer(f);if(this._stashUsed>0){let _=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(p,0,f).set(_,0)}this._stashBuffer=p,this._bufferSize=f}_normalizeSpeed(d){let f=this._speedNormalizeList,p=f.length-1,_=0,T=0,I=p;if(d<f[0])return f[0];for(;T<=I;){if(_=T+Math.floor((I-T)/2),_===p||d>=f[_]&&d<f[_+1])return f[_];f[_]<d?T=_+1:I=_-1}}_adjustStashSize(d){let f=0;this._config.isLive||d<512?f=d:d>=512&&d<=1024?f=Math.floor(d*1.5):f=d*2,f>8192&&(f=8192);let p=f*1024+1024*1024*1;this._bufferSize<p&&this._expandBuffer(p),this._stashSize=f*1024}_dispatchChunks(d,f){return this._currentRange.to=f+d.byteLength-1,this._onDataArrival(d,f)}_onURLRedirect(d){this._redirectedURL=d,this._onRedirect&&this._onRedirect(d)}_onContentLengthKnown(d){d&&this._fullRequestFlag&&(this._totalLength=d,this._fullRequestFlag=!1)}_onLoaderChunkArrival(d,f,p){if(!this._onDataArrival)throw new ot("IOController: No existing consumer (onDataArrival) callback!");if(this._paused)return;this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,this._onRecoveredEarlyEof&&this._onRecoveredEarlyEof()),this._speedSampler.addBytes(d.byteLength);let _=this._speedSampler.lastSecondKBps;if(_!==0){let T=this._normalizeSpeed(_);this._speedNormalized!==T&&(this._speedNormalized=T,this._adjustStashSize(T))}if(this._enableStash)if(this._stashUsed===0&&this._stashByteStart===0&&(this._stashByteStart=f),this._stashUsed+d.byteLength<=this._stashSize)new Uint8Array(this._stashBuffer,0,this._stashSize).set(new Uint8Array(d),this._stashUsed),this._stashUsed+=d.byteLength;else{let T=new Uint8Array(this._stashBuffer,0,this._bufferSize);if(this._stashUsed>0){let I=this._stashBuffer.slice(0,this._stashUsed),O=this._dispatchChunks(I,this._stashByteStart);if(O<I.byteLength){if(O>0){let be=new Uint8Array(I,O);T.set(be,0),this._stashUsed=be.byteLength,this._stashByteStart+=O}}else this._stashUsed=0,this._stashByteStart+=O;this._stashUsed+d.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+d.byteLength),T=new Uint8Array(this._stashBuffer,0,this._bufferSize)),T.set(new Uint8Array(d),this._stashUsed),this._stashUsed+=d.byteLength}else{let I=this._dispatchChunks(d,f);if(I<d.byteLength){let O=d.byteLength-I;O>this._bufferSize&&(this._expandBuffer(O),T=new Uint8Array(this._stashBuffer,0,this._bufferSize)),T.set(new Uint8Array(d,I),0),this._stashUsed+=O,this._stashByteStart=f+I}}}else if(this._stashUsed===0){let T=this._dispatchChunks(d,f);if(T<d.byteLength){let I=d.byteLength-T;I>this._bufferSize&&this._expandBuffer(I),new Uint8Array(this._stashBuffer,0,this._bufferSize).set(new Uint8Array(d,T),0),this._stashUsed+=I,this._stashByteStart=f+T}}else{this._stashUsed+d.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+d.byteLength);let T=new Uint8Array(this._stashBuffer,0,this._bufferSize);T.set(new Uint8Array(d),this._stashUsed),this._stashUsed+=d.byteLength;let I=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart);if(I<this._stashUsed&&I>0){let O=new Uint8Array(this._stashBuffer,I);T.set(O,0)}this._stashUsed-=I,this._stashByteStart+=I}}_flushStashBuffer(d){if(this._stashUsed>0){let f=this._stashBuffer.slice(0,this._stashUsed),p=this._dispatchChunks(f,this._stashByteStart),_=f.byteLength-p;if(p<f.byteLength)if(d)g.w(this.TAG,`${_} bytes unconsumed data remain when flush buffer, dropped`);else{if(p>0){let T=new Uint8Array(this._stashBuffer,0,this._bufferSize),I=new Uint8Array(f,p);T.set(I,0),this._stashUsed=I.byteLength,this._stashByteStart+=p}return 0}return this._stashUsed=0,this._stashByteStart=0,_}return 0}_onLoaderComplete(d,f){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)}_onLoaderError(d,f){switch(g.e(this.TAG,`Loader error, code = ${f.code}, msg = ${f.msg}`),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,d=z.UNRECOVERABLE_EARLY_EOF),d){case z.EARLY_EOF:{if(!this._config.isLive&&this._totalLength){let p=this._currentRange.to+1;p<this._totalLength&&(g.w(this.TAG,"Connection lost, trying reconnect..."),this._isEarlyEofReconnecting=!0,this._internalSeek(p,!1));return}d=z.UNRECOVERABLE_EARLY_EOF;break}case z.UNRECOVERABLE_EARLY_EOF:case z.CONNECTING_TIMEOUT:case z.HTTP_STATUS_CODE_INVALID:case z.EXCEPTION:break}if(this._onError)this._onError(d,f);else throw new he("IOException: "+f.msg)}}var ke=F;const lt={enableWorker:!1,enableStashBuffer:!0,stashInitialSize:void 0,isLive:!1,lazyLoad:!0,lazyLoadMaxDuration:3*60,lazyLoadRecoverDuration:30,deferLoadAfterSourceOpen:!0,autoCleanupMaxBackwardDuration:3*60,autoCleanupMinBackwardDuration:2*60,statisticsInfoReportInterval:600,fixAudioTimestampGap:!0,accurateSeek:!1,seekType:"range",seekParamStart:"bstart",seekParamEnd:"bend",rangeLoadZeroStart:!1,customSeekHandler:void 0,reuseRedirectedURL:!1,headers:void 0,customLoader:void 0};function me(){return Object.assign({},lt)}class Ye{static supportMSEH264Playback(){return window.MediaSource&&window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"')}static supportNetworkStreamIO(){let d=new ke({},me()),f=d.loaderType;return d.destroy(),f=="fetch-stream-loader"||f=="xhr-moz-chunked-loader"}static getNetworkLoaderTypeName(){let d=new ke({},me()),f=d.loaderType;return d.destroy(),f}static supportNativeMediaPlayback(d){Ye.videoElement==null&&(Ye.videoElement=window.document.createElement("video"));let f=Ye.videoElement.canPlayType(d);return f==="probably"||f=="maybe"}static getFeatureList(){let d={mseFlvPlayback:!1,mseLiveFlvPlayback:!1,networkStreamIO:!1,networkLoaderName:"",nativeMP4H264Playback:!1,nativeWebmVP8Playback:!1,nativeWebmVP9Playback:!1};return d.mseFlvPlayback=Ye.supportMSEH264Playback(),d.networkStreamIO=Ye.supportNetworkStreamIO(),d.networkLoaderName=Ye.getNetworkLoaderTypeName(),d.mseLiveFlvPlayback=d.mseFlvPlayback&&d.networkStreamIO,d.nativeMP4H264Playback=Ye.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'),d.nativeWebmVP8Playback=Ye.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'),d.nativeWebmVP9Playback=Ye.supportNativeMediaPlayback('video/webm; codecs="vp9"'),d}}var Fe=Ye,Ie={ERROR:"error",LOADING_COMPLETE:"loading_complete",RECOVERED_EARLY_EOF:"recovered_early_eof",MEDIA_INFO:"media_info",METADATA_ARRIVED:"metadata_arrived",SCRIPTDATA_ARRIVED:"scriptdata_arrived",STATISTICS_INFO:"statistics_info"};class st{static get forceGlobalTag(){return g.FORCE_GLOBAL_TAG}static set forceGlobalTag(d){g.FORCE_GLOBAL_TAG=d,st._notifyChange()}static get globalTag(){return g.GLOBAL_TAG}static set globalTag(d){g.GLOBAL_TAG=d,st._notifyChange()}static get enableAll(){return g.ENABLE_VERBOSE&&g.ENABLE_DEBUG&&g.ENABLE_INFO&&g.ENABLE_WARN&&g.ENABLE_ERROR}static set enableAll(d){g.ENABLE_VERBOSE=d,g.ENABLE_DEBUG=d,g.ENABLE_INFO=d,g.ENABLE_WARN=d,g.ENABLE_ERROR=d,st._notifyChange()}static get enableDebug(){return g.ENABLE_DEBUG}static set enableDebug(d){g.ENABLE_DEBUG=d,st._notifyChange()}static get enableVerbose(){return g.ENABLE_VERBOSE}static set enableVerbose(d){g.ENABLE_VERBOSE=d,st._notifyChange()}static get enableInfo(){return g.ENABLE_INFO}static set enableInfo(d){g.ENABLE_INFO=d,st._notifyChange()}static get enableWarn(){return g.ENABLE_WARN}static set enableWarn(d){g.ENABLE_WARN=d,st._notifyChange()}static get enableError(){return g.ENABLE_ERROR}static set enableError(d){g.ENABLE_ERROR=d,st._notifyChange()}static getConfig(){return{globalTag:g.GLOBAL_TAG,forceGlobalTag:g.FORCE_GLOBAL_TAG,enableVerbose:g.ENABLE_VERBOSE,enableDebug:g.ENABLE_DEBUG,enableInfo:g.ENABLE_INFO,enableWarn:g.ENABLE_WARN,enableError:g.ENABLE_ERROR,enableCallback:g.ENABLE_CALLBACK}}static applyConfig(d){g.GLOBAL_TAG=d.globalTag,g.FORCE_GLOBAL_TAG=d.forceGlobalTag,g.ENABLE_VERBOSE=d.enableVerbose,g.ENABLE_DEBUG=d.enableDebug,g.ENABLE_INFO=d.enableInfo,g.ENABLE_WARN=d.enableWarn,g.ENABLE_ERROR=d.enableError,g.ENABLE_CALLBACK=d.enableCallback}static _notifyChange(){let d=st.emitter;if(d.listenerCount("change")>0){let f=st.getConfig();d.emit("change",f)}}static registerListener(d){st.emitter.addListener("change",d)}static removeListener(d){st.emitter.removeListener("change",d)}static addLogListener(d){g.emitter.addListener("log",d),g.emitter.listenerCount("log")>0&&(g.ENABLE_CALLBACK=!0,st._notifyChange())}static removeLogListener(d){g.emitter.removeListener("log",d),g.emitter.listenerCount("log")===0&&(g.ENABLE_CALLBACK=!1,st._notifyChange())}}st.emitter=new(Z());var xt=st;class ei{constructor(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}isComplete(){let d=this.hasAudio===!1||this.hasAudio===!0&&this.audioCodec!=null&&this.audioSampleRate!=null&&this.audioChannelCount!=null,f=this.hasVideo===!1||this.hasVideo===!0&&this.videoCodec!=null&&this.width!=null&&this.height!=null&&this.fps!=null&&this.profile!=null&&this.level!=null&&this.refFrames!=null&&this.chromaFormat!=null&&this.sarNum!=null&&this.sarDen!=null;return this.mimeType!=null&&this.duration!=null&&this.metadata!=null&&this.hasKeyframesIndex!=null&&d&&f}isSeekable(){return this.hasKeyframesIndex===!0}getNearestKeyframe(d){if(this.keyframesIndex==null)return null;let f=this.keyframesIndex,p=this._search(f.times,d);return{index:p,milliseconds:f.times[p],fileposition:f.filepositions[p]}}_search(d,f){let p=0,_=d.length-1,T=0,I=0,O=_;for(f<d[0]&&(p=0,I=O+1);I<=O;)if(T=I+Math.floor((O-I)/2),T===_||f>=d[T]&&f<d[T+1]){p=T;break}else d[T]<f?I=T+1:O=T-1;return p}}var si=ei;function di(Ee,d,f){let p=Ee;if(d+f<p.length){for(;f--;)if((p[++d]&192)!==128)return!1;return!0}else return!1}function Ai(Ee){let d=[],f=Ee,p=0,_=Ee.length;for(;p<_;){if(f[p]<128){d.push(String.fromCharCode(f[p])),++p;continue}else if(!(f[p]<192)){if(f[p]<224){if(di(f,p,1)){let T=(f[p]&31)<<6|f[p+1]&63;if(T>=128){d.push(String.fromCharCode(T&65535)),p+=2;continue}}}else if(f[p]<240){if(di(f,p,2)){let T=(f[p]&15)<<12|(f[p+1]&63)<<6|f[p+2]&63;if(T>=2048&&(T&63488)!==55296){d.push(String.fromCharCode(T&65535)),p+=3;continue}}}else if(f[p]<248&&di(f,p,3)){let T=(f[p]&7)<<18|(f[p+1]&63)<<12|(f[p+2]&63)<<6|f[p+3]&63;if(T>65536&&T<1114112){T-=65536,d.push(String.fromCharCode(T>>>10|55296)),d.push(String.fromCharCode(T&1023|56320)),p+=4;continue}}}d.push("\uFFFD"),++p}return d.join("")}var hi=Ai;let St=function(){let Ee=new ArrayBuffer(2);return new DataView(Ee).setInt16(0,256,!0),new Int16Array(Ee)[0]===256}();class qt{static parseScriptData(d,f,p){let _={};try{let T=qt.parseValue(d,f,p),I=qt.parseValue(d,f+T.size,p-T.size);_[T.data]=I.data}catch(T){g.e("AMF",T.toString())}return _}static parseObject(d,f,p){if(p<3)throw new ot("Data not enough when parse ScriptDataObject");let _=qt.parseString(d,f,p),T=qt.parseValue(d,f+_.size,p-_.size),I=T.objectEnd;return{data:{name:_.data,value:T.data},size:_.size+T.size,objectEnd:I}}static parseVariable(d,f,p){return qt.parseObject(d,f,p)}static parseString(d,f,p){if(p<2)throw new ot("Data not enough when parse String");let T=new DataView(d,f,p).getUint16(0,!St),I;return T>0?I=hi(new Uint8Array(d,f+2,T)):I="",{data:I,size:2+T}}static parseLongString(d,f,p){if(p<4)throw new ot("Data not enough when parse LongString");let T=new DataView(d,f,p).getUint32(0,!St),I;return T>0?I=hi(new Uint8Array(d,f+4,T)):I="",{data:I,size:4+T}}static parseDate(d,f,p){if(p<10)throw new ot("Data size invalid when parse Date");let _=new DataView(d,f,p),T=_.getFloat64(0,!St),I=_.getInt16(8,!St);return T+=I*60*1e3,{data:new Date(T),size:10}}static parseValue(d,f,p){if(p<1)throw new ot("Data not enough when parse Value");let _=new DataView(d,f,p),T=1,I=_.getUint8(0),O,be=!1;try{switch(I){case 0:O=_.getFloat64(1,!St),T+=8;break;case 1:{O=!!_.getUint8(1),T+=1;break}case 2:{let _e=qt.parseString(d,f+1,p-1);O=_e.data,T+=_e.size;break}case 3:{O={};let _e=0;for((_.getUint32(p-4,!St)&16777215)===9&&(_e=3);T<p-4;){let Me=qt.parseObject(d,f+T,p-T-_e);if(Me.objectEnd)break;O[Me.data.name]=Me.data.value,T+=Me.size}T<=p-3&&(_.getUint32(T-1,!St)&16777215)===9&&(T+=3);break}case 8:{O={},T+=4;let _e=0;for((_.getUint32(p-4,!St)&16777215)===9&&(_e=3);T<p-8;){let Me=qt.parseVariable(d,f+T,p-T-_e);if(Me.objectEnd)break;O[Me.data.name]=Me.data.value,T+=Me.size}T<=p-3&&(_.getUint32(T-1,!St)&16777215)===9&&(T+=3);break}case 9:O=void 0,T=1,be=!0;break;case 10:{O=[];let _e=_.getUint32(1,!St);T+=4;for(let Me=0;Me<_e;Me++){let It=qt.parseValue(d,f+T,p-T);O.push(It.data),T+=It.size}break}case 11:{let _e=qt.parseDate(d,f+1,p-1);O=_e.data,T+=_e.size;break}case 12:{let _e=qt.parseString(d,f+1,p-1);O=_e.data,T+=_e.size;break}default:T=p,g.w("AMF","Unsupported AMF value type "+I)}}catch(_e){g.e("AMF",_e.toString())}return{data:O,size:T,objectEnd:be}}}var We=qt;class Oi{constructor(d){this.TAG="ExpGolomb",this._buffer=d,this._buffer_index=0,this._total_bytes=d.byteLength,this._total_bits=d.byteLength*8,this._current_word=0,this._current_word_bits_left=0}destroy(){this._buffer=null}_fillCurrentWord(){let d=this._total_bytes-this._buffer_index;if(d<=0)throw new ot("ExpGolomb: _fillCurrentWord() but no bytes available");let f=Math.min(4,d),p=new Uint8Array(4);p.set(this._buffer.subarray(this._buffer_index,this._buffer_index+f)),this._current_word=new DataView(p.buffer).getUint32(0,!1),this._buffer_index+=f,this._current_word_bits_left=f*8}readBits(d){if(d>32)throw new at("ExpGolomb: readBits() bits exceeded max 32bits!");if(d<=this._current_word_bits_left){let I=this._current_word>>>32-d;return this._current_word<<=d,this._current_word_bits_left-=d,I}let f=this._current_word_bits_left?this._current_word:0;f=f>>>32-this._current_word_bits_left;let p=d-this._current_word_bits_left;this._fillCurrentWord();let _=Math.min(p,this._current_word_bits_left),T=this._current_word>>>32-_;return this._current_word<<=_,this._current_word_bits_left-=_,f=f<<_|T,f}readBool(){return this.readBits(1)===1}readByte(){return this.readBits(8)}_skipLeadingZero(){let d;for(d=0;d<this._current_word_bits_left;d++)if(this._current_word&2147483648>>>d)return this._current_word<<=d,this._current_word_bits_left-=d,d;return this._fillCurrentWord(),d+this._skipLeadingZero()}readUEG(){let d=this._skipLeadingZero();return this.readBits(d+1)-1}readSEG(){let d=this.readUEG();return d&1?d+1>>>1:-1*(d>>>1)}}var Q=Oi;class Te{static _ebsp2rbsp(d){let f=d,p=f.byteLength,_=new Uint8Array(p),T=0;for(let I=0;I<p;I++)I>=2&&f[I]===3&&f[I-1]===0&&f[I-2]===0||(_[T]=f[I],T++);return new Uint8Array(_.buffer,0,T)}static parseSPS(d){let f=Te._ebsp2rbsp(d),p=new Q(f);p.readByte();let _=p.readByte();p.readByte();let T=p.readByte();p.readUEG();let I=Te.getProfileString(_),O=Te.getLevelString(T),be=1,_e=420,Me=[0,420,422,444],It=8;if((_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128||_===138||_===144)&&(be=p.readUEG(),be===3&&p.readBits(1),be<=3&&(_e=Me[be]),It=p.readUEG()+8,p.readUEG(),p.readBits(1),p.readBool())){let nt=be!==3?8:12;for(let Pt=0;Pt<nt;Pt++)p.readBool()&&(Pt<6?Te._skipScalingList(p,16):Te._skipScalingList(p,64))}p.readUEG();let ht=p.readUEG();if(ht===0)p.readUEG();else if(ht===1){p.readBits(1),p.readSEG(),p.readSEG();let nt=p.readUEG();for(let Pt=0;Pt<nt;Pt++)p.readSEG()}let we=p.readUEG();p.readBits(1);let gt=p.readUEG(),$e=p.readUEG(),Se=p.readBits(1);Se===0&&p.readBits(1),p.readBits(1);let ve=0,et=0,qe=0,Yt=0;p.readBool()&&(ve=p.readUEG(),et=p.readUEG(),qe=p.readUEG(),Yt=p.readUEG());let mi=1,Ce=1,ze=0,it=!0,k=0,H=0;if(p.readBool()){if(p.readBool()){let nt=p.readByte(),Pt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Ct=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];nt>0&&nt<16?(mi=Pt[nt-1],Ce=Ct[nt-1]):nt===255&&(mi=p.readByte()<<8|p.readByte(),Ce=p.readByte()<<8|p.readByte())}if(p.readBool()&&p.readBool(),p.readBool()&&(p.readBits(4),p.readBool()&&p.readBits(24)),p.readBool()&&(p.readUEG(),p.readUEG()),p.readBool()){let nt=p.readBits(32),Pt=p.readBits(32);it=p.readBool(),k=Pt,H=nt*2,ze=k/H}}let q=1;(mi!==1||Ce!==1)&&(q=mi/Ce);let le=0,ye=0;if(be===0)le=1,ye=2-Se;else{let nt=be===3?1:2,Pt=be===1?2:1;le=nt,ye=Pt*(2-Se)}let Le=(gt+1)*16,Ke=(2-Se)*(($e+1)*16);Le-=(ve+et)*le,Ke-=(qe+Yt)*ye;let Ut=Math.ceil(Le*q);return p.destroy(),p=null,{profile_string:I,level_string:O,bit_depth:It,ref_frames:we,chroma_format:_e,chroma_format_string:Te.getChromaFormatString(_e),frame_rate:{fixed:it,fps:ze,fps_den:H,fps_num:k},sar_ratio:{width:mi,height:Ce},codec_size:{width:Le,height:Ke},present_size:{width:Ut,height:Ke}}}static _skipScalingList(d,f){let p=8,_=8,T=0;for(let I=0;I<f;I++)_!==0&&(T=d.readSEG(),_=(p+T+256)%256),p=_===0?p:_}static getProfileString(d){switch(d){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}}static getLevelString(d){return(d/10).toFixed(1)}static getChromaFormatString(d){switch(d){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}}}var B=Te,Oe={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"};function Ze(Ee){return Ee>>>8&255|(Ee&255)<<8}function mt(Ee){return(Ee&4278190080)>>>24|(Ee&16711680)>>>8|(Ee&65280)<<8|(Ee&255)<<24}function G(Ee,d){return Ee[d]<<24|Ee[d+1]<<16|Ee[d+2]<<8|Ee[d+3]}class ee{constructor(d,f){this.TAG="FLVDemuxer",this._config=f,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=d.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=d.hasAudioTrack,this._hasVideo=d.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new si,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1e3,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1e3},this._flvSoundRateTable=[5500,11025,22050,44100,48e3],this._mpegSamplingRates=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],this._mpegAudioV10SampleRateTable=[44100,48e3,32e3,0],this._mpegAudioV20SampleRateTable=[22050,24e3,16e3,0],this._mpegAudioV25SampleRateTable=[11025,12e3,8e3,0],this._mpegAudioL1BitRateTable=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],this._mpegAudioL2BitRateTable=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],this._mpegAudioL3BitRateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],this._videoTrack={type:"video",id:1,sequenceNumber:0,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},this._littleEndian=function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]===256}()}destroy(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null}static probe(d){let f=new Uint8Array(d),p={match:!1};if(f[0]!==70||f[1]!==76||f[2]!==86||f[3]!==1)return p;let _=(f[4]&4)>>>2!==0,T=(f[4]&1)!==0,I=G(f,5);return I<9?p:{match:!0,consumed:I,dataOffset:I,hasAudioTrack:_,hasVideoTrack:T}}bindDataSource(d){return d.onDataArrival=this.parseChunks.bind(this),this}get onTrackMetadata(){return this._onTrackMetadata}set onTrackMetadata(d){this._onTrackMetadata=d}get onMediaInfo(){return this._onMediaInfo}set onMediaInfo(d){this._onMediaInfo=d}get onMetaDataArrived(){return this._onMetaDataArrived}set onMetaDataArrived(d){this._onMetaDataArrived=d}get onScriptDataArrived(){return this._onScriptDataArrived}set onScriptDataArrived(d){this._onScriptDataArrived=d}get onError(){return this._onError}set onError(d){this._onError=d}get onDataAvailable(){return this._onDataAvailable}set onDataAvailable(d){this._onDataAvailable=d}get timestampBase(){return this._timestampBase}set timestampBase(d){this._timestampBase=d}get overridedDuration(){return this._duration}set overridedDuration(d){this._durationOverrided=!0,this._duration=d,this._mediaInfo.duration=d}set overridedHasAudio(d){this._hasAudioFlagOverrided=!0,this._hasAudio=d,this._mediaInfo.hasAudio=d}set overridedHasVideo(d){this._hasVideoFlagOverrided=!0,this._hasVideo=d,this._mediaInfo.hasVideo=d}resetMediaInfo(){this._mediaInfo=new si}_isInitialMetadataDispatched(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!this._hasAudio&&this._hasVideo?this._videoInitialMetadataDispatched:!1}parseChunks(d,f){if(!this._onError||!this._onMediaInfo||!this._onTrackMetadata||!this._onDataAvailable)throw new ot("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");let p=0,_=this._littleEndian;if(f===0)if(d.byteLength>13)p=ee.probe(d).dataOffset;else return 0;for(this._firstParse&&(this._firstParse=!1,f+p!==this._dataOffset&&g.w(this.TAG,"First time parsing but chunk byteStart invalid!"),new DataView(d,p).getUint32(0,!_)!==0&&g.w(this.TAG,"PrevTagSize0 !== 0 !!!"),p+=4);p<d.byteLength;){this._dispatch=!0;let T=new DataView(d,p);if(p+11+4>d.byteLength)break;let I=T.getUint8(0),O=T.getUint32(0,!_)&16777215;if(p+11+O+4>d.byteLength)break;if(I!==8&&I!==9&&I!==18){g.w(this.TAG,`Unsupported tag type ${I}, skipped`),p+=11+O+4;continue}let be=T.getUint8(4),_e=T.getUint8(5),Me=T.getUint8(6),It=T.getUint8(7),ht=Me|_e<<8|be<<16|It<<24;(T.getUint32(7,!_)&16777215)!==0&&g.w(this.TAG,"Meet tag which has StreamID != 0!");let gt=p+11;switch(I){case 8:this._parseAudioData(d,gt,O,ht);break;case 9:this._parseVideoData(d,gt,O,ht,f+p);break;case 18:this._parseScriptData(d,gt,O);break}let $e=T.getUint32(11+O,!_);$e!==11+O&&g.w(this.TAG,`Invalid PrevTagSize ${$e}`),p+=11+O+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),p}_parseScriptData(d,f,p){let _=We.parseScriptData(d,f,p);if(_.hasOwnProperty("onMetaData")){if(_.onMetaData==null||typeof _.onMetaData!="object"){g.w(this.TAG,"Invalid onMetaData structure!");return}this._metadata&&g.w(this.TAG,"Found another onMetaData tag!"),this._metadata=_;let T=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},T)),typeof T.hasAudio=="boolean"&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=T.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),typeof T.hasVideo=="boolean"&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=T.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),typeof T.audiodatarate=="number"&&(this._mediaInfo.audioDataRate=T.audiodatarate),typeof T.videodatarate=="number"&&(this._mediaInfo.videoDataRate=T.videodatarate),typeof T.width=="number"&&(this._mediaInfo.width=T.width),typeof T.height=="number"&&(this._mediaInfo.height=T.height),typeof T.duration=="number"){if(!this._durationOverrided){let I=Math.floor(T.duration*this._timescale);this._duration=I,this._mediaInfo.duration=I}}else this._mediaInfo.duration=0;if(typeof T.framerate=="number"){let I=Math.floor(T.framerate*1e3);if(I>0){let O=I/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=O,this._referenceFrameRate.fps_num=I,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=O}}if(typeof T.keyframes=="object"){this._mediaInfo.hasKeyframesIndex=!0;let I=T.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(I),T.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=T,g.v(this.TAG,"Parsed onMetaData"),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo)}Object.keys(_).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},_))}_parseKeyframesIndex(d){let f=[],p=[];for(let _=1;_<d.times.length;_++){let T=this._timestampBase+Math.floor(d.times[_]*1e3);f.push(T),p.push(d.filepositions[_])}return{times:f,filepositions:p}}_parseAudioData(d,f,p,_){if(p<=1){g.w(this.TAG,"Flv: Invalid audio packet, missing SoundData payload!");return}if(this._hasAudioFlagOverrided===!0&&this._hasAudio===!1)return;let T=this._littleEndian,O=new DataView(d,f,p).getUint8(0),be=O>>>4;if(be!==2&&be!==10){this._onError(Oe.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+be);return}let _e=0,Me=(O&12)>>>2;if(Me>=0&&Me<=4)_e=this._flvSoundRateTable[Me];else{this._onError(Oe.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+Me);return}let It=(O&2)>>>1,ht=O&1,we=this._audioMetadata,gt=this._audioTrack;if(we||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),we=this._audioMetadata={},we.type="audio",we.id=gt.id,we.timescale=this._timescale,we.duration=this._duration,we.audioSampleRate=_e,we.channelCount=ht===0?1:2),be===10){let $e=this._parseAACAudioData(d,f+1,p-1);if($e==null)return;if($e.packetType===0){we.config&&g.w(this.TAG,"Found another AudioSpecificConfig!");let Se=$e.data;we.audioSampleRate=Se.samplingRate,we.channelCount=Se.channelCount,we.codec=Se.codec,we.originalCodec=Se.originalCodec,we.config=Se.config,we.refSampleDuration=1024/we.audioSampleRate*we.timescale,g.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",we);let ve=this._mediaInfo;ve.audioCodec=we.originalCodec,ve.audioSampleRate=we.audioSampleRate,ve.audioChannelCount=we.channelCount,ve.hasVideo?ve.videoCodec!=null&&(ve.mimeType='video/x-flv; codecs="'+ve.videoCodec+","+ve.audioCodec+'"'):ve.mimeType='video/x-flv; codecs="'+ve.audioCodec+'"',ve.isComplete()&&this._onMediaInfo(ve)}else if($e.packetType===1){let Se=this._timestampBase+_,ve={unit:$e.data,length:$e.data.byteLength,dts:Se,pts:Se};gt.samples.push(ve),gt.length+=$e.data.length}else g.e(this.TAG,`Flv: Unsupported AAC data type ${$e.packetType}`)}else if(be===2){if(!we.codec){let et=this._parseMP3AudioData(d,f+1,p-1,!0);if(et==null)return;we.audioSampleRate=et.samplingRate,we.channelCount=et.channelCount,we.codec=et.codec,we.originalCodec=et.originalCodec,we.refSampleDuration=1152/we.audioSampleRate*we.timescale,g.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",we);let qe=this._mediaInfo;qe.audioCodec=we.codec,qe.audioSampleRate=we.audioSampleRate,qe.audioChannelCount=we.channelCount,qe.audioDataRate=et.bitRate,qe.hasVideo?qe.videoCodec!=null&&(qe.mimeType='video/x-flv; codecs="'+qe.videoCodec+","+qe.audioCodec+'"'):qe.mimeType='video/x-flv; codecs="'+qe.audioCodec+'"',qe.isComplete()&&this._onMediaInfo(qe)}let $e=this._parseMP3AudioData(d,f+1,p-1,!1);if($e==null)return;let Se=this._timestampBase+_,ve={unit:$e,length:$e.byteLength,dts:Se,pts:Se};gt.samples.push(ve),gt.length+=$e.length}}_parseAACAudioData(d,f,p){if(p<=1){g.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!");return}let _={},T=new Uint8Array(d,f,p);return _.packetType=T[0],T[0]===0?_.data=this._parseAACAudioSpecificConfig(d,f+1,p-1):_.data=T.subarray(1),_}_parseAACAudioSpecificConfig(d,f,p){let _=new Uint8Array(d,f,p),T=null,I=0,O=0,be=null,_e=0,Me=null;if(I=O=_[0]>>>3,_e=(_[0]&7)<<1|_[1]>>>7,_e<0||_e>=this._mpegSamplingRates.length){this._onError(Oe.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");return}let It=this._mpegSamplingRates[_e],ht=(_[1]&120)>>>3;if(ht<0||ht>=8){this._onError(Oe.FORMAT_ERROR,"Flv: AAC invalid channel configuration");return}I===5&&(Me=(_[1]&7)<<1|_[2]>>>7,be=(_[2]&124)>>>2);let we=self.navigator.userAgent.toLowerCase();return we.indexOf("firefox")!==-1?_e>=6?(I=5,T=new Array(4),Me=_e-3):(I=2,T=new Array(2),Me=_e):we.indexOf("android")!==-1?(I=2,T=new Array(2),Me=_e):(I=5,Me=_e,T=new Array(4),_e>=6?Me=_e-3:ht===1&&(I=2,T=new Array(2),Me=_e)),T[0]=I<<3,T[0]|=(_e&15)>>>1,T[1]=(_e&15)<<7,T[1]|=(ht&15)<<3,I===5&&(T[1]|=(Me&15)>>>1,T[2]=(Me&1)<<7,T[2]|=8,T[3]=0),{config:T,samplingRate:It,channelCount:ht,codec:"mp4a.40."+I,originalCodec:"mp4a.40."+O}}_parseMP3AudioData(d,f,p,_){if(p<4){g.w(this.TAG,"Flv: Invalid MP3 packet, header missing!");return}let T=this._littleEndian,I=new Uint8Array(d,f,p),O=null;if(_){if(I[0]!==255)return;let be=I[1]>>>3&3,_e=(I[1]&6)>>1,Me=(I[2]&240)>>>4,It=(I[2]&12)>>>2,we=(I[3]>>>6&3)!==3?2:1,gt=0,$e=0,Se=34,ve="mp3";switch(be){case 0:gt=this._mpegAudioV25SampleRateTable[It];break;case 2:gt=this._mpegAudioV20SampleRateTable[It];break;case 3:gt=this._mpegAudioV10SampleRateTable[It];break}switch(_e){case 1:Se=34,Me<this._mpegAudioL3BitRateTable.length&&($e=this._mpegAudioL3BitRateTable[Me]);break;case 2:Se=33,Me<this._mpegAudioL2BitRateTable.length&&($e=this._mpegAudioL2BitRateTable[Me]);break;case 3:Se=32,Me<this._mpegAudioL1BitRateTable.length&&($e=this._mpegAudioL1BitRateTable[Me]);break}O={bitRate:$e,samplingRate:gt,channelCount:we,codec:ve,originalCodec:ve}}else O=I;return O}_parseVideoData(d,f,p,_,T){if(p<=1){g.w(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");return}if(this._hasVideoFlagOverrided===!0&&this._hasVideo===!1)return;let I=new Uint8Array(d,f,p)[0],O=(I&240)>>>4,be=I&15;if(be!==7){this._onError(Oe.CODEC_UNSUPPORTED,`Flv: Unsupported codec in video frame: ${be}`);return}this._parseAVCVideoPacket(d,f+1,p-1,_,T,O)}_parseAVCVideoPacket(d,f,p,_,T,I){if(p<4){g.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");return}let O=this._littleEndian,be=new DataView(d,f,p),_e=be.getUint8(0),It=(be.getUint32(0,!O)&16777215)<<8>>8;if(_e===0)this._parseAVCDecoderConfigurationRecord(d,f+4,p-4);else if(_e===1)this._parseAVCVideoData(d,f+4,p-4,_,T,I,It);else if(_e!==2){this._onError(Oe.FORMAT_ERROR,`Flv: Invalid video packet type ${_e}`);return}}_parseAVCDecoderConfigurationRecord(d,f,p){if(p<7){g.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");return}let _=this._videoMetadata,T=this._videoTrack,I=this._littleEndian,O=new DataView(d,f,p);_?typeof _.avcc!="undefined"&&g.w(this.TAG,"Found another AVCDecoderConfigurationRecord!"):(this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),_=this._videoMetadata={},_.type="video",_.id=T.id,_.timescale=this._timescale,_.duration=this._duration);let be=O.getUint8(0),_e=O.getUint8(1),Me=O.getUint8(2),It=O.getUint8(3);if(be!==1||_e===0){this._onError(Oe.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord");return}if(this._naluLengthSize=(O.getUint8(4)&3)+1,this._naluLengthSize!==3&&this._naluLengthSize!==4){this._onError(Oe.FORMAT_ERROR,`Flv: Strange NaluLengthSizeMinusOne: ${this._naluLengthSize-1}`);return}let ht=O.getUint8(5)&31;if(ht===0){this._onError(Oe.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No SPS");return}else ht>1&&g.w(this.TAG,`Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ${ht}`);let we=6;for(let $e=0;$e<ht;$e++){let Se=O.getUint16(we,!I);if(we+=2,Se===0)continue;let ve=new Uint8Array(d,f+we,Se);we+=Se;let et=B.parseSPS(ve);if($e!==0)continue;_.codecWidth=et.codec_size.width,_.codecHeight=et.codec_size.height,_.presentWidth=et.present_size.width,_.presentHeight=et.present_size.height,_.profile=et.profile_string,_.level=et.level_string,_.bitDepth=et.bit_depth,_.chromaFormat=et.chroma_format,_.sarRatio=et.sar_ratio,_.frameRate=et.frame_rate,(et.frame_rate.fixed===!1||et.frame_rate.fps_num===0||et.frame_rate.fps_den===0)&&(_.frameRate=this._referenceFrameRate);let qe=_.frameRate.fps_den,Yt=_.frameRate.fps_num;_.refSampleDuration=_.timescale*(qe/Yt);let fi=ve.subarray(1,4),mi="avc1.";for(let ze=0;ze<3;ze++){let it=fi[ze].toString(16);it.length<2&&(it="0"+it),mi+=it}_.codec=mi;let Ce=this._mediaInfo;Ce.width=_.codecWidth,Ce.height=_.codecHeight,Ce.fps=_.frameRate.fps,Ce.profile=_.profile,Ce.level=_.level,Ce.refFrames=et.ref_frames,Ce.chromaFormat=et.chroma_format_string,Ce.sarNum=_.sarRatio.width,Ce.sarDen=_.sarRatio.height,Ce.videoCodec=mi,Ce.hasAudio?Ce.audioCodec!=null&&(Ce.mimeType='video/x-flv; codecs="'+Ce.videoCodec+","+Ce.audioCodec+'"'):Ce.mimeType='video/x-flv; codecs="'+Ce.videoCodec+'"',Ce.isComplete()&&this._onMediaInfo(Ce)}let gt=O.getUint8(we);if(gt===0){this._onError(Oe.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No PPS");return}else gt>1&&g.w(this.TAG,`Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ${gt}`);we++;for(let $e=0;$e<gt;$e++){let Se=O.getUint16(we,!I);we+=2,Se!==0&&(we+=Se)}_.avcc=new Uint8Array(p),_.avcc.set(new Uint8Array(d,f,p),0),g.v(this.TAG,"Parsed AVCDecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",_)}_parseAVCVideoData(d,f,p,_,T,I,O){let be=this._littleEndian,_e=new DataView(d,f,p),Me=[],It=0,ht=0;const we=this._naluLengthSize;let gt=this._timestampBase+_,$e=I===1;for(;ht<p;){if(ht+4>=p){g.w(this.TAG,`Malformed Nalu near timestamp ${gt}, offset = ${ht}, dataSize = ${p}`);break}let Se=_e.getUint32(ht,!be);if(we===3&&(Se>>>=8),Se>p-we){g.w(this.TAG,`Malformed Nalus near timestamp ${gt}, NaluSize > DataSize!`);return}let ve=_e.getUint8(ht+we)&31;ve===5&&($e=!0);let et=new Uint8Array(d,f+ht,we+Se),qe={type:ve,data:et};Me.push(qe),It+=et.byteLength,ht+=we+Se}if(Me.length){let Se=this._videoTrack,ve={units:Me,length:It,isKeyframe:$e,dts:gt,cts:O,pts:gt+O};$e&&(ve.fileposition=T),Se.samples.push(ve),Se.length+=It}}}var se=ee;class w{static init(){w.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[],".mp3":[]};for(let f in w.types)w.types.hasOwnProperty(f)&&(w.types[f]=[f.charCodeAt(0),f.charCodeAt(1),f.charCodeAt(2),f.charCodeAt(3)]);let d=w.constants={};d.FTYP=new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),d.STSD_PREFIX=new Uint8Array([0,0,0,0,0,0,0,1]),d.STTS=new Uint8Array([0,0,0,0,0,0,0,0]),d.STSC=d.STCO=d.STTS,d.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),d.HDLR_VIDEO=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]),d.HDLR_AUDIO=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.DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),d.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),d.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}static box(d){let f=8,p=null,_=Array.prototype.slice.call(arguments,1),T=_.length;for(let O=0;O<T;O++)f+=_[O].byteLength;p=new Uint8Array(f),p[0]=f>>>24&255,p[1]=f>>>16&255,p[2]=f>>>8&255,p[3]=f&255,p.set(d,4);let I=8;for(let O=0;O<T;O++)p.set(_[O],I),I+=_[O].byteLength;return p}static generateInitSegment(d){let f=w.box(w.types.ftyp,w.constants.FTYP),p=w.moov(d),_=new Uint8Array(f.byteLength+p.byteLength);return _.set(f,0),_.set(p,f.byteLength),_}static moov(d){let f=w.mvhd(d.timescale,d.duration),p=w.trak(d),_=w.mvex(d);return w.box(w.types.moov,f,p,_)}static mvhd(d,f){return w.box(w.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,d>>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&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]))}static trak(d){return w.box(w.types.trak,w.tkhd(d),w.mdia(d))}static tkhd(d){let f=d.id,p=d.duration,_=d.presentWidth,T=d.presentHeight;return w.box(w.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,f>>>24&255,f>>>16&255,f>>>8&255,f&255,0,0,0,0,p>>>24&255,p>>>16&255,p>>>8&255,p&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,_>>>8&255,_&255,0,0,T>>>8&255,T&255,0,0]))}static mdia(d){return w.box(w.types.mdia,w.mdhd(d),w.hdlr(d),w.minf(d))}static mdhd(d){let f=d.timescale,p=d.duration;return w.box(w.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,f>>>24&255,f>>>16&255,f>>>8&255,f&255,p>>>24&255,p>>>16&255,p>>>8&255,p&255,85,196,0,0]))}static hdlr(d){let f=null;return d.type==="audio"?f=w.constants.HDLR_AUDIO:f=w.constants.HDLR_VIDEO,w.box(w.types.hdlr,f)}static minf(d){let f=null;return d.type==="audio"?f=w.box(w.types.smhd,w.constants.SMHD):f=w.box(w.types.vmhd,w.constants.VMHD),w.box(w.types.minf,f,w.dinf(),w.stbl(d))}static dinf(){return w.box(w.types.dinf,w.box(w.types.dref,w.constants.DREF))}static stbl(d){return w.box(w.types.stbl,w.stsd(d),w.box(w.types.stts,w.constants.STTS),w.box(w.types.stsc,w.constants.STSC),w.box(w.types.stsz,w.constants.STSZ),w.box(w.types.stco,w.constants.STCO))}static stsd(d){return d.type==="audio"?d.codec==="mp3"?w.box(w.types.stsd,w.constants.STSD_PREFIX,w.mp3(d)):w.box(w.types.stsd,w.constants.STSD_PREFIX,w.mp4a(d)):w.box(w.types.stsd,w.constants.STSD_PREFIX,w.avc1(d))}static mp3(d){let f=d.channelCount,p=d.audioSampleRate,_=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,f,0,16,0,0,0,0,p>>>8&255,p&255,0,0]);return w.box(w.types[".mp3"],_)}static mp4a(d){let f=d.channelCount,p=d.audioSampleRate,_=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,f,0,16,0,0,0,0,p>>>8&255,p&255,0,0]);return w.box(w.types.mp4a,_,w.esds(d))}static esds(d){let f=d.config||[],p=f.length,_=new Uint8Array([0,0,0,0,3,23+p,0,1,0,4,15+p,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([p]).concat(f).concat([6,1,2]));return w.box(w.types.esds,_)}static avc1(d){let f=d.avcc,p=d.codecWidth,_=d.codecHeight,T=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,p>>>8&255,p&255,_>>>8&255,_&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return w.box(w.types.avc1,T,w.box(w.types.avcC,f))}static mvex(d){return w.box(w.types.mvex,w.trex(d))}static trex(d){let f=d.id,p=new Uint8Array([0,0,0,0,f>>>24&255,f>>>16&255,f>>>8&255,f&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return w.box(w.types.trex,p)}static moof(d,f){return w.box(w.types.moof,w.mfhd(d.sequenceNumber),w.traf(d,f))}static mfhd(d){let f=new Uint8Array([0,0,0,0,d>>>24&255,d>>>16&255,d>>>8&255,d&255]);return w.box(w.types.mfhd,f)}static traf(d,f){let p=d.id,_=w.box(w.types.tfhd,new Uint8Array([0,0,0,0,p>>>24&255,p>>>16&255,p>>>8&255,p&255])),T=w.box(w.types.tfdt,new Uint8Array([0,0,0,0,f>>>24&255,f>>>16&255,f>>>8&255,f&255])),I=w.sdtp(d),O=w.trun(d,I.byteLength+16+16+8+16+8+8);return w.box(w.types.traf,_,T,O,I)}static sdtp(d){let f=d.samples||[],p=f.length,_=new Uint8Array(4+p);for(let T=0;T<p;T++){let I=f[T].flags;_[T+4]=I.isLeading<<6|I.dependsOn<<4|I.isDependedOn<<2|I.hasRedundancy}return w.box(w.types.sdtp,_)}static trun(d,f){let p=d.samples||[],_=p.length,T=12+16*_,I=new Uint8Array(T);f+=8+T,I.set([0,0,15,1,_>>>24&255,_>>>16&255,_>>>8&255,_&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255],0);for(let O=0;O<_;O++){let be=p[O].duration,_e=p[O].size,Me=p[O].flags,It=p[O].cts;I.set([be>>>24&255,be>>>16&255,be>>>8&255,be&255,_e>>>24&255,_e>>>16&255,_e>>>8&255,_e&255,Me.isLeading<<2|Me.dependsOn,Me.isDependedOn<<6|Me.hasRedundancy<<4|Me.isNonSync,0,0,It>>>24&255,It>>>16&255,It>>>8&255,It&255],12+16*O)}return w.box(w.types.trun,I)}static mdat(d){return w.box(w.types.mdat,d)}}w.init();var Ae=w;class Je{static getSilentFrame(d,f){if(d==="mp4a.40.2"){if(f===1)return new Uint8Array([0,200,0,128,35,128]);if(f===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(f===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(f===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(f===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(f===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])}else{if(f===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(f===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(f===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])}return null}}var je=Je;class Vt{constructor(d,f,p,_,T){this.dts=d,this.pts=f,this.duration=p,this.originalDts=_,this.isSyncPoint=T,this.fileposition=null}}class Bt{constructor(){this.beginDts=0,this.endDts=0,this.beginPts=0,this.endPts=0,this.originalBeginDts=0,this.originalEndDts=0,this.syncPoints=[],this.firstSample=null,this.lastSample=null}appendSyncPoint(d){d.isSyncPoint=!0,this.syncPoints.push(d)}}class Lt{constructor(){this._list=[]}clear(){this._list=[]}appendArray(d){let f=this._list;d.length!==0&&(f.length>0&&d[0].originalDts<f[f.length-1].originalDts&&this.clear(),Array.prototype.push.apply(f,d))}getLastSyncPointBeforeDts(d){if(this._list.length==0)return null;let f=this._list,p=0,_=f.length-1,T=0,I=0,O=_;for(d<f[0].dts&&(p=0,I=O+1);I<=O;)if(T=I+Math.floor((O-I)/2),T===_||d>=f[T].dts&&d<f[T+1].dts){p=T;break}else f[T].dts<d?I=T+1:O=T-1;return this._list[p]}}class Ht{constructor(d){this._type=d,this._list=[],this._lastAppendLocation=-1}get type(){return this._type}get length(){return this._list.length}isEmpty(){return this._list.length===0}clear(){this._list=[],this._lastAppendLocation=-1}_searchNearestSegmentBefore(d){let f=this._list;if(f.length===0)return-2;let p=f.length-1,_=0,T=0,I=p,O=0;if(d<f[0].originalBeginDts)return O=-1,O;for(;T<=I;)if(_=T+Math.floor((I-T)/2),_===p||d>f[_].lastSample.originalDts&&d<f[_+1].originalBeginDts){O=_;break}else f[_].originalBeginDts<d?T=_+1:I=_-1;return O}_searchNearestSegmentAfter(d){return this._searchNearestSegmentBefore(d)+1}append(d){let f=this._list,p=d,_=this._lastAppendLocation,T=0;_!==-1&&_<f.length&&p.originalBeginDts>=f[_].lastSample.originalDts&&(_===f.length-1||_<f.length-1&&p.originalBeginDts<f[_+1].originalBeginDts)?T=_+1:f.length>0&&(T=this._searchNearestSegmentBefore(p.originalBeginDts)+1),this._lastAppendLocation=T,this._list.splice(T,0,p)}getLastSegmentBefore(d){let f=this._searchNearestSegmentBefore(d);return f>=0?this._list[f]:null}getLastSampleBefore(d){let f=this.getLastSegmentBefore(d);return f!=null?f.lastSample:null}getLastSyncPointBefore(d){let f=this._searchNearestSegmentBefore(d),p=this._list[f].syncPoints;for(;p.length===0&&f>0;)f--,p=this._list[f].syncPoints;return p.length>0?p[p.length-1]:null}}class jt{constructor(d){this.TAG="MP4Remuxer",this._config=d,this._isLive=d.isLive===!0,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new Ht("audio"),this._videoSegmentInfoList=new Ht("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!!(fe.chrome&&(fe.version.major<50||fe.version.major===50&&fe.version.build<2661)),this._fillSilentAfterSeek=fe.msedge||fe.msie,this._mp3UseMpegAudio=!fe.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}destroy(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null}bindDataSource(d){return d.onDataAvailable=this.remux.bind(this),d.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this}get onInitSegment(){return this._onInitSegment}set onInitSegment(d){this._onInitSegment=d}get onMediaSegment(){return this._onMediaSegment}set onMediaSegment(d){this._onMediaSegment=d}insertDiscontinuity(){this._audioNextDts=this._videoNextDts=void 0}seek(d){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()}remux(d,f){if(!this._onMediaSegment)throw new ot("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(d,f),this._remuxVideo(f),this._remuxAudio(d)}_onTrackMetadataReceived(d,f){let p=null,_="mp4",T=f.codec;if(d==="audio")this._audioMeta=f,f.codec==="mp3"&&this._mp3UseMpegAudio?(_="mpeg",T="",p=new Uint8Array):p=Ae.generateInitSegment(f);else if(d==="video")this._videoMeta=f,p=Ae.generateInitSegment(f);else return;if(!this._onInitSegment)throw new ot("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(d,{type:d,data:p.buffer,codec:T,container:`${d}/${_}`,mediaDuration:f.duration})}_calculateDtsBase(d,f){this._dtsBaseInited||(d.samples&&d.samples.length&&(this._audioDtsBase=d.samples[0].dts),f.samples&&f.samples.length&&(this._videoDtsBase=f.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)}flushStashedSamples(){let d=this._videoStashedLastSample,f=this._audioStashedLastSample,p={type:"video",id:1,sequenceNumber:0,samples:[],length:0};d!=null&&(p.samples.push(d),p.length=d.length);let _={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};f!=null&&(_.samples.push(f),_.length=f.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(p,!0),this._remuxAudio(_,!0)}_remuxAudio(d,f){if(this._audioMeta==null)return;let p=d,_=p.samples,T,I=-1,O=-1,be=-1,_e=this._audioMeta.refSampleDuration,Me=this._audioMeta.codec==="mp3"&&this._mp3UseMpegAudio,It=this._dtsBaseInited&&this._audioNextDts===void 0,ht=!1;if(!_||_.length===0||_.length===1&&!f)return;let we=0,gt=null,$e=0;Me?(we=0,$e=p.length):(we=8,$e=8+p.length);let Se=null;if(_.length>1&&(Se=_.pop(),$e-=Se.length),this._audioStashedLastSample!=null){let Ce=this._audioStashedLastSample;this._audioStashedLastSample=null,_.unshift(Ce),$e+=Ce.length}Se!=null&&(this._audioStashedLastSample=Se);let ve=_[0].dts-this._dtsBase;if(this._audioNextDts)T=ve-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())T=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&this._audioMeta.originalCodec!=="mp3"&&(ht=!0);else{let Ce=this._audioSegmentInfoList.getLastSampleBefore(ve);if(Ce!=null){let ze=ve-(Ce.originalDts+Ce.duration);ze<=3&&(ze=0);let it=Ce.dts+Ce.duration+ze;T=ve-it}else T=0}if(ht){let Ce=ve-T,ze=this._videoSegmentInfoList.getLastSegmentBefore(ve);if(ze!=null&&ze.beginDts<Ce){let it=je.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);if(it){let k=ze.beginDts,H=Ce-ze.beginDts;g.v(this.TAG,`InsertPrefixSilentAudio: dts: ${k}, duration: ${H}`),_.unshift({unit:it,dts:k,pts:k}),$e+=it.byteLength}}else ht=!1}let et=[];for(let Ce=0;Ce<_.length;Ce++){let ze=_[Ce],it=ze.unit,k=ze.dts-this._dtsBase,H=k-T;I===-1&&(I=H);let ne=0;Ce!==_.length-1?ne=_[Ce+1].dts-this._dtsBase-T-H:Se!=null?ne=Se.dts-this._dtsBase-T-H:et.length>=1?ne=et[et.length-1].duration:ne=Math.floor(_e);let q=!1,le=null;if(ne>_e*1.5&&this._audioMeta.codec!=="mp3"&&this._fillAudioTimestampGap&&!fe.safari){q=!0;let ye=Math.abs(ne-_e),Le=Math.ceil(ye/_e),Ke=H+_e;g.w(this.TAG,`Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.
dts: ${H+ne} ms, expected: ${H+Math.round(_e)} ms, delta: ${Math.round(ye)} ms, generate: ${Le} frames`);let Ut=je.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount);Ut==null&&(g.w(this.TAG,`Unable to generate silent frame for ${this._audioMeta.originalCodec} with ${this._audioMeta.channelCount} channels, repeat last frame`),Ut=it),le=[];for(let Pt=0;Pt<Le;Pt++){let Ct=Math.round(Ke);if(le.length>0){let $t=le[le.length-1];$t.duration=Ct-$t.dts}let Dt={dts:Ct,pts:Ct,cts:0,unit:Ut,size:Ut.byteLength,duration:0,originalDts:k,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}};le.push(Dt),$e+=Dt.size,Ke+=_e}let nt=le[le.length-1];nt.duration=H+ne-nt.dts,ne=Math.round(_e)}et.push({dts:H,pts:H,cts:0,unit:ze.unit,size:ze.unit.byteLength,duration:ne,originalDts:k,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),q&&et.push.apply(et,le)}Me?gt=new Uint8Array($e):(gt=new Uint8Array($e),gt[0]=$e>>>24&255,gt[1]=$e>>>16&255,gt[2]=$e>>>8&255,gt[3]=$e&255,gt.set(Ae.types.mdat,4));for(let Ce=0;Ce<et.length;Ce++){let ze=et[Ce].unit;gt.set(ze,we),we+=ze.byteLength}let qe=et[et.length-1];O=qe.dts+qe.duration,this._audioNextDts=O;let Yt=new Bt;Yt.beginDts=I,Yt.endDts=O,Yt.beginPts=I,Yt.endPts=O,Yt.originalBeginDts=et[0].originalDts,Yt.originalEndDts=qe.originalDts+qe.duration,Yt.firstSample=new Vt(et[0].dts,et[0].pts,et[0].duration,et[0].originalDts,!1),Yt.lastSample=new Vt(qe.dts,qe.pts,qe.duration,qe.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(Yt),p.samples=et,p.sequenceNumber++;let fi=null;Me?fi=new Uint8Array:fi=Ae.moof(p,I),p.samples=[],p.length=0;let mi={type:"audio",data:this._mergeBoxes(fi,gt).buffer,sampleCount:et.length,info:Yt};Me&&It&&(mi.timestampOffset=I),this._onMediaSegment("audio",mi)}_remuxVideo(d,f){if(this._videoMeta==null)return;let p=d,_=p.samples,T,I=-1,O=-1,be=-1,_e=-1;if(!_||_.length===0||_.length===1&&!f)return;let Me=8,It=null,ht=8+d.length,we=null;if(_.length>1&&(we=_.pop(),ht-=we.length),this._videoStashedLastSample!=null){let qe=this._videoStashedLastSample;this._videoStashedLastSample=null,_.unshift(qe),ht+=qe.length}we!=null&&(this._videoStashedLastSample=we);let gt=_[0].dts-this._dtsBase;if(this._videoNextDts)T=gt-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())T=0;else{let qe=this._videoSegmentInfoList.getLastSampleBefore(gt);if(qe!=null){let Yt=gt-(qe.originalDts+qe.duration);Yt<=3&&(Yt=0);let fi=qe.dts+qe.duration+Yt;T=gt-fi}else T=0}let $e=new Bt,Se=[];for(let qe=0;qe<_.length;qe++){let Yt=_[qe],fi=Yt.dts-this._dtsBase,mi=Yt.isKeyframe,Ce=fi-T,ze=Yt.cts,it=Ce+ze;I===-1&&(I=Ce,be=it);let k=0;if(qe!==_.length-1?k=_[qe+1].dts-this._dtsBase-T-Ce:we!=null?k=we.dts-this._dtsBase-T-Ce:Se.length>=1?k=Se[Se.length-1].duration:k=Math.floor(this._videoMeta.refSampleDuration),mi){let H=new Vt(Ce,it,k,Yt.dts,!0);H.fileposition=Yt.fileposition,$e.appendSyncPoint(H)}Se.push({dts:Ce,pts:it,cts:ze,units:Yt.units,size:Yt.length,isKeyframe:mi,duration:k,originalDts:fi,flags:{isLeading:0,dependsOn:mi?2:1,isDependedOn:mi?1:0,hasRedundancy:0,isNonSync:mi?0:1}})}It=new Uint8Array(ht),It[0]=ht>>>24&255,It[1]=ht>>>16&255,It[2]=ht>>>8&255,It[3]=ht&255,It.set(Ae.types.mdat,4);for(let qe=0;qe<Se.length;qe++){let Yt=Se[qe].units;for(;Yt.length;){let mi=Yt.shift().data;It.set(mi,Me),Me+=mi.byteLength}}let ve=Se[Se.length-1];if(O=ve.dts+ve.duration,_e=ve.pts+ve.duration,this._videoNextDts=O,$e.beginDts=I,$e.endDts=O,$e.beginPts=be,$e.endPts=_e,$e.originalBeginDts=Se[0].originalDts,$e.originalEndDts=ve.originalDts+ve.duration,$e.firstSample=new Vt(Se[0].dts,Se[0].pts,Se[0].duration,Se[0].originalDts,Se[0].isKeyframe),$e.lastSample=new Vt(ve.dts,ve.pts,ve.duration,ve.originalDts,ve.isKeyframe),this._isLive||this._videoSegmentInfoList.append($e),p.samples=Se,p.sequenceNumber++,this._forceFirstIDR){let qe=Se[0].flags;qe.dependsOn=2,qe.isNonSync=0}let et=Ae.moof(p,I);p.samples=[],p.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(et,It).buffer,sampleCount:Se.length,info:$e})}_mergeBoxes(d,f){let p=new Uint8Array(d.byteLength+f.byteLength);return p.set(d,0),p.set(f,d.byteLength),p}}var Xt=jt,pe={IO_ERROR:"io_error",DEMUX_ERROR:"demux_error",INIT_SEGMENT:"init_segment",MEDIA_SEGMENT:"media_segment",LOADING_COMPLETE:"loading_complete",RECOVERED_EARLY_EOF:"recovered_early_eof",MEDIA_INFO:"media_info",METADATA_ARRIVED:"metadata_arrived",SCRIPTDATA_ARRIVED:"scriptdata_arrived",STATISTICS_INFO:"statistics_info",RECOMMEND_SEEKPOINT:"recommend_seekpoint"};class Ft{constructor(d,f){this.TAG="TransmuxingController",this._emitter=new(Z()),this._config=f,d.segments||(d.segments=[{duration:d.duration,filesize:d.filesize,url:d.url}]),typeof d.cors!="boolean"&&(d.cors=!0),typeof d.withCredentials!="boolean"&&(d.withCredentials=!1),this._mediaDataSource=d,this._currentSegmentIndex=0;let p=0;this._mediaDataSource.segments.forEach(_=>{_.timestampBase=p,p+=_.duration,_.cors=d.cors,_.withCredentials=d.withCredentials,f.referrerPolicy&&(_.referrerPolicy=f.referrerPolicy)}),!isNaN(p)&&this._mediaDataSource.duration!==p&&(this._mediaDataSource.duration=p),this._mediaInfo=null,this._demuxer=null,this._remuxer=null,this._ioctl=null,this._pendingSeekTime=null,this._pendingResolveSeekPoint=null,this._statisticsReporter=null}destroy(){this._mediaInfo=null,this._mediaDataSource=null,this._statisticsReporter&&this._disableStatisticsReporter(),this._ioctl&&(this._ioctl.destroy(),this._ioctl=null),this._demuxer&&(this._demuxer.destroy(),this._demuxer=null),this._remuxer&&(this._remuxer.destroy(),this._remuxer=null),this._emitter.removeAllListeners(),this._emitter=null}on(d,f){this._emitter.addListener(d,f)}off(d,f){this._emitter.removeListener(d,f)}start(){this._loadSegment(0),this._enableStatisticsReporter()}_loadSegment(d,f){this._currentSegmentIndex=d;let p=this._mediaDataSource.segments[d],_=this._ioctl=new ke(p,this._config,d);_.onError=this._onIOException.bind(this),_.onSeeked=this._onIOSeeked.bind(this),_.onComplete=this._onIOComplete.bind(this),_.onRedirect=this._onIORedirect.bind(this),_.onRecoveredEarlyEof=this._onIORecoveredEarlyEof.bind(this),f?this._demuxer.bindDataSource(this._ioctl):_.onDataArrival=this._onInitChunkArrival.bind(this),_.open(f)}stop(){this._internalAbort(),this._disableStatisticsReporter()}_internalAbort(){this._ioctl&&(this._ioctl.destroy(),this._ioctl=null)}pause(){this._ioctl&&this._ioctl.isWorking()&&(this._ioctl.pause(),this._disableStatisticsReporter())}resume(){this._ioctl&&this._ioctl.isPaused()&&(this._ioctl.resume(),this._enableStatisticsReporter())}seek(d){if(this._mediaInfo==null||!this._mediaInfo.isSeekable())return;let f=this._searchSegmentIndexContains(d);if(f===this._currentSegmentIndex){let p=this._mediaInfo.segments[f];if(p==null)this._pendingSeekTime=d;else{let _=p.getNearestKeyframe(d);this._remuxer.seek(_.milliseconds),this._ioctl.seek(_.fileposition),this._pendingResolveSeekPoint=_.milliseconds}}else{let p=this._mediaInfo.segments[f];if(p==null)this._pendingSeekTime=d,this._internalAbort(),this._remuxer.seek(),this._remuxer.insertDiscontinuity(),this._loadSegment(f);else{let _=p.getNearestKeyframe(d);this._internalAbort(),this._remuxer.seek(d),this._remuxer.insertDiscontinuity(),this._demuxer.resetMediaInfo(),this._demuxer.timestampBase=this._mediaDataSource.segments[f].timestampBase,this._loadSegment(f,_.fileposition),this._pendingResolveSeekPoint=_.milliseconds,this._reportSegmentMediaInfo(f)}}this._enableStatisticsReporter()}_searchSegmentIndexContains(d){let f=this._mediaDataSource.segments,p=f.length-1;for(let _=0;_<f.length;_++)if(d<f[_].timestampBase){p=_-1;break}return p}_onInitChunkArrival(d,f){let p=null,_=0;if(f>0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,_=this._demuxer.parseChunks(d,f);else if((p=se.probe(d)).match){this._demuxer=new se(p,this._config),this._remuxer||(this._remuxer=new Xt(this._config));let T=this._mediaDataSource;T.duration!=null&&!isNaN(T.duration)&&(this._demuxer.overridedDuration=T.duration),typeof T.hasAudio=="boolean"&&(this._demuxer.overridedHasAudio=T.hasAudio),typeof T.hasVideo=="boolean"&&(this._demuxer.overridedHasVideo=T.hasVideo),this._demuxer.timestampBase=T.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this),_=this._demuxer.parseChunks(d,f)}else p=null,g.e(this.TAG,"Non-FLV, Unsupported media type!"),Promise.resolve().then(()=>{this._internalAbort()}),this._emitter.emit(pe.DEMUX_ERROR,Oe.FORMAT_UNSUPPORTED,"Non-FLV, Unsupported media type"),_=0;return _}_onMediaInfo(d){this._mediaInfo==null&&(this._mediaInfo=Object.assign({},d),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,si.prototype));let f=Object.assign({},d);Object.setPrototypeOf(f,si.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=f,this._reportSegmentMediaInfo(this._currentSegmentIndex),this._pendingSeekTime!=null&&Promise.resolve().then(()=>{let p=this._pendingSeekTime;this._pendingSeekTime=null,this.seek(p)})}_onMetaDataArrived(d){this._emitter.emit(pe.METADATA_ARRIVED,d)}_onScriptDataArrived(d){this._emitter.emit(pe.SCRIPTDATA_ARRIVED,d)}_onIOSeeked(){this._remuxer.insertDiscontinuity()}_onIOComplete(d){let p=d+1;p<this._mediaDataSource.segments.length?(this._internalAbort(),this._remuxer.flushStashedSamples(),this._loadSegment(p)):(this._remuxer.flushStashedSamples(),this._emitter.emit(pe.LOADING_COMPLETE),this._disableStatisticsReporter())}_onIORedirect(d){let f=this._ioctl.extraData;this._mediaDataSource.segments[f].redirectedURL=d}_onIORecoveredEarlyEof(){this._emitter.emit(pe.RECOVERED_EARLY_EOF)}_onIOException(d,f){g.e(this.TAG,`IOException: type = ${d}, code = ${f.code}, msg = ${f.msg}`),this._emitter.emit(pe.IO_ERROR,d,f),this._disableStatisticsReporter()}_onDemuxException(d,f){g.e(this.TAG,`DemuxException: type = ${d}, info = ${f}`),this._emitter.emit(pe.DEMUX_ERROR,d,f)}_onRemuxerInitSegmentArrival(d,f){this._emitter.emit(pe.INIT_SEGMENT,d,f)}_onRemuxerMediaSegmentArrival(d,f){if(this._pendingSeekTime==null&&(this._emitter.emit(pe.MEDIA_SEGMENT,d,f),this._pendingResolveSeekPoint!=null&&d==="video")){let p=f.info.syncPoints,_=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=null,fe.safari&&p.length>0&&p[0].originalDts===_&&(_=p[0].pts),this._emitter.emit(pe.RECOMMEND_SEEKPOINT,_)}}_enableStatisticsReporter(){this._statisticsReporter==null&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))}_disableStatisticsReporter(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}_reportSegmentMediaInfo(d){let f=this._mediaInfo.segments[d],p=Object.assign({},f);p.duration=this._mediaInfo.duration,p.segmentCount=this._mediaInfo.segmentCount,delete p.segments,delete p.keyframesIndex,this._emitter.emit(pe.MEDIA_INFO,p)}_reportStatisticsInfo(){let d={};d.url=this._ioctl.currentURL,d.hasRedirect=this._ioctl.hasRedirect,d.hasRedirect&&(d.redirectedURL=this._ioctl.currentRedirectedURL),d.speed=this._ioctl.currentSpeed,d.loaderType=this._ioctl.loaderType,d.currentSegmentIndex=this._currentSegmentIndex,d.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(pe.STATISTICS_INFO,d)}}var qi=Ft,Mi=function(Ee){let d="TransmuxingWorker",f=null,p=$e.bind(this);de.install(),Ee.addEventListener("message",function(Se){switch(Se.data.cmd){case"init":f=new qi(Se.data.param[0],Se.data.param[1]),f.on(pe.IO_ERROR,ht.bind(this)),f.on(pe.DEMUX_ERROR,we.bind(this)),f.on(pe.INIT_SEGMENT,_.bind(this)),f.on(pe.MEDIA_SEGMENT,T.bind(this)),f.on(pe.LOADING_COMPLETE,I.bind(this)),f.on(pe.RECOVERED_EARLY_EOF,O.bind(this)),f.on(pe.MEDIA_INFO,be.bind(this)),f.on(pe.METADATA_ARRIVED,_e.bind(this)),f.on(pe.SCRIPTDATA_ARRIVED,Me.bind(this)),f.on(pe.STATISTICS_INFO,It.bind(this)),f.on(pe.RECOMMEND_SEEKPOINT,gt.bind(this));break;case"destroy":f&&(f.destroy(),f=null),Ee.postMessage({msg:"destroyed"});break;case"start":f.start();break;case"stop":f.stop();break;case"seek":f.seek(Se.data.param);break;case"pause":f.pause();break;case"resume":f.resume();break;case"logging_config":{let ve=Se.data.param;xt.applyConfig(ve),ve.enableCallback===!0?xt.addLogListener(p):xt.removeLogListener(p);break}}});function _(Se,ve){let et={msg:pe.INIT_SEGMENT,data:{type:Se,data:ve}};Ee.postMessage(et,[ve.data])}function T(Se,ve){let et={msg:pe.MEDIA_SEGMENT,data:{type:Se,data:ve}};Ee.postMessage(et,[ve.data])}function I(){let Se={msg:pe.LOADING_COMPLETE};Ee.postMessage(Se)}function O(){let Se={msg:pe.RECOVERED_EARLY_EOF};Ee.postMessage(Se)}function be(Se){let ve={msg:pe.MEDIA_INFO,data:Se};Ee.postMessage(ve)}function _e(Se){let ve={msg:pe.METADATA_ARRIVED,data:Se};Ee.postMessage(ve)}function Me(Se){let ve={msg:pe.SCRIPTDATA_ARRIVED,data:Se};Ee.postMessage(ve)}function It(Se){let ve={msg:pe.STATISTICS_INFO,data:Se};Ee.postMessage(ve)}function ht(Se,ve){Ee.postMessage({msg:pe.IO_ERROR,data:{type:Se,info:ve}})}function we(Se,ve){Ee.postMessage({msg:pe.DEMUX_ERROR,data:{type:Se,info:ve}})}function gt(Se){Ee.postMessage({msg:pe.RECOMMEND_SEEKPOINT,data:Se})}function $e(Se,ve){Ee.postMessage({msg:"logcat_callback",data:{type:Se,logcat:ve}})}};class rs{constructor(d,f){if(this.TAG="Transmuxer",this._emitter=new(Z()),f.enableWorker&&typeof Worker!="undefined")try{let p=$(82059);this._worker=p(Mi),this._workerDestroying=!1,this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",param:[d,f]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},xt.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:"logging_config",param:xt.getConfig()})}catch(p){g.e(this.TAG,"Error while initialize transmuxing worker, fallback to inline transmuxing"),this._worker=null,this._controller=new qi(d,f)}else this._controller=new qi(d,f);if(this._controller){let p=this._controller;p.on(pe.IO_ERROR,this._onIOError.bind(this)),p.on(pe.DEMUX_ERROR,this._onDemuxError.bind(this)),p.on(pe.INIT_SEGMENT,this._onInitSegment.bind(this)),p.on(pe.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),p.on(pe.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),p.on(pe.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),p.on(pe.MEDIA_INFO,this._onMediaInfo.bind(this)),p.on(pe.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),p.on(pe.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),p.on(pe.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),p.on(pe.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}destroy(){this._worker?this._workerDestroying||(this._workerDestroying=!0,this._worker.postMessage({cmd:"destroy"}),xt.removeListener(this.e.onLoggingConfigChanged),this.e=null):(this._controller.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null}on(d,f){this._emitter.addListener(d,f)}off(d,f){this._emitter.removeListener(d,f)}hasWorker(){return this._worker!=null}open(){this._worker?this._worker.postMessage({cmd:"start"}):this._controller.start()}close(){this._worker?this._worker.postMessage({cmd:"stop"}):this._controller.stop()}seek(d){this._worker?this._worker.postMessage({cmd:"seek",param:d}):this._controller.seek(d)}pause(){this._worker?this._worker.postMessage({cmd:"pause"}):this._controller.pause()}resume(){this._worker?this._worker.postMessage({cmd:"resume"}):this._controller.resume()}_onInitSegment(d,f){Promise.resolve().then(()=>{this._emitter.emit(pe.INIT_SEGMENT,d,f)})}_onMediaSegment(d,f){Promise.resolve().then(()=>{this._emitter.emit(pe.MEDIA_SEGMENT,d,f)})}_onLoadingComplete(){Promise.resolve().then(()=>{this._emitter.emit(pe.LOADING_COMPLETE)})}_onRecoveredEarlyEof(){Promise.resolve().then(()=>{this._emitter.emit(pe.RECOVERED_EARLY_EOF)})}_onMediaInfo(d){Promise.resolve().then(()=>{this._emitter.emit(pe.MEDIA_INFO,d)})}_onMetaDataArrived(d){Promise.resolve().then(()=>{this._emitter.emit(pe.METADATA_ARRIVED,d)})}_onScriptDataArrived(d){Promise.resolve().then(()=>{this._emitter.emit(pe.SCRIPTDATA_ARRIVED,d)})}_onStatisticsInfo(d){Promise.resolve().then(()=>{this._emitter.emit(pe.STATISTICS_INFO,d)})}_onIOError(d,f){Promise.resolve().then(()=>{this._emitter.emit(pe.IO_ERROR,d,f)})}_onDemuxError(d,f){Promise.resolve().then(()=>{this._emitter.emit(pe.DEMUX_ERROR,d,f)})}_onRecommendSeekpoint(d){Promise.resolve().then(()=>{this._emitter.emit(pe.RECOMMEND_SEEKPOINT,d)})}_onLoggingConfigChanged(d){this._worker&&this._worker.postMessage({cmd:"logging_config",param:d})}_onWorkerMessage(d){let f=d.data,p=f.data;if(f.msg==="destroyed"||this._workerDestroying){this._workerDestroying=!1,this._worker.terminate(),this._worker=null;return}switch(f.msg){case pe.INIT_SEGMENT:case pe.MEDIA_SEGMENT:this._emitter.emit(f.msg,p.type,p.data);break;case pe.LOADING_COMPLETE:case pe.RECOVERED_EARLY_EOF:this._emitter.emit(f.msg);break;case pe.MEDIA_INFO:Object.setPrototypeOf(p,si.prototype),this._emitter.emit(f.msg,p);break;case pe.METADATA_ARRIVED:case pe.SCRIPTDATA_ARRIVED:case pe.STATISTICS_INFO:this._emitter.emit(f.msg,p);break;case pe.IO_ERROR:case pe.DEMUX_ERROR:this._emitter.emit(f.msg,p.type,p.info);break;case pe.RECOMMEND_SEEKPOINT:this._emitter.emit(f.msg,p);break;case"logcat_callback":g.emitter.emit("log",p.type,p.logcat);break;default:break}}}var cs=rs,Ti={ERROR:"error",SOURCE_OPEN:"source_open",UPDATE_END:"update_end",BUFFER_FULL:"buffer_full"};class Ji{constructor(d){this.TAG="MSEController",this._config=d,this._emitter=new(Z()),this._config.isLive&&this._config.autoCleanupSourceBuffer==null&&(this._config.autoCleanupSourceBuffer=!0),this.e={onSourceOpen:this._onSourceOpen.bind(this),onSourceEnded:this._onSourceEnded.bind(this),onSourceClose:this._onSourceClose.bind(this),onSourceBufferError:this._onSourceBufferError.bind(this),onSourceBufferUpdateEnd:this._onSourceBufferUpdateEnd.bind(this)},this._mediaSource=null,this._mediaSourceObjectURL=null,this._mediaElement=null,this._isBufferFull=!1,this._hasPendingEos=!1,this._requireSetMediaDuration=!1,this._pendingMediaDuration=0,this._pendingSourceBufferInit=[],this._mimeTypes={video:null,audio:null},this._sourceBuffers={video:null,audio:null},this._lastInitSegments={video:null,audio:null},this._pendingSegments={video:[],audio:[]},this._pendingRemoveRanges={video:[],audio:[]},this._idrList=new Lt}destroy(){(this._mediaElement||this._mediaSource)&&this.detachMediaElement(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null}on(d,f){this._emitter.addListener(d,f)}off(d,f){this._emitter.removeListener(d,f)}attachMediaElement(d){if(this._mediaSource)throw new ot("MediaSource has been attached to an HTMLMediaElement!");let f=this._mediaSource=new window.MediaSource;f.addEventListener("sourceopen",this.e.onSourceOpen),f.addEventListener("sourceended",this.e.onSourceEnded),f.addEventListener("sourceclose",this.e.onSourceClose),this._mediaElement=d,this._mediaSourceObjectURL=window.URL.createObjectURL(this._mediaSource),d.src=this._mediaSourceObjectURL}detachMediaElement(){if(this._mediaSource){let d=this._mediaSource;for(let f in this._sourceBuffers){let p=this._pendingSegments[f];p.splice(0,p.length),this._pendingSegments[f]=null,this._pendingRemoveRanges[f]=null,this._lastInitSegments[f]=null;let _=this._sourceBuffers[f];if(_){if(d.readyState!=="closed"){try{d.removeSourceBuffer(_)}catch(T){g.e(this.TAG,T.message)}_.removeEventListener("error",this.e.onSourceBufferError),_.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[f]=null,this._sourceBuffers[f]=null}}if(d.readyState==="open")try{d.endOfStream()}catch(f){g.e(this.TAG,f.message)}d.removeEventListener("sourceopen",this.e.onSourceOpen),d.removeEventListener("sourceended",this.e.onSourceEnded),d.removeEventListener("sourceclose",this.e.onSourceClose),this._pendingSourceBufferInit=[],this._isBufferFull=!1,this._idrList.clear(),this._mediaSource=null}this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement=null),this._mediaSourceObjectURL&&(window.URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)}appendInitSegment(d,f){if(!this._mediaSource||this._mediaSource.readyState!=="open"){this._pendingSourceBufferInit.push(d),this._pendingSegments[d.type].push(d);return}let p=d,_=`${p.container}`;p.codec&&p.codec.length>0&&(_+=`;codecs=${p.codec}`);let T=!1;if(g.v(this.TAG,"Received Initialization Segment, mimeType: "+_),this._lastInitSegments[p.type]=p,_!==this._mimeTypes[p.type]){if(this._mimeTypes[p.type])g.v(this.TAG,`Notice: ${p.type} mimeType changed, origin: ${this._mimeTypes[p.type]}, target: ${_}`);else{T=!0;try{let I=this._sourceBuffers[p.type]=this._mediaSource.addSourceBuffer(_);I.addEventListener("error",this.e.onSourceBufferError),I.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(I){g.e(this.TAG,I.message),this._emitter.emit(Ti.ERROR,{code:I.code,msg:I.message});return}}this._mimeTypes[p.type]=_}f||this._pendingSegments[p.type].push(p),T||this._sourceBuffers[p.type]&&!this._sourceBuffers[p.type].updating&&this._doAppendSegments(),fe.safari&&p.container==="audio/mpeg"&&p.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=p.mediaDuration/1e3,this._updateMediaSourceDuration())}appendMediaSegment(d){let f=d;this._pendingSegments[f.type].push(f),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();let p=this._sourceBuffers[f.type];p&&!p.updating&&!this._hasPendingRemoveRanges()&&this._doAppendSegments()}seek(d){for(let f in this._sourceBuffers){if(!this._sourceBuffers[f])continue;let p=this._sourceBuffers[f];if(this._mediaSource.readyState==="open")try{p.abort()}catch(T){g.e(this.TAG,T.message)}this._idrList.clear();let _=this._pendingSegments[f];if(_.splice(0,_.length),this._mediaSource.readyState!=="closed"){for(let T=0;T<p.buffered.length;T++){let I=p.buffered.start(T),O=p.buffered.end(T);this._pendingRemoveRanges[f].push({start:I,end:O})}if(p.updating||this._doRemoveRanges(),fe.safari){let T=this._lastInitSegments[f];T&&(this._pendingSegments[f].push(T),p.updating||this._doAppendSegments())}}}}endOfStream(){let d=this._mediaSource,f=this._sourceBuffers;if(!d||d.readyState!=="open"){d&&d.readyState==="closed"&&this._hasPendingSegments()&&(this._hasPendingEos=!0);return}f.video&&f.video.updating||f.audio&&f.audio.updating?this._hasPendingEos=!0:(this._hasPendingEos=!1,d.endOfStream())}getNearestKeyframe(d){return this._idrList.getLastSyncPointBeforeDts(d)}_needCleanupSourceBuffer(){if(!this._config.autoCleanupSourceBuffer)return!1;let d=this._mediaElement.currentTime;for(let f in this._sourceBuffers){let p=this._sourceBuffers[f];if(p){let _=p.buffered;if(_.length>=1&&d-_.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1}_doCleanupSourceBuffer(){let d=this._mediaElement.currentTime;for(let f in this._sourceBuffers){let p=this._sourceBuffers[f];if(p){let _=p.buffered,T=!1;for(let I=0;I<_.length;I++){let O=_.start(I),be=_.end(I);if(O<=d&&d<be+3){if(d-O>=this._config.autoCleanupMaxBackwardDuration){T=!0;let _e=d-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[f].push({start:O,end:_e})}}else be<d&&(T=!0,this._pendingRemoveRanges[f].push({start:O,end:be}))}T&&!p.updating&&this._doRemoveRanges()}}}_updateMediaSourceDuration(){let d=this._sourceBuffers;if(this._mediaElement.readyState===0||this._mediaSource.readyState!=="open"||d.video&&d.video.updating||d.audio&&d.audio.updating)return;let f=this._mediaSource.duration,p=this._pendingMediaDuration;p>0&&(isNaN(f)||p>f)&&(g.v(this.TAG,`Update MediaSource duration from ${f} to ${p}`),this._mediaSource.duration=p),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}_doRemoveRanges(){for(let d in this._pendingRemoveRanges){if(!this._sourceBuffers[d]||this._sourceBuffers[d].updating)continue;let f=this._sourceBuffers[d],p=this._pendingRemoveRanges[d];for(;p.length&&!f.updating;){let _=p.shift();f.remove(_.start,_.end)}}}_doAppendSegments(){let d=this._pendingSegments;for(let f in d)if(!(!this._sourceBuffers[f]||this._sourceBuffers[f].updating)&&d[f].length>0){let p=d[f].shift();if(p.timestampOffset){let _=this._sourceBuffers[f].timestampOffset,T=p.timestampOffset/1e3;Math.abs(_-T)>.1&&(g.v(this.TAG,`Update MPEG audio timestampOffset from ${_} to ${T}`),this._sourceBuffers[f].timestampOffset=T),delete p.timestampOffset}if(!p.data||p.data.byteLength===0)continue;try{this._sourceBuffers[f].appendBuffer(p.data),this._isBufferFull=!1,f==="video"&&p.hasOwnProperty("info")&&this._idrList.appendArray(p.info.syncPoints)}catch(_){this._pendingSegments[f].unshift(p),_.code===22?(this._isBufferFull||this._emitter.emit(Ti.BUFFER_FULL),this._isBufferFull=!0):(g.e(this.TAG,_.message),this._emitter.emit(Ti.ERROR,{code:_.code,msg:_.message}))}}}_onSourceOpen(){if(g.v(this.TAG,"MediaSource onSourceOpen"),this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0){let d=this._pendingSourceBufferInit;for(;d.length;){let f=d.shift();this.appendInitSegment(f,!0)}}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(Ti.SOURCE_OPEN)}_onSourceEnded(){g.v(this.TAG,"MediaSource onSourceEnded")}_onSourceClose(){g.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&this.e!=null&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose))}_hasPendingSegments(){let d=this._pendingSegments;return d.video.length>0||d.audio.length>0}_hasPendingRemoveRanges(){let d=this._pendingRemoveRanges;return d.video.length>0||d.audio.length>0}_onSourceBufferUpdateEnd(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(Ti.UPDATE_END)}_onSourceBufferError(d){g.e(this.TAG,`SourceBuffer Error: ${d}`)}}var Wi=Ji;const Qe={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},Nt={NETWORK_EXCEPTION:z.EXCEPTION,NETWORK_STATUS_CODE_INVALID:z.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:z.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:z.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:Oe.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:Oe.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:Oe.CODEC_UNSUPPORTED};class kt{constructor(d,f){if(this.TAG="FlvPlayer",this._type="FlvPlayer",this._emitter=new(Z()),this._config=me(),typeof f=="object"&&Object.assign(this._config,f),d.type.toLowerCase()!=="flv")throw new at("FlvPlayer requires an flv MediaDataSource input!");d.isLive===!0&&(this._config.isLive=!0),this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this),onvSeeking:this._onvSeeking.bind(this),onvCanPlay:this._onvCanPlay.bind(this),onvStalled:this._onvStalled.bind(this),onvProgress:this._onvProgress.bind(this)},self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now,this._pendingSeekTime=null,this._requestSetTime=!1,this._seekpointRecord=null,this._progressChecker=null,this._mediaDataSource=d,this._mediaElement=null,this._msectl=null,this._transmuxer=null,this._mseSourceOpened=!1,this._hasPendingLoad=!1,this._receivedCanPlay=!1,this._mediaInfo=null,this._statisticsInfo=null;let p=fe.chrome&&(fe.version.major<50||fe.version.major===50&&fe.version.build<2661);this._alwaysSeekKeyframe=!!(p||fe.msedge||fe.msie),this._alwaysSeekKeyframe&&(this._config.accurateSeek=!1)}destroy(){this._progressChecker!=null&&(window.clearInterval(this._progressChecker),this._progressChecker=null),this._transmuxer&&this.unload(),this._mediaElement&&this.detachMediaElement(),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null}on(d,f){d===Ie.MEDIA_INFO?this._mediaInfo!=null&&Promise.resolve().then(()=>{this._emitter.emit(Ie.MEDIA_INFO,this.mediaInfo)}):d===Ie.STATISTICS_INFO&&this._statisticsInfo!=null&&Promise.resolve().then(()=>{this._emitter.emit(Ie.STATISTICS_INFO,this.statisticsInfo)}),this._emitter.addListener(d,f)}off(d,f){this._emitter.removeListener(d,f)}attachMediaElement(d){if(this._mediaElement=d,d.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),d.addEventListener("seeking",this.e.onvSeeking),d.addEventListener("canplay",this.e.onvCanPlay),d.addEventListener("stalled",this.e.onvStalled),d.addEventListener("progress",this.e.onvProgress),this._msectl=new Wi(this._config),this._msectl.on(Ti.UPDATE_END,this._onmseUpdateEnd.bind(this)),this._msectl.on(Ti.BUFFER_FULL,this._onmseBufferFull.bind(this)),this._msectl.on(Ti.SOURCE_OPEN,()=>{this._mseSourceOpened=!0,this._hasPendingLoad&&(this._hasPendingLoad=!1,this.load())}),this._msectl.on(Ti.ERROR,f=>{this._emitter.emit(Ie.ERROR,Qe.MEDIA_ERROR,Nt.MEDIA_MSE_ERROR,f)}),this._msectl.attachMediaElement(d),this._pendingSeekTime!=null)try{d.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(f){}}detachMediaElement(){this._mediaElement&&(this._msectl.detachMediaElement(),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement.removeEventListener("seeking",this.e.onvSeeking),this._mediaElement.removeEventListener("canplay",this.e.onvCanPlay),this._mediaElement.removeEventListener("stalled",this.e.onvStalled),this._mediaElement.removeEventListener("progress",this.e.onvProgress),this._mediaElement=null),this._msectl&&(this._msectl.destroy(),this._msectl=null)}load(){if(!this._mediaElement)throw new ot("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new ot("FlvPlayer.load() has been called, please call unload() first!");if(!this._hasPendingLoad){if(this._config.deferLoadAfterSourceOpen&&this._mseSourceOpened===!1){this._hasPendingLoad=!0;return}this._mediaElement.readyState>0&&(this._requestSetTime=!0,this._mediaElement.currentTime=0),this._transmuxer=new cs(this._mediaDataSource,this._config),this._transmuxer.on(pe.INIT_SEGMENT,(d,f)=>{this._msectl.appendInitSegment(f)}),this._transmuxer.on(pe.MEDIA_SEGMENT,(d,f)=>{if(this._msectl.appendMediaSegment(f),this._config.lazyLoad&&!this._config.isLive){let p=this._mediaElement.currentTime;f.info.endDts>=(p+this._config.lazyLoadMaxDuration)*1e3&&this._progressChecker==null&&(g.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this._suspendTransmuxer())}}),this._transmuxer.on(pe.LOADING_COMPLETE,()=>{this._msectl.endOfStream(),this._emitter.emit(Ie.LOADING_COMPLETE)}),this._transmuxer.on(pe.RECOVERED_EARLY_EOF,()=>{this._emitter.emit(Ie.RECOVERED_EARLY_EOF)}),this._transmuxer.on(pe.IO_ERROR,(d,f)=>{this._emitter.emit(Ie.ERROR,Qe.NETWORK_ERROR,d,f)}),this._transmuxer.on(pe.DEMUX_ERROR,(d,f)=>{this._emitter.emit(Ie.ERROR,Qe.MEDIA_ERROR,d,{code:-1,msg:f})}),this._transmuxer.on(pe.MEDIA_INFO,d=>{this._mediaInfo=d,this._emitter.emit(Ie.MEDIA_INFO,Object.assign({},d))}),this._transmuxer.on(pe.METADATA_ARRIVED,d=>{this._emitter.emit(Ie.METADATA_ARRIVED,d)}),this._transmuxer.on(pe.SCRIPTDATA_ARRIVED,d=>{this._emitter.emit(Ie.SCRIPTDATA_ARRIVED,d)}),this._transmuxer.on(pe.STATISTICS_INFO,d=>{this._statisticsInfo=this._fillStatisticsInfo(d),this._emitter.emit(Ie.STATISTICS_INFO,Object.assign({},this._statisticsInfo))}),this._transmuxer.on(pe.RECOMMEND_SEEKPOINT,d=>{this._mediaElement&&!this._config.accurateSeek&&(this._requestSetTime=!0,this._mediaElement.currentTime=d/1e3)}),this._transmuxer.open()}}unload(){this._mediaElement&&this._mediaElement.pause(),this._msectl&&this._msectl.seek(0),this._transmuxer&&(this._transmuxer.close(),this._transmuxer.destroy(),this._transmuxer=null)}play(){return this._mediaElement.play()}pause(){this._mediaElement.pause()}get type(){return this._type}get buffered(){return this._mediaElement.buffered}get duration(){return this._mediaElement.duration}get volume(){return this._mediaElement.volume}set volume(d){this._mediaElement.volume=d}get muted(){return this._mediaElement.muted}set muted(d){this._mediaElement.muted=d}get currentTime(){return this._mediaElement?this._mediaElement.currentTime:0}set currentTime(d){this._mediaElement?this._internalSeek(d):this._pendingSeekTime=d}get mediaInfo(){return Object.assign({},this._mediaInfo)}get statisticsInfo(){return this._statisticsInfo==null&&(this._statisticsInfo={}),this._statisticsInfo=this._fillStatisticsInfo(this._statisticsInfo),Object.assign({},this._statisticsInfo)}_fillStatisticsInfo(d){if(d.playerType=this._type,!(this._mediaElement instanceof HTMLVideoElement))return d;let f=!0,p=0,_=0;if(this._mediaElement.getVideoPlaybackQuality){let T=this._mediaElement.getVideoPlaybackQuality();p=T.totalVideoFrames,_=T.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(p=this._mediaElement.webkitDecodedFrameCount,_=this._mediaElement.webkitDroppedFrameCount):f=!1;return f&&(d.decodedFrames=p,d.droppedFrames=_),d}_onmseUpdateEnd(){if(!this._config.lazyLoad||this._config.isLive)return;let d=this._mediaElement.buffered,f=this._mediaElement.currentTime,p=0,_=0;for(let T=0;T<d.length;T++){let I=d.start(T),O=d.end(T);if(I<=f&&f<O){p=I,_=O;break}}_>=f+this._config.lazyLoadMaxDuration&&this._progressChecker==null&&(g.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this._suspendTransmuxer())}_onmseBufferFull(){g.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._progressChecker==null&&this._suspendTransmuxer()}_suspendTransmuxer(){this._transmuxer&&(this._transmuxer.pause(),this._progressChecker==null&&(this._progressChecker=window.setInterval(this._checkProgressAndResume.bind(this),1e3)))}_checkProgressAndResume(){let d=this._mediaElement.currentTime,f=this._mediaElement.buffered,p=!1;for(let _=0;_<f.length;_++){let T=f.start(_),I=f.end(_);if(d>=T&&d<I){d>=I-this._config.lazyLoadRecoverDuration&&(p=!0);break}}p&&(window.clearInterval(this._progressChecker),this._progressChecker=null,p&&(g.v(this.TAG,"Continue loading from paused position"),this._transmuxer.resume()))}_isTimepointBuffered(d){let f=this._mediaElement.buffered;for(let p=0;p<f.length;p++){let _=f.start(p),T=f.end(p);if(d>=_&&d<T)return!0}return!1}_internalSeek(d){let f=this._isTimepointBuffered(d),p=!1,_=0;if(d<1&&this._mediaElement.buffered.length>0){let T=this._mediaElement.buffered.start(0);(T<1&&d<T||fe.safari)&&(p=!0,_=fe.safari?.1:T)}if(p)this._requestSetTime=!0,this._mediaElement.currentTime=_;else if(f){if(!this._alwaysSeekKeyframe)this._requestSetTime=!0,this._mediaElement.currentTime=d;else{let T=this._msectl.getNearestKeyframe(Math.floor(d*1e3));this._requestSetTime=!0,T!=null?this._mediaElement.currentTime=T.dts/1e3:this._mediaElement.currentTime=d}this._progressChecker!=null&&this._checkProgressAndResume()}else this._progressChecker!=null&&(window.clearInterval(this._progressChecker),this._progressChecker=null),this._msectl.seek(d),this._transmuxer.seek(Math.floor(d*1e3)),this._config.accurateSeek&&(this._requestSetTime=!0,this._mediaElement.currentTime=d)}_checkAndApplyUnbufferedSeekpoint(){if(this._seekpointRecord)if(this._seekpointRecord.recordTime<=this._now()-100){let d=this._mediaElement.currentTime;this._seekpointRecord=null,this._isTimepointBuffered(d)||(this._progressChecker!=null&&(window.clearTimeout(this._progressChecker),this._progressChecker=null),this._msectl.seek(d),this._transmuxer.seek(Math.floor(d*1e3)),this._config.accurateSeek&&(this._requestSetTime=!0,this._mediaElement.currentTime=d))}else window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this),50)}_checkAndResumeStuckPlayback(d){let f=this._mediaElement;if(d||!this._receivedCanPlay||f.readyState<2){let p=f.buffered;p.length>0&&f.currentTime<p.start(0)&&(g.w(this.TAG,`Playback seems stuck at ${f.currentTime}, seek to ${p.start(0)}`),this._requestSetTime=!0,this._mediaElement.currentTime=p.start(0),this._mediaElement.removeEventListener("progress",this.e.onvProgress))}else this._mediaElement.removeEventListener("progress",this.e.onvProgress)}_onvLoadedMetadata(d){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null)}_onvSeeking(d){let f=this._mediaElement.currentTime,p=this._mediaElement.buffered;if(this._requestSetTime){this._requestSetTime=!1;return}if(f<1&&p.length>0){let _=p.start(0);if(_<1&&f<_||fe.safari){this._requestSetTime=!0,this._mediaElement.currentTime=fe.safari?.1:_;return}}if(this._isTimepointBuffered(f)){if(this._alwaysSeekKeyframe){let _=this._msectl.getNearestKeyframe(Math.floor(f*1e3));_!=null&&(this._requestSetTime=!0,this._mediaElement.currentTime=_.dts/1e3)}this._progressChecker!=null&&this._checkProgressAndResume();return}this._seekpointRecord={seekPoint:f,recordTime:this._now()},window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this),50)}_onvCanPlay(d){this._receivedCanPlay=!0,this._mediaElement.removeEventListener("canplay",this.e.onvCanPlay)}_onvStalled(d){this._checkAndResumeStuckPlayback(!0)}_onvProgress(d){this._checkAndResumeStuckPlayback()}}var gi=kt;class _i{constructor(d,f){if(this.TAG="NativePlayer",this._type="NativePlayer",this._emitter=new(Z()),this._config=me(),typeof f=="object"&&Object.assign(this._config,f),d.type.toLowerCase()==="flv")throw new at("NativePlayer does't support flv MediaDataSource input!");if(d.hasOwnProperty("segments"))throw new at(`NativePlayer(${d.type}) doesn't support multipart playback!`);this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=d,this._mediaElement=null}destroy(){this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null}on(d,f){d===Ie.MEDIA_INFO?this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(()=>{this._emitter.emit(Ie.MEDIA_INFO,this.mediaInfo)}):d===Ie.STATISTICS_INFO&&this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(()=>{this._emitter.emit(Ie.STATISTICS_INFO,this.statisticsInfo)}),this._emitter.addListener(d,f)}off(d,f){this._emitter.removeListener(d,f)}attachMediaElement(d){if(this._mediaElement=d,d.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._pendingSeekTime!=null)try{d.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(f){}}detachMediaElement(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement=null),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}load(){if(!this._mediaElement)throw new ot("HTMLMediaElement must be attached before load()!");this._mediaElement.src=this._mediaDataSource.url,this._mediaElement.readyState>0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)}unload(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)}play(){return this._mediaElement.play()}pause(){this._mediaElement.pause()}get type(){return this._type}get buffered(){return this._mediaElement.buffered}get duration(){return this._mediaElement.duration}get volume(){return this._mediaElement.volume}set volume(d){this._mediaElement.volume=d}get muted(){return this._mediaElement.muted}set muted(d){this._mediaElement.muted=d}get currentTime(){return this._mediaElement?this._mediaElement.currentTime:0}set currentTime(d){this._mediaElement?this._mediaElement.currentTime=d:this._pendingSeekTime=d}get mediaInfo(){let f={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(f.duration=Math.floor(this._mediaElement.duration*1e3),this._mediaElement instanceof HTMLVideoElement&&(f.width=this._mediaElement.videoWidth,f.height=this._mediaElement.videoHeight)),f}get statisticsInfo(){let d={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return d;let f=!0,p=0,_=0;if(this._mediaElement.getVideoPlaybackQuality){let T=this._mediaElement.getVideoPlaybackQuality();p=T.totalVideoFrames,_=T.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(p=this._mediaElement.webkitDecodedFrameCount,_=this._mediaElement.webkitDroppedFrameCount):f=!1;return f&&(d.decodedFrames=p,d.droppedFrames=_),d}_onvLoadedMetadata(d){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(Ie.MEDIA_INFO,this.mediaInfo)}_reportStatisticsInfo(){this._emitter.emit(Ie.STATISTICS_INFO,this.statisticsInfo)}}var yi=_i;de.install();function Rt(Ee,d){let f=Ee;if(f==null||typeof f!="object")throw new at("MediaDataSource must be an javascript object!");if(!f.hasOwnProperty("type"))throw new at("MediaDataSource must has type field to indicate video file type!");switch(f.type){case"flv":return new gi(f,d);default:return new yi(f,d)}}function Bi(){return Fe.supportMSEH264Playback()}function Qt(){return Fe.getFeatureList()}let Si={};Si.createPlayer=Rt,Si.isSupported=Bi,Si.getFeatureList=Qt,Si.BaseLoader=Zt,Si.LoaderStatus=D,Si.LoaderErrors=z,Si.Events=Ie,Si.ErrorTypes=Qe,Si.ErrorDetails=Nt,Si.FlvPlayer=gi,Si.NativePlayer=yi,Si.LoggingControl=xt,Object.defineProperty(Si,"version",{enumerable:!0,get:function(){return"__VERSION__"}});var Ui=Si},25769:function(Pi,wt,$){"use strict";var b=$(98040),de={"text/plain":"Text","text/html":"Url",default:"Text"},Be="Copy to clipboard: #{key}, Enter";function Z(g){var xe=(/mac os x/i.test(navigator.userAgent)?"\u2318":"Ctrl")+"+C";return g.replace(/#{\s*key\s*}/g,xe)}function A(g,xe){var ae,he,ot,at,Re,D,z=!1;xe||(xe={}),ae=xe.debug||!1;try{ot=b(),at=document.createRange(),Re=document.getSelection(),D=document.createElement("span"),D.textContent=g,D.ariaHidden="true",D.style.all="unset",D.style.position="fixed",D.style.top=0,D.style.clip="rect(0, 0, 0, 0)",D.style.whiteSpace="pre",D.style.webkitUserSelect="text",D.style.MozUserSelect="text",D.style.msUserSelect="text",D.style.userSelect="text",D.addEventListener("copy",function(ft){if(ft.stopPropagation(),xe.format)if(ft.preventDefault(),typeof ft.clipboardData=="undefined"){ae&&console.warn("unable to use e.clipboardData"),ae&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var De=de[xe.format]||de.default;window.clipboardData.setData(De,g)}else ft.clipboardData.clearData(),ft.clipboardData.setData(xe.format,g);xe.onCopy&&(ft.preventDefault(),xe.onCopy(ft.clipboardData))}),document.body.appendChild(D),at.selectNodeContents(D),Re.addRange(at);var Zt=document.execCommand("copy");if(!Zt)throw new Error("copy command was unsuccessful");z=!0}catch(ft){ae&&console.error("unable to copy using execCommand: ",ft),ae&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(xe.format||"text",g),xe.onCopy&&xe.onCopy(window.clipboardData),z=!0}catch(De){ae&&console.error("unable to copy using clipboardData: ",De),ae&&console.error("falling back to prompt"),he=Z("message"in xe?xe.message:Be),window.prompt(he,g)}}finally{Re&&(typeof Re.removeRange=="function"?Re.removeRange(at):Re.removeAllRanges()),D&&document.body.removeChild(D),ot()}return z}Pi.exports=A},3867:function(Pi,wt,$){var b=$(97671);(function(de,Be){Pi.exports=Be()})(this,function(){"use strict";function de(G){var ee=typeof G;return G!==null&&(ee==="object"||ee==="function")}function Be(G){return typeof G=="function"}var Z=void 0;Array.isArray?Z=Array.isArray:Z=function(G){return Object.prototype.toString.call(G)==="[object Array]"};var A=Z,g=0,xe=void 0,ae=void 0,he=function(ee,se){ie[g]=ee,ie[g+1]=se,g+=2,g===2&&(ae?ae(ge):J())};function ot(G){ae=G}function at(G){he=G}var Re=typeof window!="undefined"?window:void 0,D=Re||{},z=D.MutationObserver||D.WebKitMutationObserver,Zt=typeof self=="undefined"&&typeof b!="undefined"&&{}.toString.call(b)==="[object process]",ft=typeof Uint8ClampedArray!="undefined"&&typeof importScripts!="undefined"&&typeof MessageChannel!="undefined";function De(){return function(){return b.nextTick(ge)}}function fe(){return typeof xe!="undefined"?function(){xe(ge)}:W()}function M(){var G=0,ee=new z(ge),se=document.createTextNode("");return ee.observe(se,{characterData:!0}),function(){se.data=G=++G%2}}function C(){var G=new MessageChannel;return G.port1.onmessage=ge,function(){return G.port2.postMessage(0)}}function W(){var G=setTimeout;return function(){return G(ge,1)}}var ie=new Array(1e3);function ge(){for(var G=0;G<g;G+=2){var ee=ie[G],se=ie[G+1];ee(se),ie[G]=void 0,ie[G+1]=void 0}g=0}function Xe(){try{var G=Function("return this")().require("vertx");return xe=G.runOnLoop||G.runOnContext,fe()}catch(ee){return W()}}var J=void 0;Zt?J=De():z?J=M():ft?J=C():Re===void 0?J=Xe():J=W();function dt(G,ee){var se=this,w=new this.constructor(_t);w[Gt]===void 0&&qt(w);var Ae=se._state;if(Ae){var Je=arguments[Ae-1];he(function(){return di(Ae,w,Je,se._result)})}else ei(se,w,G,ee);return w}function Et(G){var ee=this;if(G&&typeof G=="object"&&G.constructor===ee)return G;var se=new ee(_t);return Ne(se,G),se}var Gt=Math.random().toString(36).substring(2);function _t(){}var te=void 0,X=1,oe=2;function F(){return new TypeError("You cannot resolve a promise with itself")}function ke(){return new TypeError("A promises callback cannot return that same promise.")}function lt(G,ee,se,w){try{G.call(ee,se,w)}catch(Ae){return Ae}}function me(G,ee,se){he(function(w){var Ae=!1,Je=lt(se,ee,function(je){Ae||(Ae=!0,ee!==je?Ne(w,je):st(w,je))},function(je){Ae||(Ae=!0,xt(w,je))},"Settle: "+(w._label||" unknown promise"));!Ae&&Je&&(Ae=!0,xt(w,Je))},G)}function Ye(G,ee){ee._state===X?st(G,ee._result):ee._state===oe?xt(G,ee._result):ei(ee,void 0,function(se){return Ne(G,se)},function(se){return xt(G,se)})}function Fe(G,ee,se){ee.constructor===G.constructor&&se===dt&&ee.constructor.resolve===Et?Ye(G,ee):se===void 0?st(G,ee):Be(se)?me(G,ee,se):st(G,ee)}function Ne(G,ee){if(G===ee)xt(G,F());else if(de(ee)){var se=void 0;try{se=ee.then}catch(w){xt(G,w);return}Fe(G,ee,se)}else st(G,ee)}function Ie(G){G._onerror&&G._onerror(G._result),si(G)}function st(G,ee){G._state===te&&(G._result=ee,G._state=X,G._subscribers.length!==0&&he(si,G))}function xt(G,ee){G._state===te&&(G._state=oe,G._result=ee,he(Ie,G))}function ei(G,ee,se,w){var Ae=G._subscribers,Je=Ae.length;G._onerror=null,Ae[Je]=ee,Ae[Je+X]=se,Ae[Je+oe]=w,Je===0&&G._state&&he(si,G)}function si(G){var ee=G._subscribers,se=G._state;if(ee.length!==0){for(var w=void 0,Ae=void 0,Je=G._result,je=0;je<ee.length;je+=3)w=ee[je],Ae=ee[je+se],w?di(se,w,Ae,Je):Ae(Je);G._subscribers.length=0}}function di(G,ee,se,w){var Ae=Be(se),Je=void 0,je=void 0,Vt=!0;if(Ae){try{Je=se(w)}catch(Bt){Vt=!1,je=Bt}if(ee===Je){xt(ee,ke());return}}else Je=w;ee._state!==te||(Ae&&Vt?Ne(ee,Je):Vt===!1?xt(ee,je):G===X?st(ee,Je):G===oe&&xt(ee,Je))}function Ai(G,ee){try{ee(function(w){Ne(G,w)},function(w){xt(G,w)})}catch(se){xt(G,se)}}var hi=0;function St(){return hi++}function qt(G){G[Gt]=hi++,G._state=void 0,G._result=void 0,G._subscribers=[]}function We(){return new Error("Array Methods must be provided an Array")}var Oi=function(){function G(ee,se){this._instanceConstructor=ee,this.promise=new ee(_t),this.promise[Gt]||qt(this.promise),A(se)?(this.length=se.length,this._remaining=se.length,this._result=new Array(this.length),this.length===0?st(this.promise,this._result):(this.length=this.length||0,this._enumerate(se),this._remaining===0&&st(this.promise,this._result))):xt(this.promise,We())}return G.prototype._enumerate=function(se){for(var w=0;this._state===te&&w<se.length;w++)this._eachEntry(se[w],w)},G.prototype._eachEntry=function(se,w){var Ae=this._instanceConstructor,Je=Ae.resolve;if(Je===Et){var je=void 0,Vt=void 0,Bt=!1;try{je=se.then}catch(Ht){Bt=!0,Vt=Ht}if(je===dt&&se._state!==te)this._settledAt(se._state,w,se._result);else if(typeof je!="function")this._remaining--,this._result[w]=se;else if(Ae===Ze){var Lt=new Ae(_t);Bt?xt(Lt,Vt):Fe(Lt,se,je),this._willSettleAt(Lt,w)}else this._willSettleAt(new Ae(function(Ht){return Ht(se)}),w)}else this._willSettleAt(Je(se),w)},G.prototype._settledAt=function(se,w,Ae){var Je=this.promise;Je._state===te&&(this._remaining--,se===oe?xt(Je,Ae):this._result[w]=Ae),this._remaining===0&&st(Je,this._result)},G.prototype._willSettleAt=function(se,w){var Ae=this;ei(se,void 0,function(Je){return Ae._settledAt(X,w,Je)},function(Je){return Ae._settledAt(oe,w,Je)})},G}();function Q(G){return new Oi(this,G).promise}function Te(G){var ee=this;return A(G)?new ee(function(se,w){for(var Ae=G.length,Je=0;Je<Ae;Je++)ee.resolve(G[Je]).then(se,w)}):new ee(function(se,w){return w(new TypeError("You must pass an array to race."))})}function B(G){var ee=this,se=new ee(_t);return xt(se,G),se}function Pe(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function Oe(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var Ze=function(){function G(ee){this[Gt]=St(),this._result=this._state=void 0,this._subscribers=[],_t!==ee&&(typeof ee!="function"&&Pe(),this instanceof G?Ai(this,ee):Oe())}return G.prototype.catch=function(se){return this.then(null,se)},G.prototype.finally=function(se){var w=this,Ae=w.constructor;return Be(se)?w.then(function(Je){return Ae.resolve(se()).then(function(){return Je})},function(Je){return Ae.resolve(se()).then(function(){throw Je})}):w.then(se,se)},G}();Ze.prototype.then=dt,Ze.all=Q,Ze.race=Te,Ze.resolve=Et,Ze.reject=B,Ze._setScheduler=ot,Ze._setAsap=at,Ze._asap=he;function mt(){var G=void 0;if(typeof $.g!="undefined")G=$.g;else if(typeof self!="undefined")G=self;else try{G=Function("return this")()}catch(w){throw new Error("polyfill failed because global object is unavailable in this environment")}var ee=G.Promise;if(ee){var se=null;try{se=Object.prototype.toString.call(ee.resolve())}catch(w){}if(se==="[object Promise]"&&!ee.cast)return}G.Promise=Ze}return Ze.polyfill=mt,Ze.Promise=Ze,Ze})},86204:function(Pi){"use strict";var wt=typeof Reflect=="object"?Reflect:null,$=wt&&typeof wt.apply=="function"?wt.apply:function(C,W,ie){return Function.prototype.apply.call(C,W,ie)},b;wt&&typeof wt.ownKeys=="function"?b=wt.ownKeys:Object.getOwnPropertySymbols?b=function(C){return Object.getOwnPropertyNames(C).concat(Object.getOwnPropertySymbols(C))}:b=function(C){return Object.getOwnPropertyNames(C)};function de(M){console&&console.warn&&console.warn(M)}var Be=Number.isNaN||function(C){return C!==C};function Z(){Z.init.call(this)}Pi.exports=Z,Pi.exports.once=ft,Z.EventEmitter=Z,Z.prototype._events=void 0,Z.prototype._eventsCount=0,Z.prototype._maxListeners=void 0;var A=10;function g(M){if(typeof M!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof M)}Object.defineProperty(Z,"defaultMaxListeners",{enumerable:!0,get:function(){return A},set:function(M){if(typeof M!="number"||M<0||Be(M))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+M+".");A=M}}),Z.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Z.prototype.setMaxListeners=function(C){if(typeof C!="number"||C<0||Be(C))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+C+".");return this._maxListeners=C,this};function xe(M){return M._maxListeners===void 0?Z.defaultMaxListeners:M._maxListeners}Z.prototype.getMaxListeners=function(){return xe(this)},Z.prototype.emit=function(C){for(var W=[],ie=1;ie<arguments.length;ie++)W.push(arguments[ie]);var ge=C==="error",Xe=this._events;if(Xe!==void 0)ge=ge&&Xe.error===void 0;else if(!ge)return!1;if(ge){var J;if(W.length>0&&(J=W[0]),J instanceof Error)throw J;var dt=new Error("Unhandled error."+(J?" ("+J.message+")":""));throw dt.context=J,dt}var Et=Xe[C];if(Et===void 0)return!1;if(typeof Et=="function")$(Et,this,W);else for(var Gt=Et.length,_t=D(Et,Gt),ie=0;ie<Gt;++ie)$(_t[ie],this,W);return!0};function ae(M,C,W,ie){var ge,Xe,J;if(g(W),Xe=M._events,Xe===void 0?(Xe=M._events=Object.create(null),M._eventsCount=0):(Xe.newListener!==void 0&&(M.emit("newListener",C,W.listener?W.listener:W),Xe=M._events),J=Xe[C]),J===void 0)J=Xe[C]=W,++M._eventsCount;else if(typeof J=="function"?J=Xe[C]=ie?[W,J]:[J,W]:ie?J.unshift(W):J.push(W),ge=xe(M),ge>0&&J.length>ge&&!J.warned){J.warned=!0;var dt=new Error("Possible EventEmitter memory leak detected. "+J.length+" "+String(C)+" listeners added. Use emitter.setMaxListeners() to increase limit");dt.name="MaxListenersExceededWarning",dt.emitter=M,dt.type=C,dt.count=J.length,de(dt)}return M}Z.prototype.addListener=function(C,W){return ae(this,C,W,!1)},Z.prototype.on=Z.prototype.addListener,Z.prototype.prependListener=function(C,W){return ae(this,C,W,!0)};function he(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ot(M,C,W){var ie={fired:!1,wrapFn:void 0,target:M,type:C,listener:W},ge=he.bind(ie);return ge.listener=W,ie.wrapFn=ge,ge}Z.prototype.once=function(C,W){return g(W),this.on(C,ot(this,C,W)),this},Z.prototype.prependOnceListener=function(C,W){return g(W),this.prependListener(C,ot(this,C,W)),this},Z.prototype.removeListener=function(C,W){var ie,ge,Xe,J,dt;if(g(W),ge=this._events,ge===void 0)return this;if(ie=ge[C],ie===void 0)return this;if(ie===W||ie.listener===W)--this._eventsCount===0?this._events=Object.create(null):(delete ge[C],ge.removeListener&&this.emit("removeListener",C,ie.listener||W));else if(typeof ie!="function"){for(Xe=-1,J=ie.length-1;J>=0;J--)if(ie[J]===W||ie[J].listener===W){dt=ie[J].listener,Xe=J;break}if(Xe<0)return this;Xe===0?ie.shift():z(ie,Xe),ie.length===1&&(ge[C]=ie[0]),ge.removeListener!==void 0&&this.emit("removeListener",C,dt||W)}return this},Z.prototype.off=Z.prototype.removeListener,Z.prototype.removeAllListeners=function(C){var W,ie,ge;if(ie=this._events,ie===void 0)return this;if(ie.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):ie[C]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete ie[C]),this;if(arguments.length===0){var Xe=Object.keys(ie),J;for(ge=0;ge<Xe.length;++ge)J=Xe[ge],J!=="removeListener"&&this.removeAllListeners(J);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(W=ie[C],typeof W=="function")this.removeListener(C,W);else if(W!==void 0)for(ge=W.length-1;ge>=0;ge--)this.removeListener(C,W[ge]);return this};function at(M,C,W){var ie=M._events;if(ie===void 0)return[];var ge=ie[C];return ge===void 0?[]:typeof ge=="function"?W?[ge.listener||ge]:[ge]:W?Zt(ge):D(ge,ge.length)}Z.prototype.listeners=function(C){return at(this,C,!0)},Z.prototype.rawListeners=function(C){return at(this,C,!1)},Z.listenerCount=function(M,C){return typeof M.listenerCount=="function"?M.listenerCount(C):Re.call(M,C)},Z.prototype.listenerCount=Re;function Re(M){var C=this._events;if(C!==void 0){var W=C[M];if(typeof W=="function")return 1;if(W!==void 0)return W.length}return 0}Z.prototype.eventNames=function(){return this._eventsCount>0?b(this._events):[]};function D(M,C){for(var W=new Array(C),ie=0;ie<C;++ie)W[ie]=M[ie];return W}function z(M,C){for(;C+1<M.length;C++)M[C]=M[C+1];M.pop()}function Zt(M){for(var C=new Array(M.length),W=0;W<C.length;++W)C[W]=M[W].listener||M[W];return C}function ft(M,C){return new Promise(function(W,ie){function ge(J){M.removeListener(C,Xe),ie(J)}function Xe(){typeof M.removeListener=="function"&&M.removeListener("error",ge),W([].slice.call(arguments))}fe(M,C,Xe,{once:!0}),C!=="error"&&De(M,ge,{once:!0})})}function De(M,C,W){typeof M.on=="function"&&fe(M,"error",C,W)}function fe(M,C,W,ie){if(typeof M.on=="function")ie.once?M.once(C,W):M.on(C,W);else if(typeof M.addEventListener=="function")M.addEventListener(C,function ge(Xe){ie.once&&M.removeEventListener(C,ge),W(Xe)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof M)}},96478:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return Xe}});var b=$(32855),de=$(74430),Be=$(11913),Z=$(43079),A=$(65030),g=$(92310),xe=$.n(g),ae=$(8654),he=$(59301),ot=$(10228),at=$(16089),Re=ot.Z.ESC,D=ot.Z.TAB;function z(J){var dt=J.visible,Et=J.triggerRef,Gt=J.onVisibleChange,_t=J.autoFocus,te=J.overlayRef,X=he.useRef(!1),oe=function(){if(dt){var me,Ye;(me=Et.current)===null||me===void 0||(Ye=me.focus)===null||Ye===void 0||Ye.call(me),Gt==null||Gt(!1)}},F=function(){var me;return(me=te.current)!==null&&me!==void 0&&me.focus?(te.current.focus(),X.current=!0,!0):!1},ke=function(me){switch(me.keyCode){case Re:oe();break;case D:{var Ye=!1;X.current||(Ye=F()),Ye?me.preventDefault():oe();break}}};he.useEffect(function(){return dt?(window.addEventListener("keydown",ke),_t&&(0,at.Z)(F,3),function(){window.removeEventListener("keydown",ke),X.current=!1}):function(){X.current=!1}},[dt])}var Zt=(0,he.forwardRef)(function(J,dt){var Et=J.overlay,Gt=J.arrow,_t=J.prefixCls,te=(0,he.useMemo)(function(){var oe;return typeof Et=="function"?oe=Et():oe=Et,oe},[Et]),X=(0,ae.sQ)(dt,(0,ae.C4)(te));return he.createElement(he.Fragment,null,Gt&&he.createElement("div",{className:"".concat(_t,"-arrow")}),he.cloneElement(te,{ref:(0,ae.Yr)(te)?X:void 0}))}),ft=Zt,De={adjustX:1,adjustY:1},fe=[0,0],M={topLeft:{points:["bl","tl"],overflow:De,offset:[0,-4],targetOffset:fe},top:{points:["bc","tc"],overflow:De,offset:[0,-4],targetOffset:fe},topRight:{points:["br","tr"],overflow:De,offset:[0,-4],targetOffset:fe},bottomLeft:{points:["tl","bl"],overflow:De,offset:[0,4],targetOffset:fe},bottom:{points:["tc","bc"],overflow:De,offset:[0,4],targetOffset:fe},bottomRight:{points:["tr","br"],overflow:De,offset:[0,4],targetOffset:fe}},C=M,W=["arrow","prefixCls","transitionName","animation","align","placement","placements","getPopupContainer","showAction","hideAction","overlayClassName","overlayStyle","visible","trigger","autoFocus","overlay","children","onVisibleChange"];function ie(J,dt){var Et,Gt=J.arrow,_t=Gt===void 0?!1:Gt,te=J.prefixCls,X=te===void 0?"rc-dropdown":te,oe=J.transitionName,F=J.animation,ke=J.align,lt=J.placement,me=lt===void 0?"bottomLeft":lt,Ye=J.placements,Fe=Ye===void 0?C:Ye,Ne=J.getPopupContainer,Ie=J.showAction,st=J.hideAction,xt=J.overlayClassName,ei=J.overlayStyle,si=J.visible,di=J.trigger,Ai=di===void 0?["hover"]:di,hi=J.autoFocus,St=J.overlay,qt=J.children,We=J.onVisibleChange,Oi=(0,Z.Z)(J,W),Q=he.useState(),Te=(0,Be.Z)(Q,2),B=Te[0],Pe=Te[1],Oe="visible"in J?si:B,Ze=he.useRef(null),mt=he.useRef(null),G=he.useRef(null);he.useImperativeHandle(dt,function(){return Ze.current});var ee=function(Ht){Pe(Ht),We==null||We(Ht)};z({visible:Oe,triggerRef:G,onVisibleChange:ee,autoFocus:hi,overlayRef:mt});var se=function(Ht){var jt=J.onOverlayClick;Pe(!1),jt&&jt(Ht)},w=function(){return he.createElement(ft,{ref:mt,overlay:St,prefixCls:X,arrow:_t})},Ae=function(){return typeof St=="function"?w:w()},Je=function(){var Ht=J.minOverlayWidthMatchTrigger,jt=J.alignPoint;return"minOverlayWidthMatchTrigger"in J?Ht:!jt},je=function(){var Ht=J.openClassName;return Ht!==void 0?Ht:"".concat(X,"-open")},Vt=he.cloneElement(qt,{className:xe()((Et=qt.props)===null||Et===void 0?void 0:Et.className,Oe&&je()),ref:(0,ae.Yr)(qt)?(0,ae.sQ)(G,(0,ae.C4)(qt)):void 0}),Bt=st;return!Bt&&Ai.indexOf("contextMenu")!==-1&&(Bt=["click"]),he.createElement(A.Z,(0,b.Z)({builtinPlacements:Fe},Oi,{prefixCls:X,ref:Ze,popupClassName:xe()(xt,(0,de.Z)({},"".concat(X,"-show-arrow"),_t)),popupStyle:ei,action:Ai,showAction:Ie,hideAction:Bt,popupPlacement:me,popupAlign:ke,popupTransitionName:oe,popupAnimation:F,popupVisible:Oe,stretch:Je()?"minWidth":"",popup:Ae(),onPopupVisibleChange:ee,onPopupClick:se,getPopupContainer:Ne}),Vt)}var ge=he.forwardRef(ie),Xe=ge},28321:function(Pi,wt,$){"use strict";$.d(wt,{iz:function(){return ht},ck:function(){return Qe},BW:function(){return Se},sN:function(){return Qe},Wd:function(){return Me},ZP:function(){return it},Xl:function(){return Et}});var b=$(32855),de=$(74430),Be=$(27247),Z=$(3300),A=$(11913),g=$(43079),xe=$(92310),ae=$.n(xe),he=$(11780),ot=$(18929),at=$(13697),Re=$(48736),D=$(59301),z=$(4676),Zt=D.createContext(null);function ft(k,H){return k===void 0?null:"".concat(k,"-").concat(H)}function De(k){var H=D.useContext(Zt);return ft(H,k)}var fe=$(80547),M=["children","locked"],C=D.createContext(null);function W(k,H){var ne=(0,Be.Z)({},k);return Object.keys(H).forEach(function(q){var le=H[q];le!==void 0&&(ne[q]=le)}),ne}function ie(k){var H=k.children,ne=k.locked,q=(0,g.Z)(k,M),le=D.useContext(C),ye=(0,fe.Z)(function(){return W(le,q)},[le,q],function(Le,Ke){return!ne&&(Le[0]!==Ke[0]||!(0,at.Z)(Le[1],Ke[1],!0))});return D.createElement(C.Provider,{value:ye},H)}var ge=[],Xe=D.createContext(null);function J(){return D.useContext(Xe)}var dt=D.createContext(ge);function Et(k){var H=D.useContext(dt);return D.useMemo(function(){return k!==void 0?[].concat((0,Z.Z)(H),[k]):H},[H,k])}var Gt=D.createContext(null),_t=D.createContext({}),te=_t,X=$(29194);function oe(k){var H=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if((0,X.Z)(k)){var ne=k.nodeName.toLowerCase(),q=["input","select","textarea","button"].includes(ne)||k.isContentEditable||ne==="a"&&!!k.getAttribute("href"),le=k.getAttribute("tabindex"),ye=Number(le),Le=null;return le&&!Number.isNaN(ye)?Le=ye:q&&Le===null&&(Le=0),q&&k.disabled&&(Le=null),Le!==null&&(Le>=0||H&&Le<0)}return!1}function F(k){var H=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,ne=(0,Z.Z)(k.querySelectorAll("*")).filter(function(q){return oe(q,H)});return oe(k,H)&&ne.unshift(k),ne}var ke=null;function lt(){ke=document.activeElement}function me(){ke=null}function Ye(){if(ke)try{ke.focus()}catch(k){}}function Fe(k,H){if(H.keyCode===9){var ne=F(k),q=ne[H.shiftKey?0:ne.length-1],le=q===document.activeElement||k===document.activeElement;if(le){var ye=ne[H.shiftKey?ne.length-1:0];ye.focus(),H.preventDefault()}}}var Ne=$(10228),Ie=$(16089),st=Ne.Z.LEFT,xt=Ne.Z.RIGHT,ei=Ne.Z.UP,si=Ne.Z.DOWN,di=Ne.Z.ENTER,Ai=Ne.Z.ESC,hi=Ne.Z.HOME,St=Ne.Z.END,qt=[ei,si,st,xt];function We(k,H,ne,q){var le,ye="prev",Le="next",Ke="children",Ut="parent";if(k==="inline"&&q===di)return{inlineTrigger:!0};var nt=(0,de.Z)((0,de.Z)({},ei,ye),si,Le),Pt=(0,de.Z)((0,de.Z)((0,de.Z)((0,de.Z)({},st,ne?Le:ye),xt,ne?ye:Le),si,Ke),di,Ke),Ct=(0,de.Z)((0,de.Z)((0,de.Z)((0,de.Z)((0,de.Z)((0,de.Z)({},ei,ye),si,Le),di,Ke),Ai,Ut),st,ne?Ke:Ut),xt,ne?Ut:Ke),Dt={inline:nt,horizontal:Pt,vertical:Ct,inlineSub:nt,horizontalSub:Ct,verticalSub:Ct},$t=(le=Dt["".concat(k).concat(H?"":"Sub")])===null||le===void 0?void 0:le[q];switch($t){case ye:return{offset:-1,sibling:!0};case Le:return{offset:1,sibling:!0};case Ut:return{offset:-1,sibling:!1};case Ke:return{offset:1,sibling:!1};default:return null}}function Oi(k){for(var H=k;H;){if(H.getAttribute("data-menu-list"))return H;H=H.parentElement}return null}function Q(k,H){for(var ne=k||document.activeElement;ne;){if(H.has(ne))return ne;ne=ne.parentElement}return null}function Te(k,H){var ne=F(k,!0);return ne.filter(function(q){return H.has(q)})}function B(k,H,ne){var q=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;if(!k)return null;var le=Te(k,H),ye=le.length,Le=le.findIndex(function(Ke){return ne===Ke});return q<0?Le===-1?Le=ye-1:Le-=1:q>0&&(Le+=1),Le=(Le+ye)%ye,le[Le]}var Pe=function(H,ne){var q=new Set,le=new Map,ye=new Map;return H.forEach(function(Le){var Ke=document.querySelector("[data-menu-id='".concat(ft(ne,Le),"']"));Ke&&(q.add(Ke),ye.set(Ke,Le),le.set(Le,Ke))}),{elements:q,key2element:le,element2key:ye}};function Oe(k,H,ne,q,le,ye,Le,Ke,Ut,nt){var Pt=D.useRef(),Ct=D.useRef();Ct.current=H;var Dt=function(){Ie.Z.cancel(Pt.current)};return D.useEffect(function(){return function(){Dt()}},[]),function($t){var zt=$t.which;if([].concat(qt,[di,Ai,hi,St]).includes(zt)){var ni=ye(),At=Pe(ni,q),Ot=At,pi=Ot.elements,Wt=Ot.key2element,Kt=Ot.element2key,Ei=Wt.get(H),ti=Q(Ei,pi),oi=Kt.get(ti),ji=We(k,Le(oi,!0).length===1,ne,zt);if(!ji&&zt!==hi&&zt!==St)return;(qt.includes(zt)||[hi,St].includes(zt))&&$t.preventDefault();var bi=function(Ci){if(Ci){var fs=Ci,ci=Ci.querySelector("a");ci!=null&&ci.getAttribute("href")&&(fs=ci);var ds=Kt.get(Ci);Ke(ds),Dt(),Pt.current=(0,Ie.Z)(function(){Ct.current===ds&&fs.focus()})}};if([hi,St].includes(zt)||ji.sibling||!ti){var li;!ti||k==="inline"?li=le.current:li=Oi(ti);var ui,zi=Te(li,pi);zt===hi?ui=zi[0]:zt===St?ui=zi[zi.length-1]:ui=B(li,pi,ti,ji.offset),bi(ui)}else if(ji.inlineTrigger)Ut(oi);else if(ji.offset>0)Ut(oi,!0),Dt(),Pt.current=(0,Ie.Z)(function(){At=Pe(ni,q);var Xi=ti.getAttribute("aria-controls"),Ci=document.getElementById(Xi),fs=B(Ci,At.elements);bi(fs)},5);else if(ji.offset<0){var $i=Le(oi,!0),Jt=$i[$i.length-2],es=Wt.get(Jt);Ut(Jt,!1),bi(es)}}nt==null||nt($t)}}function Ze(k){Promise.resolve().then(k)}var mt="__RC_UTIL_PATH_SPLIT__",G=function(H){return H.join(mt)},ee=function(H){return H.split(mt)},se="rc-menu-more";function w(){var k=D.useState({}),H=(0,A.Z)(k,2),ne=H[1],q=(0,D.useRef)(new Map),le=(0,D.useRef)(new Map),ye=D.useState([]),Le=(0,A.Z)(ye,2),Ke=Le[0],Ut=Le[1],nt=(0,D.useRef)(0),Pt=(0,D.useRef)(!1),Ct=function(){Pt.current||ne({})},Dt=(0,D.useCallback)(function(Wt,Kt){var Ei=G(Kt);le.current.set(Ei,Wt),q.current.set(Wt,Ei),nt.current+=1;var ti=nt.current;Ze(function(){ti===nt.current&&Ct()})},[]),$t=(0,D.useCallback)(function(Wt,Kt){var Ei=G(Kt);le.current.delete(Ei),q.current.delete(Wt)},[]),zt=(0,D.useCallback)(function(Wt){Ut(Wt)},[]),ni=(0,D.useCallback)(function(Wt,Kt){var Ei=q.current.get(Wt)||"",ti=ee(Ei);return Kt&&Ke.includes(ti[0])&&ti.unshift(se),ti},[Ke]),At=(0,D.useCallback)(function(Wt,Kt){return Wt.filter(function(Ei){return Ei!==void 0}).some(function(Ei){var ti=ni(Ei,!0);return ti.includes(Kt)})},[ni]),Ot=function(){var Kt=(0,Z.Z)(q.current.keys());return Ke.length&&Kt.push(se),Kt},pi=(0,D.useCallback)(function(Wt){var Kt="".concat(q.current.get(Wt)).concat(mt),Ei=new Set;return(0,Z.Z)(le.current.keys()).forEach(function(ti){ti.startsWith(Kt)&&Ei.add(le.current.get(ti))}),Ei},[]);return D.useEffect(function(){return function(){Pt.current=!0}},[]),{registerPath:Dt,unregisterPath:$t,refreshOverflowKeys:zt,isSubPathKey:At,getKeyPath:ni,getKeys:Ot,getSubPathKeys:pi}}function Ae(k){var H=D.useRef(k);H.current=k;var ne=D.useCallback(function(){for(var q,le=arguments.length,ye=new Array(le),Le=0;Le<le;Le++)ye[Le]=arguments[Le];return(q=H.current)===null||q===void 0?void 0:q.call.apply(q,[H].concat(ye))},[]);return k?ne:void 0}var Je=Math.random().toFixed(5).toString().slice(2),je=0;function Vt(k){var H=(0,ot.Z)(k,{value:k}),ne=(0,A.Z)(H,2),q=ne[0],le=ne[1];return D.useEffect(function(){je+=1;var ye="".concat(Je,"-").concat(je);le("rc-menu-uuid-".concat(ye))},[]),q}var Bt=$(33377),Lt=$(93912),Ht=$(18881),jt=$(85461),Xt=$(2738),Ii=$(8654);function pe(k,H,ne,q){var le=D.useContext(C),ye=le.activeKey,Le=le.onActive,Ke=le.onInactive,Ut={active:ye===k};return H||(Ut.onMouseEnter=function(nt){ne==null||ne({key:k,domEvent:nt}),Le(k)},Ut.onMouseLeave=function(nt){q==null||q({key:k,domEvent:nt}),Ke(k)}),Ut}function Ft(k){var H=D.useContext(C),ne=H.mode,q=H.rtl,le=H.inlineIndent;if(ne!=="inline")return null;var ye=k;return q?{paddingRight:ye*le}:{paddingLeft:ye*le}}function qi(k){var H=k.icon,ne=k.props,q=k.children,le;return H===null||H===!1?null:(typeof H=="function"?le=D.createElement(H,(0,Be.Z)({},ne)):typeof H!="boolean"&&(le=H),le||q||null)}var Ki=["item"];function Mi(k){var H=k.item,ne=(0,g.Z)(k,Ki);return Object.defineProperty(ne,"item",{get:function(){return(0,Re.ZP)(!1,"`info.item` is deprecated since we will move to function component that not provides React Node instance in future."),H}}),ne}var rs=["title","attribute","elementRef"],cs=["style","className","eventKey","warnKey","disabled","itemIcon","children","role","onMouseEnter","onMouseLeave","onClick","onKeyDown","onFocus"],Hi=["active"],Ti=function(k){(0,Ht.Z)(ne,k);var H=(0,jt.Z)(ne);function ne(){return(0,Bt.Z)(this,ne),H.apply(this,arguments)}return(0,Lt.Z)(ne,[{key:"render",value:function(){var le=this.props,ye=le.title,Le=le.attribute,Ke=le.elementRef,Ut=(0,g.Z)(le,rs),nt=(0,Xt.Z)(Ut,["eventKey","popupClassName","popupOffset","onTitleClick"]);return(0,Re.ZP)(!Le,"`attribute` of Menu.Item is deprecated. Please pass attribute directly."),D.createElement(he.Z.Item,(0,b.Z)({},Le,{title:typeof ye=="string"?ye:void 0},nt,{ref:Ke}))}}]),ne}(D.Component),Ji=D.forwardRef(function(k,H){var ne=k.style,q=k.className,le=k.eventKey,ye=k.warnKey,Le=k.disabled,Ke=k.itemIcon,Ut=k.children,nt=k.role,Pt=k.onMouseEnter,Ct=k.onMouseLeave,Dt=k.onClick,$t=k.onKeyDown,zt=k.onFocus,ni=(0,g.Z)(k,cs),At=De(le),Ot=D.useContext(C),pi=Ot.prefixCls,Wt=Ot.onItemClick,Kt=Ot.disabled,Ei=Ot.overflowDisabled,ti=Ot.itemIcon,oi=Ot.selectedKeys,ji=Ot.onActive,bi=D.useContext(te),li=bi._internalRenderMenuItem,ui="".concat(pi,"-item"),zi=D.useRef(),$i=D.useRef(),Jt=Kt||Le,es=(0,Ii.x1)(H,$i),Xi=Et(le),Ci=function(Gi){return{key:le,keyPath:(0,Z.Z)(Xi).reverse(),item:zi.current,domEvent:Gi}},fs=Ke||ti,ci=pe(le,Jt,Pt,Ct),ds=ci.active,Cs=(0,g.Z)(ci,Hi),Ds=oi.includes(le),vs=Ft(Xi.length),ws=function(Gi){if(!Jt){var hs=Ci(Gi);Dt==null||Dt(Mi(hs)),Wt(hs)}},as=function(Gi){if($t==null||$t(Gi),Gi.which===Ne.Z.ENTER){var hs=Ci(Gi);Dt==null||Dt(Mi(hs)),Wt(hs)}},os=function(Gi){ji(le),zt==null||zt(Gi)},ks={};k.role==="option"&&(ks["aria-selected"]=Ds);var ys=D.createElement(Ti,(0,b.Z)({ref:zi,elementRef:es,role:nt===null?"none":nt||"menuitem",tabIndex:Le?null:-1,"data-menu-id":Ei&&At?null:At},(0,Xt.Z)(ni,["extra"]),Cs,ks,{component:"li","aria-disabled":Le,style:(0,Be.Z)((0,Be.Z)({},vs),ne),className:ae()(ui,(0,de.Z)((0,de.Z)((0,de.Z)({},"".concat(ui,"-active"),ds),"".concat(ui,"-selected"),Ds),"".concat(ui,"-disabled"),Jt),q),onClick:ws,onKeyDown:as,onFocus:os}),Ut,D.createElement(qi,{props:(0,Be.Z)((0,Be.Z)({},k),{},{isSelected:Ds}),icon:fs}));return li&&(ys=li(ys,k,{selected:Ds})),ys});function Wi(k,H){var ne=k.eventKey,q=J(),le=Et(ne);return D.useEffect(function(){if(q)return q.registerPath(ne,le),function(){q.unregisterPath(ne,le)}},[le]),q?null:D.createElement(Ji,(0,b.Z)({},k,{ref:H}))}var Qe=D.forwardRef(Wi),Nt=["className","children"],kt=function(H,ne){var q=H.className,le=H.children,ye=(0,g.Z)(H,Nt),Le=D.useContext(C),Ke=Le.prefixCls,Ut=Le.mode,nt=Le.rtl;return D.createElement("ul",(0,b.Z)({className:ae()(Ke,nt&&"".concat(Ke,"-rtl"),"".concat(Ke,"-sub"),"".concat(Ke,"-").concat(Ut==="inline"?"inline":"vertical"),q),role:"menu"},ye,{"data-menu-list":!0,ref:ne}),le)},gi=D.forwardRef(kt);gi.displayName="SubMenuList";var _i=gi,yi=$(11592);function Rt(k,H){return(0,yi.Z)(k).map(function(ne,q){if(D.isValidElement(ne)){var le,ye,Le=ne.key,Ke=(le=(ye=ne.props)===null||ye===void 0?void 0:ye.eventKey)!==null&&le!==void 0?le:Le,Ut=Ke==null;Ut&&(Ke="tmp_key-".concat([].concat((0,Z.Z)(H),[q]).join("-")));var nt={key:Ke,eventKey:Ke};return D.cloneElement(ne,nt)}return ne})}var Bi=$(65030),Qt={adjustX:1,adjustY:1},Si={topLeft:{points:["bl","tl"],overflow:Qt},topRight:{points:["br","tr"],overflow:Qt},bottomLeft:{points:["tl","bl"],overflow:Qt},bottomRight:{points:["tr","br"],overflow:Qt},leftTop:{points:["tr","tl"],overflow:Qt},leftBottom:{points:["br","bl"],overflow:Qt},rightTop:{points:["tl","tr"],overflow:Qt},rightBottom:{points:["bl","br"],overflow:Qt}},Ui={topLeft:{points:["bl","tl"],overflow:Qt},topRight:{points:["br","tr"],overflow:Qt},bottomLeft:{points:["tl","bl"],overflow:Qt},bottomRight:{points:["tr","br"],overflow:Qt},rightTop:{points:["tr","tl"],overflow:Qt},rightBottom:{points:["br","bl"],overflow:Qt},leftTop:{points:["tl","tr"],overflow:Qt},leftBottom:{points:["bl","br"],overflow:Qt}},Ee=null;function d(k,H,ne){if(H)return H;if(ne)return ne[k]||ne.other}var f={horizontal:"bottomLeft",vertical:"rightTop","vertical-left":"rightTop","vertical-right":"leftTop"};function p(k){var H=k.prefixCls,ne=k.visible,q=k.children,le=k.popup,ye=k.popupStyle,Le=k.popupClassName,Ke=k.popupOffset,Ut=k.disabled,nt=k.mode,Pt=k.onVisibleChange,Ct=D.useContext(C),Dt=Ct.getPopupContainer,$t=Ct.rtl,zt=Ct.subMenuOpenDelay,ni=Ct.subMenuCloseDelay,At=Ct.builtinPlacements,Ot=Ct.triggerSubMenuAction,pi=Ct.forceSubMenuRender,Wt=Ct.rootClassName,Kt=Ct.motion,Ei=Ct.defaultMotions,ti=D.useState(!1),oi=(0,A.Z)(ti,2),ji=oi[0],bi=oi[1],li=$t?(0,Be.Z)((0,Be.Z)({},Ui),At):(0,Be.Z)((0,Be.Z)({},Si),At),ui=f[nt],zi=d(nt,Kt,Ei),$i=D.useRef(zi);nt!=="inline"&&($i.current=zi);var Jt=(0,Be.Z)((0,Be.Z)({},$i.current),{},{leavedClassName:"".concat(H,"-hidden"),removeOnLeave:!1,motionAppear:!0}),es=D.useRef();return D.useEffect(function(){return es.current=(0,Ie.Z)(function(){bi(ne)}),function(){Ie.Z.cancel(es.current)}},[ne]),D.createElement(Bi.Z,{prefixCls:H,popupClassName:ae()("".concat(H,"-popup"),(0,de.Z)({},"".concat(H,"-rtl"),$t),Le,Wt),stretch:nt==="horizontal"?"minWidth":null,getPopupContainer:Dt,builtinPlacements:li,popupPlacement:ui,popupVisible:ji,popup:le,popupStyle:ye,popupAlign:Ke&&{offset:Ke},action:Ut?[]:[Ot],mouseEnterDelay:zt,mouseLeaveDelay:ni,onPopupVisibleChange:Pt,forceRender:pi,popupMotion:Jt,fresh:!0},q)}var _=$(77900);function T(k){var H=k.id,ne=k.open,q=k.keyPath,le=k.children,ye="inline",Le=D.useContext(C),Ke=Le.prefixCls,Ut=Le.forceSubMenuRender,nt=Le.motion,Pt=Le.defaultMotions,Ct=Le.mode,Dt=D.useRef(!1);Dt.current=Ct===ye;var $t=D.useState(!Dt.current),zt=(0,A.Z)($t,2),ni=zt[0],At=zt[1],Ot=Dt.current?ne:!1;D.useEffect(function(){Dt.current&&At(!1)},[Ct]);var pi=(0,Be.Z)({},d(ye,nt,Pt));q.length>1&&(pi.motionAppear=!1);var Wt=pi.onVisibleChanged;return pi.onVisibleChanged=function(Kt){return!Dt.current&&!Kt&&At(!0),Wt==null?void 0:Wt(Kt)},ni?null:D.createElement(ie,{mode:ye,locked:!Dt.current},D.createElement(_.default,(0,b.Z)({visible:Ot},pi,{forceRender:Ut,removeOnLeave:!1,leavedClassName:"".concat(Ke,"-hidden")}),function(Kt){var Ei=Kt.className,ti=Kt.style;return D.createElement(_i,{id:H,className:Ei,style:ti},le)}))}var I=["style","className","title","eventKey","warnKey","disabled","internalPopupClose","children","itemIcon","expandIcon","popupClassName","popupOffset","popupStyle","onClick","onMouseEnter","onMouseLeave","onTitleClick","onTitleMouseEnter","onTitleMouseLeave"],O=["active"],be=D.forwardRef(function(k,H){var ne=k.style,q=k.className,le=k.title,ye=k.eventKey,Le=k.warnKey,Ke=k.disabled,Ut=k.internalPopupClose,nt=k.children,Pt=k.itemIcon,Ct=k.expandIcon,Dt=k.popupClassName,$t=k.popupOffset,zt=k.popupStyle,ni=k.onClick,At=k.onMouseEnter,Ot=k.onMouseLeave,pi=k.onTitleClick,Wt=k.onTitleMouseEnter,Kt=k.onTitleMouseLeave,Ei=(0,g.Z)(k,I),ti=De(ye),oi=D.useContext(C),ji=oi.prefixCls,bi=oi.mode,li=oi.openKeys,ui=oi.disabled,zi=oi.overflowDisabled,$i=oi.activeKey,Jt=oi.selectedKeys,es=oi.itemIcon,Xi=oi.expandIcon,Ci=oi.onItemClick,fs=oi.onOpenChange,ci=oi.onActive,ds=D.useContext(te),Cs=ds._internalRenderSubMenuItem,Ds=D.useContext(Gt),vs=Ds.isSubPathKey,ws=Et(),as="".concat(ji,"-submenu"),os=ui||Ke,ks=D.useRef(),ys=D.useRef(),gs=Pt!=null?Pt:es,Gi=Ct!=null?Ct:Xi,hs=li.includes(ye),Vi=!zi&&hs,Ps=vs(Jt,ye),ts=pe(ye,os,Wt,Kt),ls=ts.active,Ls=(0,g.Z)(ts,O),bt=D.useState(!1),Us=(0,A.Z)(bt,2),$s=Us[0],Ms=Us[1],Bs=function(is){os||Ms(is)},rn=function(is){Bs(!0),At==null||At({key:ye,domEvent:is})},fn=function(is){Bs(!1),Ot==null||Ot({key:ye,domEvent:is})},Gs=D.useMemo(function(){return ls||(bi!=="inline"?$s||vs([$i],ye):!1)},[bi,ls,$i,$s,ye,vs]),ai=Ft(ws.length),mn=function(is){os||(pi==null||pi({key:ye,domEvent:is}),bi==="inline"&&fs(ye,!hs))},gn=Ae(function(wi){ni==null||ni(Mi(wi)),Ci(wi)}),Ys=function(is){bi!=="inline"&&fs(ye,is)},Zs=function(){ci(ye)},qs=ti&&"".concat(ti,"-popup"),Vs=D.useMemo(function(){return D.createElement(qi,{icon:bi!=="horizontal"?Gi:void 0,props:(0,Be.Z)((0,Be.Z)({},k),{},{isOpen:Vi,isSubMenu:!0})},D.createElement("i",{className:"".concat(as,"-arrow")}))},[bi,Gi,k,Vi,as]),us=D.createElement("div",(0,b.Z)({role:"menuitem",style:ai,className:"".concat(as,"-title"),tabIndex:os?null:-1,ref:ks,title:typeof le=="string"?le:null,"data-menu-id":zi&&ti?null:ti,"aria-expanded":Vi,"aria-haspopup":!0,"aria-controls":qs,"aria-disabled":os,onClick:mn,onFocus:Zs},Ls),le,Vs),_s=D.useRef(bi);if(bi!=="inline"&&ws.length>1?_s.current="vertical":_s.current=bi,!zi){var Ss=_s.current;us=D.createElement(p,{mode:Ss,prefixCls:as,visible:!Ut&&Vi&&bi!=="inline",popupClassName:Dt,popupOffset:$t,popupStyle:zt,popup:D.createElement(ie,{mode:Ss==="horizontal"?"vertical":Ss},D.createElement(_i,{id:qs,ref:ys},nt)),disabled:os,onVisibleChange:Ys},us)}var Qi=D.createElement(he.Z.Item,(0,b.Z)({ref:H,role:"none"},Ei,{component:"li",style:ne,className:ae()(as,"".concat(as,"-").concat(bi),q,(0,de.Z)((0,de.Z)((0,de.Z)((0,de.Z)({},"".concat(as,"-open"),Vi),"".concat(as,"-active"),Gs),"".concat(as,"-selected"),Ps),"".concat(as,"-disabled"),os)),onMouseEnter:rn,onMouseLeave:fn}),us,!zi&&D.createElement(T,{id:qs,open:Vi,keyPath:ws},nt));return Cs&&(Qi=Cs(Qi,k,{selected:Ps,active:Gs,open:Vi,disabled:os})),D.createElement(ie,{onItemClick:gn,mode:bi==="horizontal"?"vertical":bi,itemIcon:gs,expandIcon:Gi},Qi)}),_e=D.forwardRef(function(k,H){var ne=k.eventKey,q=k.children,le=Et(ne),ye=Rt(q,le),Le=J();D.useEffect(function(){if(Le)return Le.registerPath(ne,le),function(){Le.unregisterPath(ne,le)}},[le]);var Ke;return Le?Ke=ye:Ke=D.createElement(be,(0,b.Z)({ref:H},k),ye),D.createElement(dt.Provider,{value:le},Ke)}),Me=_e,It=$(34666);function ht(k){var H=k.className,ne=k.style,q=D.useContext(C),le=q.prefixCls,ye=J();return ye?null:D.createElement("li",{role:"separator",className:ae()("".concat(le,"-item-divider"),H),style:ne})}var we=["className","title","eventKey","children"],gt=D.forwardRef(function(k,H){var ne=k.className,q=k.title,le=k.eventKey,ye=k.children,Le=(0,g.Z)(k,we),Ke=D.useContext(C),Ut=Ke.prefixCls,nt="".concat(Ut,"-item-group");return D.createElement("li",(0,b.Z)({ref:H,role:"presentation"},Le,{onClick:function(Ct){return Ct.stopPropagation()},className:ae()(nt,ne)}),D.createElement("div",{role:"presentation",className:"".concat(nt,"-title"),title:typeof q=="string"?q:void 0},q),D.createElement("ul",{role:"group",className:"".concat(nt,"-list")},ye))}),$e=D.forwardRef(function(k,H){var ne=k.eventKey,q=k.children,le=Et(ne),ye=Rt(q,le),Le=J();return Le?ye:D.createElement(gt,(0,b.Z)({ref:H},(0,Xt.Z)(k,["warnKey"])),ye)}),Se=$e,ve=["label","children","key","type","extra"];function et(k,H,ne){var q=H.item,le=H.group,ye=H.submenu,Le=H.divider;return(k||[]).map(function(Ke,Ut){if(Ke&&(0,It.Z)(Ke)==="object"){var nt=Ke,Pt=nt.label,Ct=nt.children,Dt=nt.key,$t=nt.type,zt=nt.extra,ni=(0,g.Z)(nt,ve),At=Dt!=null?Dt:"tmp-".concat(Ut);return Ct||$t==="group"?$t==="group"?D.createElement(le,(0,b.Z)({key:At},ni,{title:Pt}),et(Ct,H,ne)):D.createElement(ye,(0,b.Z)({key:At},ni,{title:Pt}),et(Ct,H,ne)):$t==="divider"?D.createElement(Le,(0,b.Z)({key:At},ni)):D.createElement(q,(0,b.Z)({key:At},ni,{extra:zt}),Pt,(!!zt||zt===0)&&D.createElement("span",{className:"".concat(ne,"-item-extra")},zt))}return null}).filter(function(Ke){return Ke})}function qe(k,H,ne,q,le){var ye=k,Le=(0,Be.Z)({divider:ht,item:Qe,group:Se,submenu:Me},q);return H&&(ye=et(H,Le,le)),Rt(ye,ne)}var Yt=["prefixCls","rootClassName","style","className","tabIndex","items","children","direction","id","mode","inlineCollapsed","disabled","disabledOverflow","subMenuOpenDelay","subMenuCloseDelay","forceSubMenuRender","defaultOpenKeys","openKeys","activeKey","defaultActiveFirst","selectable","multiple","defaultSelectedKeys","selectedKeys","onSelect","onDeselect","inlineIndent","motion","defaultMotions","triggerSubMenuAction","builtinPlacements","itemIcon","expandIcon","overflowedIndicator","overflowedIndicatorPopupClassName","getPopupContainer","onClick","onOpenChange","onKeyDown","openAnimation","openTransitionName","_internalRenderMenuItem","_internalRenderSubMenuItem","_internalComponents"],fi=[],mi=D.forwardRef(function(k,H){var ne,q=k,le=q.prefixCls,ye=le===void 0?"rc-menu":le,Le=q.rootClassName,Ke=q.style,Ut=q.className,nt=q.tabIndex,Pt=nt===void 0?0:nt,Ct=q.items,Dt=q.children,$t=q.direction,zt=q.id,ni=q.mode,At=ni===void 0?"vertical":ni,Ot=q.inlineCollapsed,pi=q.disabled,Wt=q.disabledOverflow,Kt=q.subMenuOpenDelay,Ei=Kt===void 0?.1:Kt,ti=q.subMenuCloseDelay,oi=ti===void 0?.1:ti,ji=q.forceSubMenuRender,bi=q.defaultOpenKeys,li=q.openKeys,ui=q.activeKey,zi=q.defaultActiveFirst,$i=q.selectable,Jt=$i===void 0?!0:$i,es=q.multiple,Xi=es===void 0?!1:es,Ci=q.defaultSelectedKeys,fs=q.selectedKeys,ci=q.onSelect,ds=q.onDeselect,Cs=q.inlineIndent,Ds=Cs===void 0?24:Cs,vs=q.motion,ws=q.defaultMotions,as=q.triggerSubMenuAction,os=as===void 0?"hover":as,ks=q.builtinPlacements,ys=q.itemIcon,gs=q.expandIcon,Gi=q.overflowedIndicator,hs=Gi===void 0?"...":Gi,Vi=q.overflowedIndicatorPopupClassName,Ps=q.getPopupContainer,ts=q.onClick,ls=q.onOpenChange,Ls=q.onKeyDown,bt=q.openAnimation,Us=q.openTransitionName,$s=q._internalRenderMenuItem,Ms=q._internalRenderSubMenuItem,Bs=q._internalComponents,rn=(0,g.Z)(q,Yt),fn=D.useMemo(function(){return[qe(Dt,Ct,fi,Bs,ye),qe(Dt,Ct,fi,{},ye)]},[Dt,Ct,Bs]),Gs=(0,A.Z)(fn,2),ai=Gs[0],mn=Gs[1],gn=D.useState(!1),Ys=(0,A.Z)(gn,2),Zs=Ys[0],qs=Ys[1],Vs=D.useRef(),us=Vt(zt),_s=$t==="rtl",Ss=(0,ot.Z)(bi,{value:li,postState:function(Ri){return Ri||fi}}),Qi=(0,A.Z)(Ss,2),wi=Qi[0],is=Qi[1],Rs=function(Ri){var Fi=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;function Is(){is(Ri),ls==null||ls(Ri)}Fi?(0,z.flushSync)(Is):Is()},Ks=D.useState(wi),an=(0,A.Z)(Ks,2),Xs=an[0],ki=an[1],ss=D.useRef(!1),on=D.useMemo(function(){return(At==="inline"||At==="vertical")&&Ot?["vertical",Ot]:[At,!1]},[At,Ot]),rt=(0,A.Z)(on,2),Tt=rt[0],Li=rt[1],Yi=Tt==="inline",Ni=D.useState(Tt),pn=(0,A.Z)(Ni,2),Os=pn[0],vn=pn[1],Qs=D.useState(Li),dr=(0,A.Z)(Qs,2),hr=dr[0],fr=dr[1];D.useEffect(function(){vn(Tt),fr(Li),ss.current&&(Yi?is(Xs):Rs(fi))},[Tt,Li]);var Wr=D.useState(0),Fn=(0,A.Z)(Wr,2),Mn=Fn[0],Hs=Fn[1],Bn=Mn>=ai.length-1||Os!=="horizontal"||Wt;D.useEffect(function(){Yi&&ki(wi)},[wi]),D.useEffect(function(){return ss.current=!0,function(){ss.current=!1}},[]);var yn=w(),Zn=yn.registerPath,qn=yn.unregisterPath,mr=yn.refreshOverflowKeys,Xn=yn.isSubPathKey,jr=yn.getKeyPath,Nn=yn.getKeys,gr=yn.getSubPathKeys,pr=D.useMemo(function(){return{registerPath:Zn,unregisterPath:qn}},[Zn,qn]),Js=D.useMemo(function(){return{isSubPathKey:Xn}},[Xn]);D.useEffect(function(){mr(Bn?fi:ai.slice(Mn+1).map(function(Zi){return Zi.key}))},[Mn,Bn]);var vr=(0,ot.Z)(ui||zi&&((ne=ai[0])===null||ne===void 0?void 0:ne.key),{value:ui}),Un=(0,A.Z)(vr,2),xn=Un[0],Qn=Un[1],zr=Ae(function(Zi){Qn(Zi)}),Yr=Ae(function(){Qn(void 0)});(0,D.useImperativeHandle)(H,function(){return{list:Vs.current,focus:function(Ri){var Fi,Is=Nn(),Ts=Pe(Is,us),En=Ts.elements,ms=Ts.key2element,xs=Ts.element2key,xr=Te(Vs.current,En),ue=xn!=null?xn:xr[0]?xs.get(xr[0]):(Fi=ai.find(function(Ar){return!Ar.props.disabled}))===null||Fi===void 0?void 0:Fi.key,_n=ms.get(ue);if(ue&&_n){var $n;_n==null||($n=_n.focus)===null||$n===void 0||$n.call(_n,Ri)}}}});var Zr=(0,ot.Z)(Ci||[],{value:fs,postState:function(Ri){return Array.isArray(Ri)?Ri:Ri==null?fi:[Ri]}}),Jn=(0,A.Z)(Zr,2),In=Jn[0],er=Jn[1],yr=function(Ri){if(Jt){var Fi=Ri.key,Is=In.includes(Fi),Ts;Xi?Is?Ts=In.filter(function(ms){return ms!==Fi}):Ts=[].concat((0,Z.Z)(In),[Fi]):Ts=[Fi],er(Ts);var En=(0,Be.Z)((0,Be.Z)({},Ri),{},{selectedKeys:Ts});Is?ds==null||ds(En):ci==null||ci(En)}!Xi&&wi.length&&Os!=="inline"&&Rs(fi)},Er=Ae(function(Zi){ts==null||ts(Mi(Zi)),yr(Zi)}),tr=Ae(function(Zi,Ri){var Fi=wi.filter(function(Ts){return Ts!==Zi});if(Ri)Fi.push(Zi);else if(Os!=="inline"){var Is=gr(Zi);Fi=Fi.filter(function(Ts){return!Is.has(Ts)})}(0,at.Z)(wi,Fi,!0)||Rs(Fi,!0)}),_r=function(Ri,Fi){var Is=Fi!=null?Fi:!wi.includes(Ri);tr(Ri,Is)},Sr=Oe(Os,xn,_s,us,Vs,Nn,jr,Qn,_r,Ls);D.useEffect(function(){qs(!0)},[]);var qr=D.useMemo(function(){return{_internalRenderMenuItem:$s,_internalRenderSubMenuItem:Ms}},[$s,Ms]),Tr=Os!=="horizontal"||Wt?ai:ai.map(function(Zi,Ri){return D.createElement(ie,{key:Zi.key,overflowDisabled:Ri>Mn},Zi)}),Cn=D.createElement(he.Z,(0,b.Z)({id:zt,ref:Vs,prefixCls:"".concat(ye,"-overflow"),component:"ul",itemComponent:Qe,className:ae()(ye,"".concat(ye,"-root"),"".concat(ye,"-").concat(Os),Ut,(0,de.Z)((0,de.Z)({},"".concat(ye,"-inline-collapsed"),hr),"".concat(ye,"-rtl"),_s),Le),dir:$t,style:Ke,role:"menu",tabIndex:Pt,data:Tr,renderRawItem:function(Ri){return Ri},renderRawRest:function(Ri){var Fi=Ri.length,Is=Fi?ai.slice(-Fi):null;return D.createElement(Me,{eventKey:se,title:hs,disabled:Bn,internalPopupClose:Fi===0,popupClassName:Vi},Is)},maxCount:Os!=="horizontal"||Wt?he.Z.INVALIDATE:he.Z.RESPONSIVE,ssr:"full","data-menu-list":!0,onVisibleChange:function(Ri){Hs(Ri)},onKeyDown:Sr},rn));return D.createElement(te.Provider,{value:qr},D.createElement(Zt.Provider,{value:us},D.createElement(ie,{prefixCls:ye,rootClassName:Le,mode:Os,openKeys:wi,rtl:_s,disabled:pi,motion:Zs?vs:null,defaultMotions:Zs?ws:null,activeKey:xn,onActive:zr,onInactive:Yr,selectedKeys:In,inlineIndent:Ds,subMenuOpenDelay:Ei,subMenuCloseDelay:oi,forceSubMenuRender:ji,builtinPlacements:ks,triggerSubMenuAction:os,getPopupContainer:Ps,itemIcon:ys,expandIcon:gs,onItemClick:Er,onOpenChange:tr},D.createElement(Gt.Provider,{value:Js},Cn),D.createElement("div",{style:{display:"none"},"aria-hidden":!0},D.createElement(Xe.Provider,{value:pr},mn)))))}),Ce=mi,ze=Ce;ze.Item=Qe,ze.SubMenu=Me,ze.ItemGroup=Se,ze.Divider=ht;var it=ze},11780:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return lt}});var b=$(32855),de=$(27247),Be=$(11913),Z=$(43079),A=$(59301),g=$(92310),xe=$.n(g),ae=$(29301),he=$(34280),ot=["prefixCls","invalidate","item","renderItem","responsive","responsiveDisabled","registerSize","itemKey","className","style","children","display","order","component"],at=void 0;function Re(me,Ye){var Fe=me.prefixCls,Ne=me.invalidate,Ie=me.item,st=me.renderItem,xt=me.responsive,ei=me.responsiveDisabled,si=me.registerSize,di=me.itemKey,Ai=me.className,hi=me.style,St=me.children,qt=me.display,We=me.order,Oi=me.component,Q=Oi===void 0?"div":Oi,Te=(0,Z.Z)(me,ot),B=xt&&!qt;function Pe(ee){si(di,ee)}A.useEffect(function(){return function(){Pe(null)}},[]);var Oe=st&&Ie!==at?st(Ie,{index:We}):St,Ze;Ne||(Ze={opacity:B?0:1,height:B?0:at,overflowY:B?"hidden":at,order:xt?We:at,pointerEvents:B?"none":at,position:B?"absolute":at});var mt={};B&&(mt["aria-hidden"]=!0);var G=A.createElement(Q,(0,b.Z)({className:xe()(!Ne&&Fe,Ai),style:(0,de.Z)((0,de.Z)({},Ze),hi)},mt,Te,{ref:Ye}),Oe);return xt&&(G=A.createElement(ae.Z,{onResize:function(se){var w=se.offsetWidth;Pe(w)},disabled:ei},G)),G}var D=A.forwardRef(Re);D.displayName="Item";var z=D,Zt=$(6089),ft=$(4676),De=$(16089);function fe(me){if(typeof MessageChannel=="undefined")(0,De.Z)(me);else{var Ye=new MessageChannel;Ye.port1.onmessage=function(){return me()},Ye.port2.postMessage(void 0)}}function M(){var me=A.useRef(null),Ye=function(Ne){me.current||(me.current=[],fe(function(){(0,ft.unstable_batchedUpdates)(function(){me.current.forEach(function(Ie){Ie()}),me.current=null})})),me.current.push(Ne)};return Ye}function C(me,Ye){var Fe=A.useState(Ye),Ne=(0,Be.Z)(Fe,2),Ie=Ne[0],st=Ne[1],xt=(0,Zt.Z)(function(ei){me(function(){st(ei)})});return[Ie,xt]}var W=A.createContext(null),ie=["component"],ge=["className"],Xe=["className"],J=function(Ye,Fe){var Ne=A.useContext(W);if(!Ne){var Ie=Ye.component,st=Ie===void 0?"div":Ie,xt=(0,Z.Z)(Ye,ie);return A.createElement(st,(0,b.Z)({},xt,{ref:Fe}))}var ei=Ne.className,si=(0,Z.Z)(Ne,ge),di=Ye.className,Ai=(0,Z.Z)(Ye,Xe);return A.createElement(W.Provider,{value:null},A.createElement(z,(0,b.Z)({ref:Fe,className:xe()(ei,di)},si,Ai)))},dt=A.forwardRef(J);dt.displayName="RawItem";var Et=dt,Gt=["prefixCls","data","renderItem","renderRawItem","itemKey","itemWidth","ssr","style","className","maxCount","renderRest","renderRawRest","suffix","component","itemComponent","onVisibleChange"],_t="responsive",te="invalidate";function X(me){return"+ ".concat(me.length," ...")}function oe(me,Ye){var Fe=me.prefixCls,Ne=Fe===void 0?"rc-overflow":Fe,Ie=me.data,st=Ie===void 0?[]:Ie,xt=me.renderItem,ei=me.renderRawItem,si=me.itemKey,di=me.itemWidth,Ai=di===void 0?10:di,hi=me.ssr,St=me.style,qt=me.className,We=me.maxCount,Oi=me.renderRest,Q=me.renderRawRest,Te=me.suffix,B=me.component,Pe=B===void 0?"div":B,Oe=me.itemComponent,Ze=me.onVisibleChange,mt=(0,Z.Z)(me,Gt),G=hi==="full",ee=M(),se=C(ee,null),w=(0,Be.Z)(se,2),Ae=w[0],Je=w[1],je=Ae||0,Vt=C(ee,new Map),Bt=(0,Be.Z)(Vt,2),Lt=Bt[0],Ht=Bt[1],jt=C(ee,0),Xt=(0,Be.Z)(jt,2),Ii=Xt[0],pe=Xt[1],Ft=C(ee,0),qi=(0,Be.Z)(Ft,2),Ki=qi[0],Mi=qi[1],rs=C(ee,0),cs=(0,Be.Z)(rs,2),Hi=cs[0],Ti=cs[1],Ji=(0,A.useState)(null),Wi=(0,Be.Z)(Ji,2),Qe=Wi[0],Nt=Wi[1],kt=(0,A.useState)(null),gi=(0,Be.Z)(kt,2),_i=gi[0],yi=gi[1],Rt=A.useMemo(function(){return _i===null&&G?Number.MAX_SAFE_INTEGER:_i||0},[_i,Ae]),Bi=(0,A.useState)(!1),Qt=(0,Be.Z)(Bi,2),Si=Qt[0],Ui=Qt[1],Ee="".concat(Ne,"-item"),d=Math.max(Ii,Ki),f=We===_t,p=st.length&&f,_=We===te,T=p||typeof We=="number"&&st.length>We,I=(0,A.useMemo)(function(){var ze=st;return p?Ae===null&&G?ze=st:ze=st.slice(0,Math.min(st.length,je/Ai)):typeof We=="number"&&(ze=st.slice(0,We)),ze},[st,Ai,Ae,We,p]),O=(0,A.useMemo)(function(){return p?st.slice(Rt+1):st.slice(I.length)},[st,I,p,Rt]),be=(0,A.useCallback)(function(ze,it){var k;return typeof si=="function"?si(ze):(k=si&&(ze==null?void 0:ze[si]))!==null&&k!==void 0?k:it},[si]),_e=(0,A.useCallback)(xt||function(ze){return ze},[xt]);function Me(ze,it,k){_i===ze&&(it===void 0||it===Qe)||(yi(ze),k||(Ui(ze<st.length-1),Ze==null||Ze(ze)),it!==void 0&&Nt(it))}function It(ze,it){Je(it.clientWidth)}function ht(ze,it){Ht(function(k){var H=new Map(k);return it===null?H.delete(ze):H.set(ze,it),H})}function we(ze,it){Mi(it),pe(Ki)}function gt(ze,it){Ti(it)}function $e(ze){return Lt.get(be(I[ze],ze))}(0,he.Z)(function(){if(je&&typeof d=="number"&&I){var ze=Hi,it=I.length,k=it-1;if(!it){Me(0,null);return}for(var H=0;H<it;H+=1){var ne=$e(H);if(G&&(ne=ne||0),ne===void 0){Me(H-1,void 0,!0);break}if(ze+=ne,k===0&&ze<=je||H===k-1&&ze+$e(k)<=je){Me(k,null);break}else if(ze+d>je){Me(H-1,ze-ne-Hi+Ki);break}}Te&&$e(0)+Hi>je&&Nt(null)}},[je,Lt,Ki,Hi,be,I]);var Se=Si&&!!O.length,ve={};Qe!==null&&p&&(ve={position:"absolute",left:Qe,top:0});var et={prefixCls:Ee,responsive:p,component:Oe,invalidate:_},qe=ei?function(ze,it){var k=be(ze,it);return A.createElement(W.Provider,{key:k,value:(0,de.Z)((0,de.Z)({},et),{},{order:it,item:ze,itemKey:k,registerSize:ht,display:it<=Rt})},ei(ze,it))}:function(ze,it){var k=be(ze,it);return A.createElement(z,(0,b.Z)({},et,{order:it,key:k,item:ze,renderItem:_e,itemKey:k,registerSize:ht,display:it<=Rt}))},Yt={order:Se?Rt:Number.MAX_SAFE_INTEGER,className:"".concat(Ee,"-rest"),registerSize:we,display:Se},fi=Oi||X,mi=Q?A.createElement(W.Provider,{value:(0,de.Z)((0,de.Z)({},et),Yt)},Q(O)):A.createElement(z,(0,b.Z)({},et,Yt),typeof fi=="function"?fi(O):fi),Ce=A.createElement(Pe,(0,b.Z)({className:xe()(!_&&Ne,qt),style:St,ref:Ye},mt),I.map(qe),T?mi:null,Te&&A.createElement(z,(0,b.Z)({},et,{responsive:f,responsiveDisabled:!p,order:Rt,className:"".concat(Ee,"-suffix"),registerSize:gt,display:!0,style:ve}),Te));return f?A.createElement(ae.Z,{onResize:It,disabled:!p},Ce):Ce}var F=A.forwardRef(oe);F.displayName="Overflow",F.Item=Et,F.RESPONSIVE=_t,F.INVALIDATE=te;var ke=F,lt=ke},29301:function(Pi,wt,$){"use strict";$.d(wt,{Z:function(){return te}});var b=$(32855),de=$(59301),Be=$(11592),Z=$(48736),A=$(27247),g=$(34666),xe=$(76846),ae=$(8654),he=de.createContext(null);function ot(X){var oe=X.children,F=X.onBatchResize,ke=de.useRef(0),lt=de.useRef([]),me=de.useContext(he),Ye=de.useCallback(function(Fe,Ne,Ie){ke.current+=1;var st=ke.current;lt.current.push({size:Fe,element:Ne,data:Ie}),Promise.resolve().then(function(){st===ke.current&&(F==null||F(lt.current),lt.current=[])}),me==null||me(Fe,Ne,Ie)},[F,me]);return de.createElement(he.Provider,{value:Ye},oe)}var at=$(76374),Re=new Map;function D(X){X.forEach(function(oe){var F,ke=oe.target;(F=Re.get(ke))===null||F===void 0||F.forEach(function(lt){return lt(ke)})})}var z=new at.Z(D),Zt=null,ft=null;function De(X,oe){Re.has(X)||(Re.set(X,new Set),z.observe(X)),Re.get(X).add(oe)}function fe(X,oe){Re.has(X)&&(Re.get(X).delete(oe),Re.get(X).size||(z.unobserve(X),Re.delete(X)))}var M=$(33377),C=$(93912),W=$(18881),ie=$(85461),ge=function(X){(0,W.Z)(F,X);var oe=(0,ie.Z)(F);function F(){return(0,M.Z)(this,F),oe.apply(this,arguments)}return(0,C.Z)(F,[{key:"render",value:function(){return this.props.children}}]),F}(de.Component);function Xe(X,oe){var F=X.children,ke=X.disabled,lt=de.useRef(null),me=de.useRef(null),Ye=de.useContext(he),Fe=typeof F=="function",Ne=Fe?F(lt):F,Ie=de.useRef({width:-1,height:-1,offsetWidth:-1,offsetHeight:-1}),st=!Fe&&de.isValidElement(Ne)&&(0,ae.Yr)(Ne),xt=st?(0,ae.C4)(Ne):null,ei=(0,ae.x1)(xt,lt),si=function(){var St;return(0,xe.ZP)(lt.current)||(lt.current&&(0,g.Z)(lt.current)==="object"?(0,xe.ZP)((St=lt.current)===null||St===void 0?void 0:St.nativeElement):null)||(0,xe.ZP)(me.current)};de.useImperativeHandle(oe,function(){return si()});var di=de.useRef(X);di.current=X;var Ai=de.useCallback(function(hi){var St=di.current,qt=St.onResize,We=St.data,Oi=hi.getBoundingClientRect(),Q=Oi.width,Te=Oi.height,B=hi.offsetWidth,Pe=hi.offsetHeight,Oe=Math.floor(Q),Ze=Math.floor(Te);if(Ie.current.width!==Oe||Ie.current.height!==Ze||Ie.current.offsetWidth!==B||Ie.current.offsetHeight!==Pe){var mt={width:Oe,height:Ze,offsetWidth:B,offsetHeight:Pe};Ie.current=mt;var G=B===Math.round(Q)?Q:B,ee=Pe===Math.round(Te)?Te:Pe,se=(0,A.Z)((0,A.Z)({},mt),{},{offsetWidth:G,offsetHeight:ee});Ye==null||Ye(se,hi,We),qt&&Promise.resolve().then(function(){qt(se,hi)})}},[]);return de.useEffect(function(){var hi=si();return hi&&!ke&&De(hi,Ai),function(){return fe(hi,Ai)}},[lt.current,ke]),de.createElement(ge,{ref:me},st?de.cloneElement(Ne,{ref:ei}):Ne)}var J=de.forwardRef(Xe),dt=J,Et="rc-observer-key";function Gt(X,oe){var F=X.children,ke=typeof F=="function"?[F]:(0,Be.Z)(F);return ke.map(function(lt,me){var Ye=(lt==null?void 0:lt.key)||"".concat(Et,"-").concat(me);return de.createElement(dt,(0,b.Z)({},X,{key:Ye,ref:me===0?oe:void 0}),lt)})}var _t=de.forwardRef(Gt);_t.Collection=ot;var te=_t},29125:function(Pi,wt,$){"use strict";$.d(wt,{G:function(){return Z},Z:function(){return fe}});var b=$(92310),de=$.n(b),Be=$(59301);function Z(M){var C=M.children,W=M.prefixCls,ie=M.id,ge=M.overlayInnerStyle,Xe=M.bodyClassName,J=M.className,dt=M.style;return Be.createElement("div",{className:de()("".concat(W,"-content"),J),style:dt},Be.createElement("div",{className:de()("".concat(W,"-inner"),Xe),id:ie,role:"tooltip",style:ge},typeof C=="function"?C():C))}var A=$(32855),g=$(27247),xe=$(43079),ae=$(65030),he={shiftX:64,adjustY:1},ot={adjustX:1,shiftY:!0},at=[0,0],Re={left:{points:["cr","cl"],overflow:ot,offset:[-4,0],targetOffset:at},right:{points:["cl","cr"],overflow:ot,offset:[4,0],targetOffset:at},top:{points:["bc","tc"],overflow:he,offset:[0,-4],targetOffset:at},bottom:{points:["tc","bc"],overflow:he,offset:[0,4],targetOffset:at},topLeft:{points:["bl","tl"],overflow:he,offset:[0,-4],targetOffset:at},leftTop:{points:["tr","tl"],overflow:ot,offset:[-4,0],targetOffset:at},topRight:{points:["br","tr"],overflow:he,offset:[0,-4],targetOffset:at},rightTop:{points:["tl","tr"],overflow:ot,offset:[4,0],targetOffset:at},bottomRight:{points:["tr","br"],overflow:he,offset:[0,4],targetOffset:at},rightBottom:{points:["bl","br"],overflow:ot,offset:[4,0],targetOffset:at},bottomLeft:{points:["tl","bl"],overflow:he,offset:[0,4],targetOffset:at},leftBottom:{points:["br","bl"],overflow:ot,offset:[-4,0],targetOffset:at}},D=null,z=$(80402),Zt=["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","afterVisibleChange","transitionName","animation","motion","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer","overlayInnerStyle","arrowContent","overlay","id","showArrow","classNames","styles"],ft=function(C,W){var ie=C.overlayClassName,ge=C.trigger,Xe=ge===void 0?["hover"]:ge,J=C.mouseEnterDelay,dt=J===void 0?0:J,Et=C.mouseLeaveDelay,Gt=Et===void 0?.1:Et,_t=C.overlayStyle,te=C.prefixCls,X=te===void 0?"rc-tooltip":te,oe=C.children,F=C.onVisibleChange,ke=C.afterVisibleChange,lt=C.transitionName,me=C.animation,Ye=C.motion,Fe=C.placement,Ne=Fe===void 0?"right":Fe,Ie=C.align,st=Ie===void 0?{}:Ie,xt=C.destroyTooltipOnHide,ei=xt===void 0?!1:xt,si=C.defaultVisible,di=C.getTooltipContainer,Ai=C.overlayInnerStyle,hi=C.arrowContent,St=C.overlay,qt=C.id,We=C.showArrow,Oi=We===void 0?!0:We,Q=C.classNames,Te=C.styles,B=(0,xe.Z)(C,Zt),Pe=(0,z.Z)(qt),Oe=(0,Be.useRef)(null);(0,Be.useImperativeHandle)(W,function(){return Oe.current});var Ze=(0,g.Z)({},B);"visible"in C&&(Ze.popupVisible=C.visible);var mt=function(){return Be.createElement(Z,{key:"content",prefixCls:X,id:Pe,bodyClassName:Q==null?void 0:Q.body,overlayInnerStyle:(0,g.Z)((0,g.Z)({},Ai),Te==null?void 0:Te.body)},St)},G=function(){var se=Be.Children.only(oe),w=(se==null?void 0:se.props)||{},Ae=(0,g.Z)((0,g.Z)({},w),{},{"aria-describedby":St?Pe:null});return Be.cloneElement(oe,Ae)};return Be.createElement(ae.Z,(0,A.Z)({popupClassName:de()(ie,Q==null?void 0:Q.root),prefixCls:X,popup:mt,action:Xe,builtinPlacements:Re,popupPlacement:Ne,ref:Oe,popupAlign:st,getPopupContainer:di,onPopupVisibleChange:F,afterPopupVisibleChange:ke,popupTransitionName:lt,popupAnimation:me,popupMotion:Ye,defaultPopupVisible:si,autoDestroy:ei,mouseLeaveDelay:Gt,popupStyle:(0,g.Z)((0,g.Z)({},_t),Te==null?void 0:Te.root),mouseEnterDelay:dt,arrow:Oi},Ze),G())},De=(0,Be.forwardRef)(ft),fe=De},49658:function(Pi,wt){"use strict";wt.Z=function(){if(typeof navigator=="undefined"||typeof window=="undefined")return!1;var $=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test($)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test($==null?void 0:$.substr(0,4))}},83145:function(Pi,wt,$){"use strict";Object.defineProperty(wt,"__esModule",{value:!0}),wt.CopyToClipboard=void 0;var b=Be($(59301)),de=Be($(25769));function Be(M){return M&&M.__esModule?M:{default:M}}function Z(M){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Z=function(W){return typeof W}:Z=function(W){return W&&typeof Symbol=="function"&&W.constructor===Symbol&&W!==Symbol.prototype?"symbol":typeof W},Z(M)}function A(M,C){var W=Object.keys(M);if(Object.getOwnPropertySymbols){var ie=Object.getOwnPropertySymbols(M);C&&(ie=ie.filter(function(ge){return Object.getOwnPropertyDescriptor(M,ge).enumerable})),W.push.apply(W,ie)}return W}function g(M){for(var C=1;C<arguments.length;C++){var W=arguments[C]!=null?arguments[C]:{};C%2?A(W,!0).forEach(function(ie){De(M,ie,W[ie])}):Object.getOwnPropertyDescriptors?Object.defineProperties(M,Object.getOwnPropertyDescriptors(W)):A(W).forEach(function(ie){Object.defineProperty(M,ie,Object.getOwnPropertyDescriptor(W,ie))})}return M}function xe(M,C){if(M==null)return{};var W=ae(M,C),ie,ge;if(Object.getOwnPropertySymbols){var Xe=Object.getOwnPropertySymbols(M);for(ge=0;ge<Xe.length;ge++)ie=Xe[ge],!(C.indexOf(ie)>=0)&&Object.prototype.propertyIsEnumerable.call(M,ie)&&(W[ie]=M[ie])}return W}function ae(M,C){if(M==null)return{};var W={},ie=Object.keys(M),ge,Xe;for(Xe=0;Xe<ie.length;Xe++)ge=ie[Xe],!(C.indexOf(ge)>=0)&&(W[ge]=M[ge]);return W}function he(M,C){if(!(M instanceof C))throw new TypeError("Cannot call a class as a function")}function ot(M,C){for(var W=0;W<C.length;W++){var ie=C[W];ie.enumerable=ie.enumerable||!1,ie.configurable=!0,"value"in ie&&(ie.writable=!0),Object.defineProperty(M,ie.key,ie)}}function at(M,C,W){return C&&ot(M.prototype,C),W&&ot(M,W),M}function Re(M,C){return C&&(Z(C)==="object"||typeof C=="function")?C:z(M)}function D(M){return D=Object.setPrototypeOf?Object.getPrototypeOf:function(W){return W.__proto__||Object.getPrototypeOf(W)},D(M)}function z(M){if(M===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return M}function Zt(M,C){if(typeof C!="function"&&C!==null)throw new TypeError("Super expression must either be null or a function");M.prototype=Object.create(C&&C.prototype,{constructor:{value:M,writable:!0,configurable:!0}}),C&&ft(M,C)}function ft(M,C){return ft=Object.setPrototypeOf||function(ie,ge){return ie.__proto__=ge,ie},ft(M,C)}function De(M,C,W){return C in M?Object.defineProperty(M,C,{value:W,enumerable:!0,configurable:!0,writable:!0}):M[C]=W,M}var fe=function(M){Zt(C,M);function C(){var W,ie;he(this,C);for(var ge=arguments.length,Xe=new Array(ge),J=0;J<ge;J++)Xe[J]=arguments[J];return ie=Re(this,(W=D(C)).call.apply(W,[this].concat(Xe))),De(z(ie),"onClick",function(dt){var Et=ie.props,Gt=Et.text,_t=Et.onCopy,te=Et.children,X=Et.options,oe=b.default.Children.only(te),F=(0,de.default)(Gt,X);_t&&_t(Gt,F),oe&&oe.props&&typeof oe.props.onClick=="function"&&oe.props.onClick(dt)}),ie}return at(C,[{key:"render",value:function(){var ie=this.props,ge=ie.text,Xe=ie.onCopy,J=ie.options,dt=ie.children,Et=xe(ie,["text","onCopy","options","children"]),Gt=b.default.Children.only(dt);return b.default.cloneElement(Gt,g({},Et,{onClick:this.onClick}))}}]),C}(b.default.PureComponent);wt.CopyToClipboard=fe,De(fe,"defaultProps",{onCopy:void 0,options:void 0})},56102:function(Pi,wt,$){"use strict";var b=$(83145),de=b.CopyToClipboard;de.CopyToClipboard=de,Pi.exports=de},76374:function(Pi,wt,$){"use strict";var b=function(){if(typeof Map!="undefined")return Map;function te(X,oe){var F=-1;return X.some(function(ke,lt){return ke[0]===oe?(F=lt,!0):!1}),F}return function(){function X(){this.__entries__=[]}return Object.defineProperty(X.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),X.prototype.get=function(oe){var F=te(this.__entries__,oe),ke=this.__entries__[F];return ke&&ke[1]},X.prototype.set=function(oe,F){var ke=te(this.__entries__,oe);~ke?this.__entries__[ke][1]=F:this.__entries__.push([oe,F])},X.prototype.delete=function(oe){var F=this.__entries__,ke=te(F,oe);~ke&&F.splice(ke,1)},X.prototype.has=function(oe){return!!~te(this.__entries__,oe)},X.prototype.clear=function(){this.__entries__.splice(0)},X.prototype.forEach=function(oe,F){F===void 0&&(F=null);for(var ke=0,lt=this.__entries__;ke<lt.length;ke++){var me=lt[ke];oe.call(F,me[1],me[0])}},X}()}(),de=typeof window!="undefined"&&typeof document!="undefined"&&window.document===document,Be=function(){return typeof $.g!="undefined"&&$.g.Math===Math?$.g:typeof self!="undefined"&&self.Math===Math?self:typeof window!="undefined"&&window.Math===Math?window:Function("return this")()}(),Z=function(){return typeof requestAnimationFrame=="function"?requestAnimationFrame.bind(Be):function(te){return setTimeout(function(){return te(Date.now())},1e3/60)}}(),A=2;function g(te,X){var oe=!1,F=!1,ke=0;function lt(){oe&&(oe=!1,te()),F&&Ye()}function me(){Z(lt)}function Ye(){var Fe=Date.now();if(oe){if(Fe-ke<A)return;F=!0}else oe=!0,F=!1,setTimeout(me,X);ke=Fe}return Ye}var xe=20,ae=["top","right","bottom","left","width","height","size","weight"],he=typeof MutationObserver!="undefined",ot=function(){function te(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=g(this.refresh.bind(this),xe)}return te.prototype.addObserver=function(X){~this.observers_.indexOf(X)||this.observers_.push(X),this.connected_||this.connect_()},te.prototype.removeObserver=function(X){var oe=this.observers_,F=oe.indexOf(X);~F&&oe.splice(F,1),!oe.length&&this.connected_&&this.disconnect_()},te.prototype.refresh=function(){var X=this.updateObservers_();X&&this.refresh()},te.prototype.updateObservers_=function(){var X=this.observers_.filter(function(oe){return oe.gatherActive(),oe.hasActive()});return X.forEach(function(oe){return oe.broadcastActive()}),X.length>0},te.prototype.connect_=function(){!de||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),he?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},te.prototype.disconnect_=function(){!de||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},te.prototype.onTransitionEnd_=function(X){var oe=X.propertyName,F=oe===void 0?"":oe,ke=ae.some(function(lt){return!!~F.indexOf(lt)});ke&&this.refresh()},te.getInstance=function(){return this.instance_||(this.instance_=new te),this.instance_},te.instance_=null,te}(),at=function(te,X){for(var oe=0,F=Object.keys(X);oe<F.length;oe++){var ke=F[oe];Object.defineProperty(te,ke,{value:X[ke],enumerable:!1,writable:!1,configurable:!0})}return te},Re=function(te){var X=te&&te.ownerDocument&&te.ownerDocument.defaultView;return X||Be},D=ge(0,0,0,0);function z(te){return parseFloat(te)||0}function Zt(te){for(var X=[],oe=1;oe<arguments.length;oe++)X[oe-1]=arguments[oe];return X.reduce(function(F,ke){var lt=te["border-"+ke+"-width"];return F+z(lt)},0)}function ft(te){for(var X=["top","right","bottom","left"],oe={},F=0,ke=X;F<ke.length;F++){var lt=ke[F],me=te["padding-"+lt];oe[lt]=z(me)}return oe}function De(te){var X=te.getBBox();return ge(0,0,X.width,X.height)}function fe(te){var X=te.clientWidth,oe=te.clientHeight;if(!X&&!oe)return D;var F=Re(te).getComputedStyle(te),ke=ft(F),lt=ke.left+ke.right,me=ke.top+ke.bottom,Ye=z(F.width),Fe=z(F.height);if(F.boxSizing==="border-box"&&(Math.round(Ye+lt)!==X&&(Ye-=Zt(F,"left","right")+lt),Math.round(Fe+me)!==oe&&(Fe-=Zt(F,"top","bottom")+me)),!C(te)){var Ne=Math.round(Ye+lt)-X,Ie=Math.round(Fe+me)-oe;Math.abs(Ne)!==1&&(Ye-=Ne),Math.abs(Ie)!==1&&(Fe-=Ie)}return ge(ke.left,ke.top,Ye,Fe)}var M=function(){return typeof SVGGraphicsElement!="undefined"?function(te){return te instanceof Re(te).SVGGraphicsElement}:function(te){return te instanceof Re(te).SVGElement&&typeof te.getBBox=="function"}}();function C(te){return te===Re(te).document.documentElement}function W(te){return de?M(te)?De(te):fe(te):D}function ie(te){var X=te.x,oe=te.y,F=te.width,ke=te.height,lt=typeof DOMRectReadOnly!="undefined"?DOMRectReadOnly:Object,me=Object.create(lt.prototype);return at(me,{x:X,y:oe,width:F,height:ke,top:oe,right:X+F,bottom:ke+oe,left:X}),me}function ge(te,X,oe,F){return{x:te,y:X,width:oe,height:F}}var Xe=function(){function te(X){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=ge(0,0,0,0),this.target=X}return te.prototype.isActive=function(){var X=W(this.target);return this.contentRect_=X,X.width!==this.broadcastWidth||X.height!==this.broadcastHeight},te.prototype.broadcastRect=function(){var X=this.contentRect_;return this.broadcastWidth=X.width,this.broadcastHeight=X.height,X},te}(),J=function(){function te(X,oe){var F=ie(oe);at(this,{target:X,contentRect:F})}return te}(),dt=function(){function te(X,oe,F){if(this.activeObservations_=[],this.observations_=new b,typeof X!="function")throw new TypeError("The callback provided as parameter 1 is not a function.");this.callback_=X,this.controller_=oe,this.callbackCtx_=F}return te.prototype.observe=function(X){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if(!(typeof Element=="undefined"||!(Element instanceof Object))){if(!(X instanceof Re(X).Element))throw new TypeError('parameter 1 is not of type "Element".');var oe=this.observations_;oe.has(X)||(oe.set(X,new Xe(X)),this.controller_.addObserver(this),this.controller_.refresh())}},te.prototype.unobserve=function(X){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if(!(typeof Element=="undefined"||!(Element instanceof Object))){if(!(X instanceof Re(X).Element))throw new TypeError('parameter 1 is not of type "Element".');var oe=this.observations_;oe.has(X)&&(oe.delete(X),oe.size||this.controller_.removeObserver(this))}},te.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},te.prototype.gatherActive=function(){var X=this;this.clearActive(),this.observations_.forEach(function(oe){oe.isActive()&&X.activeObservations_.push(oe)})},te.prototype.broadcastActive=function(){if(this.hasActive()){var X=this.callbackCtx_,oe=this.activeObservations_.map(function(F){return new J(F.target,F.broadcastRect())});this.callback_.call(X,oe,X),this.clearActive()}},te.prototype.clearActive=function(){this.activeObservations_.splice(0)},te.prototype.hasActive=function(){return this.activeObservations_.length>0},te}(),Et=typeof WeakMap!="undefined"?new WeakMap:new b,Gt=function(){function te(X){if(!(this instanceof te))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var oe=ot.getInstance(),F=new dt(X,oe,this);Et.set(this,F)}return te}();["observe","unobserve","disconnect"].forEach(function(te){Gt.prototype[te]=function(){var X;return(X=Et.get(this))[te].apply(X,arguments)}});var _t=function(){return typeof Be.ResizeObserver!="undefined"?Be.ResizeObserver:Gt}();wt.Z=_t},98040:function(Pi){Pi.exports=function(){var wt=document.getSelection();if(!wt.rangeCount)return function(){};for(var $=document.activeElement,b=[],de=0;de<wt.rangeCount;de++)b.push(wt.getRangeAt(de));switch($.tagName.toUpperCase()){case"INPUT":case"TEXTAREA":$.blur();break;default:$=null;break}return wt.removeAllRanges(),function(){wt.type==="Caret"&&wt.removeAllRanges(),wt.rangeCount||b.forEach(function(Be){wt.addRange(Be)}),$&&$.focus()}}},82059:function(Pi){var wt=arguments[3],$=arguments[4],b=arguments[5],de=JSON.stringify;Pi.exports=function(Be,Z){for(var A,g=Object.keys(b),xe=0,ae=g.length;xe<ae;xe++){var he=g[xe],ot=b[he].exports;if(ot===Be||ot&&ot.default===Be){A=he;break}}if(!A){A=Math.floor(Math.pow(16,8)*Math.random()).toString(16);for(var at={},xe=0,ae=g.length;xe<ae;xe++){var he=g[xe];at[he]=he}$[A]=["function(require,module,exports){"+Be+"(self); }",at]}var Re=Math.floor(Math.pow(16,8)*Math.random()).toString(16),D={};D[A]=A,$[Re]=["function(require,module,exports){var f = require("+de(A)+");(f.default ? f.default : f)(self);}",D];var z={};Zt(Re);function Zt(W){z[W]=!0;for(var ie in $[W][1]){var ge=$[W][1][ie];z[ge]||Zt(ge)}}var ft="("+wt+")({"+Object.keys(z).map(function(W){return de(W)+":["+$[W][0]+","+de($[W][1])+"]"}).join(",")+"},{},["+de(Re)+"])",De=window.URL||window.webkitURL||window.mozURL||window.msURL,fe=new Blob([ft],{type:"text/javascript"});if(Z&&Z.bare)return fe;var M=De.createObjectURL(fe),C=new Worker(M);return C.objectURL=M,C}},68535:function(Pi,wt,$){"use strict";$.d(wt,{ZP:function(){return Rn}});const b=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},de=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Be},Be=Number.MAX_SAFE_INTEGER||9007199254740991;let Z=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}({}),A=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}({}),g=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 xe={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ae={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class he{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ot{constructor(e,t,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 he(e),this.fast_=new he(t),this.defaultTTFB_=s,this.ttfb_=new he(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new he(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new he(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new he(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function at(a,e,t){return(e=ft(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function Re(){return Re=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},Re.apply(null,arguments)}function D(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(a);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),t.push.apply(t,i)}return t}function z(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?D(Object(t),!0).forEach(function(i){at(a,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):D(Object(t)).forEach(function(i){Object.defineProperty(a,i,Object.getOwnPropertyDescriptor(t,i))})}return a}function Zt(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var i=t.call(a,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function ft(a){var e=Zt(a,"string");return typeof e=="symbol"?e:e+""}class De{constructor(e,t){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=`[${e}]:`;this.trace=fe,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const fe=function(){},M={trace:fe,debug:fe,log:fe,warn:fe,info:fe,error:fe};function C(){return Re({},M)}function W(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):fe}function ie(a,e,t){return e[a]?e[a].bind(e):W(a,t)}const ge=C();function Xe(a,e,t){const i=C();if(typeof console=="object"&&a===!0||typeof a=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=ie(n,a,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.11`)}catch(n){return C()}s.forEach(n=>{ge[n]=ie(n,a)})}else Re(ge,i);return i}const J=ge;function dt(a=!0){return typeof self=="undefined"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Et(a){return typeof self!="undefined"&&a===self.ManagedMediaSource}function Gt(a,e){const t=Object.keys(a),i=Object.keys(e),s=t.length,n=i.length;return!s||!n||s===n&&!t.some(r=>i.indexOf(r)===-1)}function _t(a,e=!1){if(typeof TextDecoder!="undefined"){const l=new TextDecoder("utf-8").decode(a);if(e){const c=l.indexOf("\0");return c!==-1?l.substring(0,c):l}return l.replace(/\0/g,"")}const t=a.length;let i,s,n,r="",o=0;for(;o<t;){if(i=a[o++],i===0&&e)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}function te(a){let e="";for(let t=0;t<a.length;t++){let i=a[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function X(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function oe(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var F={exports:{}},ke;function lt(){return ke||(ke=1,function(a,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(u,l,c){if(c=c||{},u=u.trim(),l=l.trim(),!l){if(!c.alwaysNormalize)return u;var h=o.parseURL(u);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var m=o.parseURL(l);if(!m)throw new Error("Error trying to parse relative URL.");if(m.scheme)return c.alwaysNormalize?(m.path=o.normalizePath(m.path),o.buildURLFromParts(m)):l;var v=o.parseURL(u);if(!v)throw new Error("Error trying to parse base URL.");if(!v.netLoc&&v.path&&v.path[0]!=="/"){var y=s.exec(v.path);v.netLoc=y[1],v.path=y[2]}v.netLoc&&!v.path&&(v.path="/");var S={scheme:v.scheme,netLoc:m.netLoc,path:null,params:m.params,query:m.query,fragment:m.fragment};if(!m.netLoc&&(S.netLoc=v.netLoc,m.path[0]!=="/"))if(!m.path)S.path=v.path,m.params||(S.params=v.params,m.query||(S.query=v.query));else{var E=v.path,x=E.substring(0,E.lastIndexOf("/")+1)+m.path;S.path=o.normalizePath(x)}return S.path===null&&(S.path=c.alwaysNormalize?o.normalizePath(m.path):m.path),o.buildURLFromParts(S)},parseURL:function(u){var l=i.exec(u);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(n,"");u.length!==(u=u.replace(r,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};a.exports=o})()}(F)),F.exports}var me=lt();class Ye{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 Fe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Ne{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,si(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=(t==null?void 0:t.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={[Fe.AUDIO]:null,[Fe.VIDEO]:null,[Fe.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ye),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=me.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Fe.AUDIO]=null,e[Fe.VIDEO]=null,e[Fe.AUDIOVIDEO]=null}}function Ie(a){return a.sn!=="initSegment"}class st extends Ne{constructor(e,t){super(t),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=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(b(e)&&b(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1){const s=this._decryptdata=this.levelkeys[i[0]]||null;if(s)return s.getDecryptData(this.sn)}}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=b(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!b(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ie(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,r=!1){const{elementaryStreams:o}=this,u=o[e];if(!u){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:r};return}u.startPTS=Math.min(u.startPTS,t),u.endPTS=Math.max(u.endPTS,i),u.startDTS=Math.min(u.startDTS,s),u.endDTS=Math.max(u.endDTS,n)}}class xt extends Ne{constructor(e,t,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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const r=e.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:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function ei(a,e){const t=Object.getPrototypeOf(a);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||ei(t,e)}}function si(a,e){const t=ei(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const di=Math.pow(2,32)-1,Ai=[].push,hi={video:1,audio:2,id3:3,text:4};function St(a){return String.fromCharCode.apply(null,a)}function qt(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function We(a,e){const t=Q(a,e);return t<0?4294967296+t:t}function Oi(a,e){let t=We(a,e);return t*=Math.pow(2,32),t+=We(a,e+4),t}function Q(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Te(a){const e=a.byteLength;for(let t=0;t<e;){const i=We(a,t);if(i>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=i>1?t+i:e}return!1}function B(a,e){const t=[];if(!e.length)return t;const i=a.byteLength;for(let s=0;s<i;){const n=We(a,s),r=St(a.subarray(s+4,s+8)),o=n>1?s+n:i;if(r===e[0])if(e.length===1)t.push(a.subarray(s+8,o));else{const u=B(a.subarray(s+8,o),e.slice(1));u.length&&Ai.apply(t,u)}s=o}return t}function Pe(a){const e=[],t=a[0];let i=8;const s=We(a,i);i+=4;let n=0,r=0;t===0?(n=We(a,i),r=We(a,i+4),i+=8):(n=Oi(a,i),r=Oi(a,i+8),i+=16),i+=2;let o=a.length+r;const u=qt(a,i);i+=2;for(let l=0;l<u;l++){let c=i;const h=We(a,c);c+=4;const m=h&2147483647;if((h&2147483648)>>>31===1)return J.warn("SIDX has hierarchical references (not supported)"),null;const y=We(a,c);c+=4,e.push({referenceSize:m,subsegmentDuration:y,info:{duration:y/s,start:o,end:o+m-1}}),o+=m,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:u,references:e}}function Oe(a){const e=[],t=B(a,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],r=B(n,["tkhd"])[0];if(r){let o=r[0];const u=We(r,o===0?12:20),l=B(n,["mdia","mdhd"])[0];if(l){o=l[0];const c=We(l,o===0?12:20),h=B(n,["mdia","hdlr"])[0];if(h){const m=St(h.subarray(8,12)),v={soun:Fe.AUDIO,vide:Fe.VIDEO}[m],y=B(n,["mdia","minf","stbl","stsd"])[0],S=Ze(y);v?(e[u]={timescale:c,type:v,stsd:S},e[v]=z({timescale:c,id:u},S)):e[u]={timescale:c,type:m,stsd:S}}}}}return B(a,["moov","mvex","trex"]).forEach(s=>{const n=We(s,4),r=e[n];r&&(r.default={duration:We(s,12),flags:We(s,20)})}),e}function Ze(a){const e=a.subarray(8),t=e.subarray(86),i=St(e.subarray(4,8));let s=i,n;const r=i==="enca"||i==="encv";if(r){const l=B(e,[i])[0].subarray(i==="enca"?28:78);B(l,["sinf"]).forEach(h=>{const m=B(h,["schm"])[0];if(m){const v=St(m.subarray(4,8));if(v==="cbcs"||v==="cenc"){const y=B(h,["frma"])[0];y&&(s=St(y))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const u=B(t,["avcC"])[0];u&&u.length>3&&(s+="."+se(u[1])+se(u[2])+se(u[3]),n=mt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const u=B(e,[i])[0],l=B(u.subarray(28),["esds"])[0];if(l&&l.length>7){let c=4;if(l[c++]!==3)break;c=ee(l,c),c+=2;const h=l[c++];if(h&128&&(c+=2),h&64&&(c+=l[c++]),l[c++]!==4)break;c=ee(l,c);const m=l[c++];if(m===64)s+="."+se(m);else break;if(c+=12,l[c++]!==5)break;c=ee(l,c);const v=l[c++];let y=(v&248)>>3;y===31&&(y+=1+((v&7)<<3)+((l[c]&224)>>5)),s+="."+y}break}case"hvc1":case"hev1":{const u=B(t,["hvcC"])[0];if(u&&u.length>12){const l=u[1],c=["","A","B","C"][l>>6],h=l&31,m=We(u,2),v=(l&32)>>5?"H":"L",y=u[12],S=u.subarray(6,12);s+="."+c+h,s+="."+G(m).toString(16).toUpperCase(),s+="."+v+y;let E="";for(let x=S.length;x--;){const R=S[x];(R||E)&&(E="."+R.toString(16).toUpperCase()+E)}s+=E}n=mt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=mt(s,t)||s;break}case"vp09":{const u=B(t,["vpcC"])[0];if(u&&u.length>6){const l=u[4],c=u[5],h=u[6]>>4&15;s+="."+w(l)+"."+w(c)+"."+w(h)}break}case"av01":{const u=B(t,["av1C"])[0];if(u&&u.length>2){const l=u[1]>>>5,c=u[1]&31,h=u[2]>>>7?"H":"M",m=(u[2]&64)>>6,v=(u[2]&32)>>5,y=l===2&&m?v?12:10:m?10:8,S=(u[2]&16)>>4,E=(u[2]&8)>>3,x=(u[2]&4)>>2,R=u[2]&3;s+="."+l+"."+w(c)+h+"."+w(y)+"."+S+"."+E+x+R+"."+w(1)+"."+w(1)+"."+w(1)+"."+0,n=mt("dav1",t)}break}}return{codec:s,encrypted:r,supplemental:n}}function mt(a,e){const t=B(e,["dvvC"]),i=t.length?t[0]:B(e,["dvcC"])[0];if(i){const s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return a+"."+w(s)+"."+w(n)}}function G(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function ee(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function se(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function w(a){return(a<10?"0":"")+a}function Ae(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&B(a,["moov","trak"]).forEach(s=>{const r=B(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=B(r,["enca"]);const u=o.length>0;u||(o=B(r,["encv"])),o.forEach(l=>{const c=u?l.subarray(28):l.subarray(78);B(c,["sinf"]).forEach(m=>{const v=Je(m);if(v){const y=v.subarray(8,24);y.some(S=>S!==0)||(J.log(`[eme] Patching keyId in 'enc${u?"a":"v"}>sinf>>tenc' box: ${te(y)} -> ${te(t)}`),v.set(t,8))}})})})}function Je(a){const e=B(a,["schm"])[0];if(e){const t=St(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return B(a,["schi","tenc"])[0]}return null}function je(a,e,t){const i={},s=B(a,["moof","traf"]);for(let n=0;n<s.length;n++){const r=s[n],o=B(r,["tfhd"])[0],u=We(o,4),l=e[u];if(!l)continue;i[u]||(i[u]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const c=i[u],h=B(r,["tfdt"])[0];if(h){const L=h[0];let P=We(h,4);L===1&&(P===di?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(P*=di+1,P+=We(h,8))),b(P)&&(!b(c.start)||P<c.start)&&(c.start=P)}const m=l.default,v=We(o,0)|(m==null?void 0:m.flags);let y=(m==null?void 0:m.duration)||0;v&8&&(v&2?y=We(o,12):y=We(o,8));const S=B(r,["trun"]);let E=c.start||0,x=0,R=y;for(let L=0;L<S.length;L++){const P=S[L],V=We(P,4),re=c.sampleCount;c.sampleCount+=V;const N=P[3]&1,j=P[3]&4,Y=P[2]&1,U=P[2]&2,ce=P[2]&4,He=P[2]&8;let ut=8,yt=V;for(N&&(ut+=4),j&&V&&(!(P[ut+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=re),ut+=4,Y?(R=We(P,ut),ut+=4):R=y,U&&(ut+=4),He&&(ut+=4),E+=R,x+=R,yt--);yt--;)Y?(R=We(P,ut),ut+=4):R=y,U&&(ut+=4),ce&&(P[ut+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(yt+1),c.keyFrameStart=E),ut+=4),He&&(ut+=4),E+=R,x+=R;!x&&y&&(x+=y*V)}c.duration+=x}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,r=0;const o=B(a,["sidx"]);for(let u=0;u<o.length;u++){const l=Pe(o[u]);if(l!=null&&l.references){n=Math.min(n,l.earliestPresentationTime/l.timescale);const c=l.references.reduce((h,m)=>h+m.info.duration||0,0);r=Math.max(r,c+l.earliestPresentationTime/l.timescale)}}r&&b(r)&&Object.keys(i).forEach(u=>{i[u].duration||(i[u].duration=r*i[u].timescale-i[u].start)})}return i}function Vt(a){const e={valid:null,remainder:null},t=B(a,["moof"]);if(t.length<2)return e.remainder=a,e;const i=t[t.length-1];return e.valid=a.slice(0,i.byteOffset-8),e.remainder=a.slice(i.byteOffset-8),e}function Bt(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Lt(a,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let r=!1;return B(i,["moof"]).map(u=>{const l=u.byteOffset-8;B(u,["traf"]).map(h=>{const m=B(h,["tfdt"]).map(v=>{const y=v[0];let S=We(v,4);return y===1&&(S*=Math.pow(2,32),S+=We(v,8)),S/s})[0];return m!==void 0&&(a=m),B(h,["tfhd"]).map(v=>{const y=We(v,4),S=We(v,0)&16777215,E=(S&1)!==0,x=(S&2)!==0,R=(S&8)!==0;let L=0;const P=(S&16)!==0;let V=0;const re=(S&32)!==0;let N=8;y===n&&(E&&(N+=8),x&&(N+=4),R&&(L=We(v,N),N+=4),P&&(V=We(v,N),N+=4),re&&(N+=4),e.type==="video"&&(r=Ht(e.codec)),B(h,["trun"]).map(j=>{const Y=j[0],U=We(j,0)&16777215,ce=(U&1)!==0;let He=0;const ut=(U&4)!==0,yt=(U&256)!==0;let ct=0;const Ue=(U&512)!==0;let pt=0;const tt=(U&1024)!==0,vt=(U&2048)!==0;let Mt=0;const Ge=We(j,4);let Ve=8;ce&&(He=We(j,Ve),Ve+=4),ut&&(Ve+=4);let ii=He+l;for(let Di=0;Di<Ge;Di++){if(yt?(ct=We(j,Ve),Ve+=4):ct=L,Ue?(pt=We(j,Ve),Ve+=4):pt=V,tt&&(Ve+=4),vt&&(Y===0?Mt=We(j,Ve):Mt=Q(j,Ve),Ve+=4),e.type===Fe.VIDEO){let ri=0;for(;ri<pt;){const vi=We(i,ii);if(ii+=4,jt(r,i[ii])){const As=i.subarray(ii,ii+vi);Xt(As,r?2:1,a+Mt/s,t)}ii+=vi,ri+=vi+4}}a+=ct/s}}))})})}),t}function Ht(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function jt(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Xt(a,e,t,i){const s=Ii(a);let n=0;n+=e;let r=0,o=0,u=0;for(;n<s.length;){r=0;do{if(n>=s.length)break;u=s[n++],r+=u}while(u===255);o=0;do{if(n>=s.length)break;u=s[n++],o+=u}while(u===255);const l=s.length-n;let c=n;if(o<l)n+=o;else if(o>l){J.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(r===4){if(s[c++]===181){const m=qt(s,c);if(c+=2,m===49){const v=We(s,c);if(c+=4,v===1195456820){const y=s[c++];if(y===3){const S=s[c++],E=31&S,x=64&S,R=x?2+E*3:0,L=new Uint8Array(R);if(x){L[0]=S;for(let P=1;P<R;P++)L[P]=s[c++]}i.push({type:y,payloadType:r,pts:t,bytes:L})}}}}}else if(r===5&&o>16){const h=[];for(let y=0;y<16;y++){const S=s[c++].toString(16);h.push(S.length==1?"0"+S:S),(y===3||y===5||y===7||y===9)&&h.push("-")}const m=o-16,v=new Uint8Array(m);for(let y=0;y<m;y++)v[y]=s[c++];i.push({payloadType:r,pts:t,uuid:h.join(""),userData:_t(v),userDataBytes:v})}}}function Ii(a){const e=a.byteLength,t=[];let i=1;for(;i<e-2;)a[i]===0&&a[i+1]===0&&a[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return a;const s=e-t.length,n=new Uint8Array(s);let r=0;for(i=0;i<s;r++,i++)r===t[0]&&(r++,t.shift()),n[i]=a[r];return n}function pe(a){const e=a[0];let t="",i="",s=0,n=0,r=0,o=0,u=0,l=0;if(e===0){for(;St(a.subarray(l,l+1))!=="\0";)t+=St(a.subarray(l,l+1)),l+=1;for(t+=St(a.subarray(l,l+1)),l+=1;St(a.subarray(l,l+1))!=="\0";)i+=St(a.subarray(l,l+1)),l+=1;i+=St(a.subarray(l,l+1)),l+=1,s=We(a,12),n=We(a,16),o=We(a,20),u=We(a,24),l=28}else if(e===1){l+=4,s=We(a,l),l+=4;const h=We(a,l);l+=4;const m=We(a,l);for(l+=4,r=fl(2,32)*h+m,de(r)||(r=Number.MAX_SAFE_INTEGER,J.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=We(a,l),l+=4,u=We(a,l),l+=4;St(a.subarray(l,l+1))!=="\0";)t+=St(a.subarray(l,l+1)),l+=1;for(t+=St(a.subarray(l,l+1)),l+=1;St(a.subarray(l,l+1))!=="\0";)i+=St(a.subarray(l,l+1)),l+=1;i+=St(a.subarray(l,l+1)),l+=1}const c=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:r,presentationTimeDelta:n,eventDuration:o,id:u,payload:c}}function Ft(a,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[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<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function qi(a,e,t){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),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const r=new Uint8Array(4);return t.byteLength>0&&new DataView(r.buffer).setUint32(0,t.byteLength,!1),Ft([112,115,115,104],new Uint8Array([i,0,0,0]),a,n,s,r,t)}const Ki=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Mi={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 rs(a,e){const t=Mi[e];return!!t&&!!t[a.slice(0,4)]}function cs(a,e,t=!0){return!a.split(",").some(i=>!Hi(i,e,t))}function Hi(a,e,t=!0){var i;const s=dt(t);return(i=s==null?void 0:s.isTypeSupported(Ti(a,e)))!=null?i:!1}function Ti(a,e){return`${e}/mp4;codecs=${a}`}function Ji(a){if(a){const e=a.substring(0,4);return Mi.video[e]}return 2}function Wi(a){const e=Ki();return a.split(",").reduce((t,i)=>{const n=e&&Ht(i)?9:Mi.video[i];return n?(n*2+t)/(t?3:2):(Mi.audio[i]+t)/(t?2:1)},0)}const Qe={};function Nt(a,e=!0){if(Qe[a])return Qe[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let s=0;s<t.length;s++){var i;if(Hi(t[s],"audio",e))return Qe[a]=t[s],t[s];if(t[s]==="mp3"&&(i=dt(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return a}const kt=/flac|opus|mp4a\.40\.34/i;function gi(a,e=!0){return a.replace(kt,t=>Nt(t.toLowerCase(),e))}function _i(a,e){const t=[];if(a){const i=a.split(",");for(let s=0;s<i.length;s++)rs(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function yi(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Rt(a,"audio")||Rt(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let i=t.length;i--;)if(t[i].substring(0,4)===a.substring(0,4))return t[i]}return t[0]}}return e||a}function Rt(a,e){return rs(a,e)&&Hi(a,e)}function Bi(a){const e=a.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Qt(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return a}function Si(a){const e=dt(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ui(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ee={supported:!0,powerEfficient:!0,smooth:!0},d={supported:!1,smooth:!1,powerEfficient:!1},f={supported:!0,configurations:[],decodingInfoResults:[Ee]};function p(a,e){return{supported:!1,configurations:e,decodingInfoResults:[d],error:a}}function _(a,e,t,i,s,n){const r=a.videoCodec,o=a.audioCodec?a.audioGroups:null,u=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,c=l?parseInt(l):u?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=e.groups[o[0]].channels:h=o.reduce((m,v)=>{if(v){const y=e.groups[v];if(!y)throw new Error(`Audio track group ${v} not found`);Object.keys(y.channels).forEach(S=>{m[S]=(m[S]||0)+y.channels[S]})}return m},{2:0})}catch(m){return!0}return r!==void 0&&(r.split(",").some(m=>Ht(m))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(i,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(s,8e6))||!!h&&b(c)&&Object.keys(h).some(m=>parseInt(m)>c)}function T(a,e,t,i={}){const s=a.videoCodec;if(!s&&!a.audioCodec||!t)return Promise.resolve(f);const n=[],r=I(a),o=r.length,u=O(a,e,o>0),l=u.length;for(let c=o||1*l||1;c--;){const h={type:"media-source"};if(o&&(h.video=r[c%o]),l){h.audio=u[c%l];const m=h.audio.bitrate;h.video&&m&&(h.video.bitrate-=m)}n.push(h)}if(s){const c=navigator.userAgent;if(s.split(",").some(h=>Ht(h))&&Ki())return Promise.resolve(p(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{const h=Me(c);return i[h]||(i[h]=t.decodingInfo(c))})).then(c=>({supported:!c.some(h=>!h.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function I(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),i=_e(a),s=a.width||640,n=a.height||480,r=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(u=>{const l={contentType:Ti(Qt(u),"video"),width:s,height:n,bitrate:i,framerate:r};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function O(a,e,t){var i;const s=(i=a.audioCodec)==null?void 0:i.split(","),n=_e(a);return s&&a.audioGroups?a.audioGroups.reduce((r,o)=>{var u;const l=o?(u=e.groups[o])==null?void 0:u.tracks:null;return l?l.reduce((c,h)=>{if(h.groupId===o){const m=parseFloat(h.channels||"");s.forEach(v=>{const y={contentType:Ti(v,"audio"),bitrate:t?be(v,n):n};m&&(y.channels=""+m),c.push(y)})}return c},r):r},[]):[]}function be(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function _e(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function Me(a){let e="";const{audio:t,video:i}=a;if(i){const s=Ui(i.contentType);e+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const s=Ui(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}const It=["NONE","TYPE-0","TYPE-1",null];function ht(a){return It.indexOf(a)>-1}const we=["SDR","PQ","HLG"];function gt(a){return!!a&&we.indexOf(a)>-1}var $e={No:"",Yes:"YES",v2:"v2"};function Se(a){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=a,s=i<e/2;return e&&s?t?$e.v2:$e.Yes:$e.No}class ve{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class et{constructor(e){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=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return qe(this._audioGroups,e)}hasSubtitleGroup(e){return qe(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function qe(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function Yt(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function fi(a,e){let t=!1,i=[];if(a&&(t=a!=="SDR",i=[a]),e){i=e.allowedVideoRanges||we.slice(0);const s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&Yt(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const mi=a=>{const e=new WeakSet;return(t,i)=>{if(a&&(i=a(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},Ce=(a,e)=>JSON.stringify(a,mi(e));function ze(a,e,t,i,s){const n=Object.keys(a),r=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,u=s==null?void 0:s.videoCodec,l=r&&parseInt(r)===2;let c=!1,h=!1,m=1/0,v=1/0,y=1/0,S=1/0,E=0,x=[];const{preferHDR:R,allowedVideoRanges:L}=fi(e,s);for(let j=n.length;j--;){const Y=a[n[j]];c||(c=Y.channels[2]>0),m=Math.min(m,Y.minHeight),v=Math.min(v,Y.minFramerate),y=Math.min(y,Y.minBitrate),L.filter(ce=>Y.videoRanges[ce]>0).length>0&&(h=!0)}m=b(m)?m:0,v=b(v)?v:0;const P=Math.max(1080,m),V=Math.max(30,v);y=b(y)?y:t,t=Math.max(y,t),h||(e=void 0);const re=n.length>1;return{codecSet:n.reduce((j,Y)=>{const U=a[Y];if(Y===j)return j;if(x=h?L.filter(ce=>U.videoRanges[ce]>0):[],re){if(U.minBitrate>t)return it(Y,`min bitrate of ${U.minBitrate} > current estimate of ${t}`),j;if(!U.hasDefaultAudio)return it(Y,"no renditions with default or auto-select sound found"),j;if(o&&Y.indexOf(o.substring(0,4))%5!==0)return it(Y,`audio codec preference "${o}" not found`),j;if(r&&!l){if(!U.channels[r])return it(Y,`no renditions with ${r} channel sound found (channels options: ${Object.keys(U.channels)})`),j}else if((!o||l)&&c&&U.channels[2]===0)return it(Y,"no renditions with stereo sound found"),j;if(U.minHeight>P)return it(Y,`min resolution of ${U.minHeight} > maximum of ${P}`),j;if(U.minFramerate>V)return it(Y,`min framerate of ${U.minFramerate} > maximum of ${V}`),j;if(!x.some(ce=>U.videoRanges[ce]>0))return it(Y,`no variants with VIDEO-RANGE of ${Ce(x)} found`),j;if(u&&Y.indexOf(u.substring(0,4))%5!==0)return it(Y,`video codec preference "${u}" not found`),j;if(U.maxScore<E)return it(Y,`max score of ${U.maxScore} < selected max of ${E}`),j}return j&&(Wi(Y)>=Wi(j)||U.fragmentError>a[j].fragmentError)?j:(S=U.minIndex,E=U.maxScore,Y)},void 0),videoRanges:x,preferHDR:R,minFramerate:v,minBitrate:y,minIndex:S}}function it(a,e){J.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function k(a){return a.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function H(a,e,t,i){return a.slice(t,i+1).reduce((s,n,r)=>{if(!n.codecSet)return s;const o=n.audioGroups;let u=s[n.codecSet];u||(s[n.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return u.minHeight=Math.min(u.minHeight,l),u.minFramerate=Math.min(u.minFramerate,n.frameRate),u.minIndex=Math.min(u.minIndex,r),u.maxScore=Math.max(u.maxScore,n.score),u.fragmentError+=n.fragmentError,u.videoRanges[n.videoRange]=(u.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const h=e.groups[c];h&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(m=>{u.channels[m]=(u.channels[m]||0)+h.channels[m]}))}),s},{})}function ne(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=a;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function q(a,e,t){if("attrs"in a){const i=e.indexOf(a);if(i!==-1)return i}for(let i=0;i<e.length;i++){const s=e[i];if(le(a,s,t))return i}return-1}function le(a,e,t){const{groupId:i,name:s,lang:n,assocLang:r,default:o}=a,u=a.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||ye(n,e.lang))&&(n===void 0||e.assocLang===r)&&(o===void 0||e.default===o)&&(u===void 0||e.forced===u)&&(!("characteristics"in a)||Le(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function ye(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function Le(a,e=""){const t=a.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function Ke(a,e){const{audioCodec:t,channels:i}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Ut(a,e,t,i,s){const n=e[i],o=e.reduce((m,v,y)=>{const S=v.uri;return(m[S]||(m[S]=[])).push(y),m},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const u=n.videoRange,l=n.frameRate,c=n.codecSet.substring(0,4),h=nt(e,i,m=>{if(m.videoRange!==u||m.frameRate!==l||m.codecSet.substring(0,4)!==c)return!1;const v=m.audioGroups,y=t.filter(S=>!v||v.indexOf(S.groupId)!==-1);return q(a,y,s)>-1});return h>-1?h:nt(e,i,m=>{const v=m.audioGroups,y=t.filter(S=>!v||v.indexOf(S.groupId)!==-1);return q(a,y,s)>-1})}function nt(a,e,t){for(let i=e;i>-1;i--)if(t(a[i]))return i;for(let i=e+1;i<a.length;i++)if(t(a[i]))return i;return-1}function Pt(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Ct extends De{constructor(e){super("abr",e.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.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:n,hls:r}=this,{autoLevelEnabled:o,media:u}=r;if(!s||!u)return;const l=performance.now(),c=n?n.stats:s.stats,h=n?n.duration:s.duration,m=l-c.loading.start,v=r.minAutoLevel,y=s.level,S=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||y<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const E=S>-1&&S!==y,x=!!t||E;if(!x&&(u.paused||!u.playbackRate||!u.readyState))return;const R=r.mainForwardBufferInfo;if(!x&&R===null)return;const L=this.bwEstimator.getEstimateTTFB(),P=Math.abs(u.playbackRate);if(m<=Math.max(L,1e3*(h/(P*2))))return;const V=R?R.len/P:0,re=c.loading.first?c.loading.first-c.loading.start:-1,N=c.loaded&&re>-1,j=this.getBwEstimate(),Y=r.levels,U=Y[y],ce=Math.max(c.loaded,Math.round(h*(s.bitrate||U.averageBitrate)/8));let He=N?m-re:m;He<1&&N&&(He=Math.min(m,c.loaded*8/j));const ut=N?c.loaded*1e3/He:0,yt=L/1e3,ct=ut?(ce-c.loaded)/ut:ce*8/j+yt;if(ct<=V)return;const Ue=ut?ut*8:j,pt=((i=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,tt=this.hls.config.abrBandWidthUpFactor;let vt=Number.POSITIVE_INFINITY,Mt;for(Mt=y-1;Mt>v;Mt--){const Di=Y[Mt].maxBitrate,ri=!Y[Mt].details||pt;if(vt=this.getTimeToLoadFrag(yt,Ue,h*Di,ri),vt<Math.min(V,h+yt))break}if(vt>=ct||vt>h*10)return;N?this.bwEstimator.sample(m-Math.min(L,re),c.loaded):this.bwEstimator.sampleTTFB(m);const Ge=Y[Mt].maxBitrate;this.getBwEstimate()*tt>Ge&&this.resetEstimator(Ge);const Ve=this.findBestLevel(Ge,v,Mt,0,V,1,1);Ve>-1&&(Mt=Ve),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${y} is loading too slowly;
Fragment duration: ${s.duration.toFixed(3)}
Time to underbuffer: ${V.toFixed(3)} s
Estimated load time for current fragment: ${ct.toFixed(3)} s
Estimated load time for down switch fragment: ${vt.toFixed(3)} s
TTFB estimate: ${re|0} ms
Current BW estimate: ${b(j)?j|0:"Unknown"} bps
New BW estimate: ${this.getBwEstimate()|0} bps
Switching to level ${Mt} @ ${Ge|0} bps`),r.nextLoadLevel=r.nextAutoLevel=Mt,this.clearTimer();const ii=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===Mt&&Mt>0){const Di=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Mt>0?"and switching down":""}
Fragment duration: ${s.duration.toFixed(3)} s
Time to underbuffer: ${Di.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,Mt>v){let ri=this.findBestLevel(this.hls.levels[v].bitrate,v,Mt,0,Di,1,1);ri===-1&&(ri=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ri,this.resetEstimator(this.hls.levels[ri].bitrate)}}};E||ct>vt*2?ii():this.timer=self.setInterval(ii,vt*1e3),r.trigger(g.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:c})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ot(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(g.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case A.FRAG_LOAD_TIMEOUT:{const i=t.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,u=r-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(u-Math.min(h,l),o.loaded)}else this.bwEstimator.sampleTTFB(u)}break}}}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,r=s?e+this.lastLevelLoadSec:0;return n+r}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;b(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===ae.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,r=this.hls.levels[t.level],o=(r.loaded?r.loaded.bytes:0)+s.loaded,u=(r.loaded?r.loaded.duration:0)+n;r.loaded={bytes:o,duration:u},r.realBitrate=Math.round(8*o/u)}if(t.bitrateTest){const n={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(g.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,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(e){return e.type!==ae.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,s,1,1);if(n>-1)return n;const r=this.hls.firstLevel,o=Math.min(Math.max(r,t),e);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 e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const r=this.hls.levels;if(r.length>Math.max(e,n)&&r[e].loadError<=r[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:r}=i,o=t?t.duration:e?e.duration:0,u=this.getBwEstimate(),l=this.getStarvationDelay();let c=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){const E=this.findBestLevel(u,r,s,l,0,c,h);if(E>=0)return this.rebufferNotice=-1,E}let m=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const E=this.bitrateTestDelay;E&&(m=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),c=h=1)}const v=this.findBestLevel(u,r,s,l,m,c,h);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${v}`)),v>-1)return v;const y=i.levels[r],S=i.loadLevelObj;return S&&(y==null?void 0:y.bitrate)<S.bitrate?r:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,n,r,o){var u;const l=s+n,c=this.lastLoadedFragLevel,h=c===-1?this.hls.firstLevel:c,{fragCurrent:m,partCurrent:v}=this,{levels:y,allAudioTracks:S,loadLevel:E,config:x}=this.hls;if(y.length===1)return 0;const R=y[h],L=!!((u=this.hls.latestLevelDetails)!=null&&u.live),P=E===-1||c===-1;let V,re="SDR",N=(R==null?void 0:R.frameRate)||0;const{audioPreference:j,videoPreference:Y}=x,U=this.audioTracksByGroup||(this.audioTracksByGroup=k(S));let ce=-1;if(P){if(this.firstSelection!==-1)return this.firstSelection;const Ue=this.codecTiers||(this.codecTiers=H(y,U,t,i)),pt=ze(Ue,re,e,j,Y),{codecSet:tt,videoRanges:vt,minFramerate:Mt,minBitrate:Ge,minIndex:Ve,preferHDR:ii}=pt;ce=Ve,V=tt,re=ii?vt[vt.length-1]:vt[0],N=Mt,e=Math.max(e,Ge),this.log(`picked start tier ${Ce(pt)}`)}else V=R==null?void 0:R.codecSet,re=R==null?void 0:R.videoRange;const He=v?v.duration:m?m.duration:0,ut=this.bwEstimator.getEstimateTTFB()/1e3,yt=[];for(let Ue=i;Ue>=t;Ue--){var ct;const pt=y[Ue],tt=Ue>h;if(!pt)continue;if(x.useMediaCapabilities&&!pt.supportedResult&&!pt.supportedPromise){const ri=navigator.mediaCapabilities;typeof(ri==null?void 0:ri.decodingInfo)=="function"&&_(pt,U,re,N,e,j)?(pt.supportedPromise=T(pt,U,ri,this.supportedCache),pt.supportedPromise.then(vi=>{if(!this.hls)return;pt.supportedResult=vi;const As=this.hls.levels,Es=As.indexOf(pt);vi.error?this.warn(`MediaCapabilities decodingInfo error: "${vi.error}" for level ${Es} ${Ce(vi)}`):vi.supported?vi.decodingInfoResults.some(js=>js.smooth===!1||js.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Es} not smooth or powerEfficient: ${Ce(vi)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Es} ${Ce(vi)}`),Es>-1&&As.length>1&&(this.log(`Removing unsupported level ${Es}`),this.hls.removeLevel(Es),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(vi=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${vi}`)})):pt.supportedResult=f}if((V&&pt.codecSet!==V||re&&pt.videoRange!==re||tt&&N>pt.frameRate||!tt&&N>0&&N<pt.frameRate||(ct=pt.supportedResult)!=null&&(ct=ct.decodingInfoResults)!=null&&ct.some(ri=>ri.smooth===!1))&&(!P||Ue!==ce)){yt.push(Ue);continue}const vt=pt.details,Mt=(v?vt==null?void 0:vt.partTarget:vt==null?void 0:vt.averagetargetduration)||He;let Ge;tt?Ge=o*e:Ge=r*e;const Ve=He&&s>=He*2&&n===0?pt.averageBitrate:pt.maxBitrate,ii=this.getTimeToLoadFrag(ut,Ge,Ve*Mt,vt===void 0);if(Ge>=Ve&&(Ue===c||pt.loadError===0&&pt.fragmentError===0)&&(ii<=ut||!b(ii)||L&&!this.bitrateTestDelay||ii<l)){const ri=this.forcedAutoLevel;return Ue!==E&&(ri===-1||ri!==E)&&(yt.length&&this.trace(`Skipped level(s) ${yt.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${y[yt[0]].codecs}" ${y[yt[0]].videoRange}; not compatible with "${V}" ${re}`),this.info(`switch candidate:${h}->${Ue} adjustedbw(${Math.round(Ge)})-bitrate=${Math.round(Ge-Ve)} ttfb:${ut.toFixed(1)} avgDuration:${Mt.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${ii.toFixed(1)} firstSelection:${P} codecSet:${pt.codecSet} videoRange:${pt.videoRange} hls.loadLevel:${E}`)),P&&(this.firstSelection=Ue),Ue}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Dt={search:function(a,e){let t=0,i=a.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=a[s];const r=e(n);if(r>0)t=s+1;else if(r<0)i=s-1;else return n}return null}};function $t(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!b(e))return null;const i=a[0].programDateTime;if(e<(i||0))return null;const s=a[a.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<a.length;++n){const r=a[n];if(Ot(e,t,r))return r}return null}function zt(a,e,t=0,i=0,s=.005){let n=null;if(a){n=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&a.level!==n.level&&n.end<=a.end&&(n=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!a||a.level===n.level)&&At(t,i,n)===0||ni(n,a,Math.min(s,i))))return n;const r=Dt.search(e,At.bind(null,t,i));return r&&(r!==a||!n)?r:n}function ni(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return a.start<=i}return!1}function At(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=a?1:t.start-i>a&&t.start?-1:0}function Ot(a,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>a}function pi(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let i=a.fragments;const{fragmentHint:s}=a;s&&(i=i.concat(s));let n;return Dt.search(i,r=>r.cc<e?1:r.cc>e?-1:(n=r,r.end<=t?1:r.start>t?-1:0)),n||null}return null}function Wt(a){switch(a.details){case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_TIMEOUT:case A.LEVEL_LOAD_TIMEOUT:case A.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Kt(a,e){const t=Wt(e);return a.default[`${t?"timeout":"error"}Retry`]}function Ei(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function ti(a){return z(z({},a),{errorRetry:null,timeoutRetry:null})}function oi(a,e,t,i){if(!a)return!1;const s=i==null?void 0:i.code,n=e<a.maxNumRetry&&(ji(s)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,i,n):n}function ji(a){return bi(a)||!!a&&(a<400||a>499)}function bi(a){return a===0&&navigator.onLine===!1}var li={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ui={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class zi extends De{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(g.ERROR,this.onError,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(g.ERROR,this.onError,this),e.off(g.ERROR,this.onErrorOut,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===ae.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(r=>s.indexOf(r.groupId)>=0).some(r=>{var o;return(o=r.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case A.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=$i();return}case A.FRAG_GAP:case A.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=li.SendAlternateToPenaltyBox;return}case A.LEVEL_EMPTY_ERROR:case A.LEVEL_PARSING_ERROR:{var r;const u=t.parent===ae.MAIN?t.level:s.loadLevel;t.details===A.LEVEL_EMPTY_ERROR&&((r=t.context)!=null&&(r=r.levelDetails)!=null&&r.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,u):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,u))}return;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.SUBTITLE_LOAD_ERROR:case A.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const u=s.loadLevelObj;if(u&&(n.type===xe.AUDIO_TRACK&&u.hasAudioGroup(n.groupId)||n.type===xe.SUBTITLE_TRACK&&u.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=li.SendAlternateToPenaltyBox,t.errorAction.flags=ui.MoveAllAlternatesMatchingHost;return}}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:li.SendAlternateToPenaltyBox,flags:ui.MoveAllAlternatesMatchingHDCP};return;case A.KEY_SYSTEM_SESSION_UPDATE_FAILED:case A.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case A.KEY_SYSTEM_NO_SESSION:t.errorAction={action:li.SendAlternateToPenaltyBox,flags:ui.MoveAllAlternatesMatchingKey};return;case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:s.loadLevel)}return;case A.INTERNAL_EXCEPTION:case A.BUFFER_APPENDING_ERROR:case A.BUFFER_FULL_ERROR:case A.LEVEL_SWITCH_ERROR:case A.BUFFER_STALLED_ERROR:case A.BUFFER_SEEK_OVER_HOLE:case A.BUFFER_NUDGE_ON_STALL:t.errorAction=$i();return}t.type===Z.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=$i())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=Kt(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(oi(s,n,Wt(e),e.response))return{action:li.RetryRequest,flags:ui.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:r}=t.config,o=Kt(e.details.startsWith("key")?r:n,e),u=t.levels.reduce((c,h)=>c+h.fragmentError,0);if(s&&(e.details!==A.FRAG_GAP&&s.fragmentError++,oi(o,u,Wt(e),e.response)))return{action:li.RetryRequest,flags:ui.None,retryConfig:o,retryCount:u};const l=this.getLevelSwitchAction(e,i);return o&&(l.retryConfig=o,l.retryCount=u),l}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var n,r;const l=e.details;s.loadError++,l===A.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1;const{levels:h,loadLevel:m,minAutoLevel:v,maxAutoLevel:y}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const S=(n=e.frag)==null?void 0:n.type,x=(S===ae.AUDIO&&l===A.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===A.BUFFER_ADD_CODEC_ERROR||l===A.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:re})=>s.audioCodec!==re),L=e.sourceBufferName==="video"&&(l===A.BUFFER_ADD_CODEC_ERROR||l===A.BUFFER_APPEND_ERROR)&&h.some(({codecSet:re,audioCodec:N})=>s.codecSet!==re&&s.audioCodec===N),{type:P,groupId:V}=(r=e.context)!=null?r:{};for(let re=h.length;re--;){const N=(re+m)%h.length;if(N!==m&&N>=v&&N<=y&&h[N].loadError===0){var o,u;const j=h[N];if(l===A.FRAG_GAP&&S===ae.MAIN&&e.frag){const Y=h[N].details;if(Y){const U=zt(e.frag,Y.fragments,e.frag.start);if(U!=null&&U.gap)continue}}else{if(P===xe.AUDIO_TRACK&&j.hasAudioGroup(V)||P===xe.SUBTITLE_TRACK&&j.hasSubtitleGroup(V))continue;if(S===ae.AUDIO&&(o=s.audioGroups)!=null&&o.some(Y=>j.hasAudioGroup(Y))||S===ae.SUBTITLE&&(u=s.subtitleGroups)!=null&&u.some(Y=>j.hasSubtitleGroup(Y))||x&&s.audioCodec===j.audioCodec||L&&s.codecSet===j.codecSet||!x&&s.codecSet!==j.codecSet)continue}c=N;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:li.SendAlternateToPenaltyBox,flags:ui.None,nextAutoLevel:c}}return{action:li.SendAlternateToPenaltyBox,flags:ui.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case li.DoNothing:break;case li.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==A.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case li.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,n=i.nextAutoLevel;switch(s){case ui.None:this.switchLevel(e,n);break;case ui.MoveAllAlternatesMatchingHDCP:{const u=this.getVariantLevelIndex(e.frag),l=t.levels[u],c=l==null?void 0:l.attrs["HDCP-LEVEL"];if(i.hdcpLevel=c,c){t.maxHdcpLevel=It[It.indexOf(c)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ui.MoveAllAlternatesMatchingKey:{const u=e.decryptdata;if(u){const l=this.hls.levels;for(let c=l.length;c--;)if(this.variantHasKey(l[c],u)){var r,o;this.log(`Banned key found in level ${c} (${l[c].bitrate}bps) or audio group "${(r=l[c].audioGroups)==null?void 0:r.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${te(u.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${e.error})`),this.hls.removeLevel(c)}l.length&&(i.resolved=!0)}break}}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===A.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Ui(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}}function $i(a){const e={action:li.DoNothing,flags:ui.None};return a&&(e.resolved=!0),e}var Jt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class es{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,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)===t&&(!i||o.buffered)){const u=o.body;if(u.start<=e&&e<=u.end)return u}}return null}detectEvictedFragments(e,t,i,s,n){this.timeRanges&&(this.timeRanges[e]=t);const r=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u||r>=u.body.sn)return;if(!u.buffered&&(!u.loaded||n)){u.body.type===i&&this.removeFragment(u.body);return}const l=u.range[e];if(l){if(l.time.length===0){this.removeFragment(u.body);return}l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return h&&this.removeFragment(u.body),h})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,s=Ci(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const r=!i.relurl;Object.keys(t).forEach(o=>{const u=i.elementaryStreams[o];if(!u)return;const l=t[o],c=r||u.partial===!0;n.range[o]=this.getBufferedTimes(i,e.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),Xi(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=fs(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=Ci(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},r=e.start,o=e.end,u=e.minEndPTS||o,l=e.maxStartPTS||r;for(let c=0;c<s.length;c++){const h=s.start(c)-this.bufferPadding,m=s.end(c)+this.bufferPadding;if(l>=h&&u<=m){n.time.push({startPTS:Math.max(r,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(r<m&&o>h){const v=Math.max(r,s.start(c)),y=Math.min(o,s.end(c));y>v&&(n.partial=!0,n.time.push({startPTS:v,endPTS:y}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,r=0;const{bufferPadding:o,fragments:u}=this;return Object.keys(u).forEach(l=>{const c=u[l];c&&Xi(c)&&(s=c.body.start-o,n=c.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),r<=i&&(t=c.body,r=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Xi(t))}getState(e){const t=Ci(e),i=this.fragments[t];return i?i.buffered?Xi(i)?Jt.PARTIAL:Jt.OK:Jt.APPENDING:Jt.NOT_LOADED}isTimeBuffered(e,t,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,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,n=Ci(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n,type:r}=t;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 u=n[r];this.detectEvictedFragments(r,u,o,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ci(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const n=t[i[s]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o)return;const u=o.body;u.type!==i||s&&!u.gap||u.start<t&&u.end>e&&(o.buffered||n)&&this.removeFragment(u)})}removeFragment(e){const t=Ci(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=fs(i,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function Xi(a){var e,t,i;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(i=a.range.audiovideo)!=null&&i.partial)}function Ci(a){return`${a.type}_${a.level}_${a.sn}`}function fs(a,e){return a.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var ci={cbc:0,ctr:1};class ds{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case ci.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ci.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Cs(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Ds{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],r=i[2],o=i[3],u=this.invSubMix,l=u[0],c=u[1],h=u[2],m=u[3],v=new Uint32Array(256);let y=0,S=0,E=0;for(E=0;E<256;E++)E<128?v[E]=E<<1:v[E]=E<<1^283;for(E=0;E<256;E++){let x=S^S<<1^S<<2^S<<3^S<<4;x=x>>>8^x&255^99,e[y]=x,t[x]=y;const R=v[y],L=v[R],P=v[L];let V=v[x]*257^x*16843008;s[y]=V<<24|V>>>8,n[y]=V<<16|V>>>16,r[y]=V<<8|V>>>24,o[y]=V,V=P*16843009^L*65537^R*257^y*16843008,l[x]=V<<24|V>>>8,c[x]=V<<16|V>>>16,h[x]=V<<8|V>>>24,m[x]=V,y?(y=R^v[v[v[P^R]]],S^=v[v[S]]):y=S=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const n=this.keySize=t.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,u;const l=this.keySchedule=new Uint32Array(r),c=this.invKeySchedule=new Uint32Array(r),h=this.sBox,m=this.rcon,v=this.invSubMix,y=v[0],S=v[1],E=v[2],x=v[3];let R,L;for(o=0;o<r;o++){if(o<n){R=l[o]=t[o];continue}L=R,o%n===0?(L=L<<8|L>>>24,L=h[L>>>24]<<24|h[L>>>16&255]<<16|h[L>>>8&255]<<8|h[L&255],L^=m[o/n|0]<<24):n>6&&o%n===4&&(L=h[L>>>24]<<24|h[L>>>16&255]<<16|h[L>>>8&255]<<8|h[L&255]),l[o]=R=(l[o-n]^L)>>>0}for(u=0;u<r;u++)o=r-u,u&3?L=l[o]:L=l[o-4],u<4||o<=4?c[u]=L:c[u]=y[h[L>>>24]]^S[h[L>>>16&255]]^E[h[L>>>8&255]]^x[h[L&255]],c[u]=c[u]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,o=this.invSubMix,u=o[0],l=o[1],c=o[2],h=o[3],m=this.uint8ArrayToUint32Array_(i);let v=m[0],y=m[1],S=m[2],E=m[3];const x=new Int32Array(e),R=new Int32Array(x.length);let L,P,V,re,N,j,Y,U,ce,He,ut,yt,ct,Ue;const pt=this.networkToHostOrderSwap;for(;t<x.length;){for(ce=pt(x[t]),He=pt(x[t+1]),ut=pt(x[t+2]),yt=pt(x[t+3]),N=ce^n[0],j=yt^n[1],Y=ut^n[2],U=He^n[3],ct=4,Ue=1;Ue<s;Ue++)L=u[N>>>24]^l[j>>16&255]^c[Y>>8&255]^h[U&255]^n[ct],P=u[j>>>24]^l[Y>>16&255]^c[U>>8&255]^h[N&255]^n[ct+1],V=u[Y>>>24]^l[U>>16&255]^c[N>>8&255]^h[j&255]^n[ct+2],re=u[U>>>24]^l[N>>16&255]^c[j>>8&255]^h[Y&255]^n[ct+3],N=L,j=P,Y=V,U=re,ct=ct+4;L=r[N>>>24]<<24^r[j>>16&255]<<16^r[Y>>8&255]<<8^r[U&255]^n[ct],P=r[j>>>24]<<24^r[Y>>16&255]<<16^r[U>>8&255]<<8^r[N&255]^n[ct+1],V=r[Y>>>24]<<24^r[U>>16&255]<<16^r[N>>8&255]<<8^r[j&255]^n[ct+2],re=r[U>>>24]<<24^r[N>>16&255]<<16^r[j>>8&255]<<8^r[Y&255]^n[ct+3],R[t]=pt(L^v),R[t+1]=pt(re^y),R[t+2]=pt(V^S),R[t+3]=pt(P^E),v=ce,y=He,S=ut,E=yt,t=t+4}return R.buffer}}class vs{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=ws(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function ws(a){switch(a){case ci.cbc:return"AES-CBC";case ci.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const as=16;class os{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch(i){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Cs(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((n,r)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,s);const u=this.flush();u?n(u.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:n,currentResult:r,remainderData:o}=this;if(s!==ci.cbc||t.byteLength!==16)return J.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Bt(o,e),this.remainderData=null);const u=this.getValidChunk(e);if(!u.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ds),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(u.buffer,0,i),this.currentIV=u.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new vs(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new ds(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(J.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%as;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(J.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const ks=Math.pow(2,17);class ys{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Vi({type:Z.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,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,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(y=>y[0]==="GAP")){u(Gi(e));return}else e.gap=!1;const l=this.loader=n?new n(s):new r(s),c=gs(e);e.loader=l;const h=ti(s.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:ks};e.stats=l.stats;const v={onSuccess:(y,S,E,x)=>{this.resetLoader(e,l);let R=y.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(R.slice(0,16)),R=R.slice(16)),o({frag:e,part:null,payload:R,networkDetails:x})},onError:(y,S,E,x)=>{this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:z({url:i,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:E,stats:x}))},onAbort:(y,S,E)=>{this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:y}))},onTimeout:(y,S,E)=>{this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:E,stats:y}))}};t&&(v.onProgress=(y,S,E,x)=>t({frag:e,part:null,payload:E,networkDetails:x})),l.load(c,m,v)})}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,r=s.loader;return new Promise((o,u)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){u(Gi(e,t));return}const l=this.loader=n?new n(s):new r(s),c=gs(e,t);e.loader=l;const h=ti(s.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ks};t.stats=l.stats,l.load(c,m,{onSuccess:(v,y,S,E)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const x={frag:e,part:t,payload:v.data,networkDetails:E};i(x),o(x)},onError:(v,y,S,E)=>{this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:z({url:c.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:S,stats:E}))},onAbort:(v,y,S)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:S,stats:v}))},onTimeout:(v,y,S)=>{this.resetLoader(e,l),u(new Vi({type:Z.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:S,stats:v}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const u=Math.round(e.duration/t.duration),l=Math.min(Math.round(i.loaded/n),u),h=(u-l)*Math.round(i.loaded/l);i.total=i.loaded+h}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(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function gs(a,e=null){const t=e||a,i={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(b(s)&&b(n)){var r;let o=s,u=n;if(a.sn==="initSegment"&&hs((r=a.decryptdata)==null?void 0:r.method)){const l=n-s;l%16&&(u=n+(16-l%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=u}return i}function Gi(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),i={type:Z.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(i.part=e),(e||a).stats.aborted=!0,new Vi(i)}function hs(a){return a==="AES-128"||a==="AES-256"}class Vi extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ps extends De{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ts{constructor(e,t,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=ls(),this.buffering={audio:ls(),video:ls(),audiovideo:ls()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=r}}function ls(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Ls={length:0,start:()=>0,end:()=>0};class bt{static isBuffered(e,t){if(e){const i=bt.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){const t=bt.getBuffered(e);return bt.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const s=bt.bufferedRanges(e);if(s.length)return bt.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,h)=>c.start-h.start||h.end-c.end);let s=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(s=c);const h=n.length;if(h){const m=n[h-1].end;e[c].start-m<i?e[c].end>m&&(n[h-1].end=e[c].end):n.push(e[c])}else n.push(e[c])}else n=e;let r=0,o,u=t,l=t;for(let c=0;c<n.length;c++){const h=n[c].start,m=n[c].end;if(s===-1&&t>=h&&t<=m&&(s=c),t+i>=h&&t<m)u=h,l=m,r=l-t;else if(t+i<h){o=h;break}}return{len:r,start:u||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Ls}catch(t){return J.log("failed to get media.buffered",t),Ls}}}const Us=/\{\$([a-zA-Z0-9-_]+)\}/g;function $s(a){return Us.test(a)}function Ms(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Us,i=>{const s=i.substring(2,i.length-1),n=t==null?void 0:t[s];return n===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function Bs(a,e,t){let i=a.variableList;i||(a.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const r=new self.URL(t).searchParams;if(r.has(s))n=r.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(r){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${r.message}`))}}else s=e.NAME,n=e.VALUE;s in i?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function rn(a,e,t){const i=e.IMPORT;if(t&&i in t){let s=a.variableList;s||(a.variableList=s={}),s[i]=t[i]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const fn=/^(\d+)x(\d+)$/,Gs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ai{constructor(e,t){typeof e=="string"&&(e=ai.parseAttrList(e,t)),Re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=fn.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={},n='"';for(Gs.lastIndex=0;(i=Gs.exec(e))!==null;){const r=i[1].trim();let o=i[2];const u=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1;let l=!1;if(u)o=o.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(u||l))o=Ms(t,o);else if(!l&&!u)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":J.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=o}return s}}const mn="com.apple.hls.interstitial";function gn(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Ys(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Zs{constructor(e,t,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=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:i,t){const n=t.attr;for(const r in n)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==n[r]){J.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=Re(new ai({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);b(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(J.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(b(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===mn}get isValid(){return!!this.id&&!this._badValueForSameId&&b(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 qs=10;class Vs{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?b(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||qs}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function us(a,e){return a.length===e.length?!a.some((t,i)=>t!==e[i]):!1}function _s(a,e){return!a&&!e?!0:!a||!e?!1:us(a,e)}function Ss(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function Qi(a){switch(a){case"AES-128":case"AES-256":return ci.cbc;case"AES-256-CTR":return ci.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function wi(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function is(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function Rs(a){const e=is(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Ks(a){const e=function(i,s,n){const r=i[s];i[s]=i[n],i[n]=r};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function an(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[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),t=wi(r)):t=Rs(r)}}return t}const Xs=typeof self!="undefined"?self:void 0;var ki={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ss={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function on(a){switch(a){case ss.FAIRPLAY:return ki.FAIRPLAY;case ss.PLAYREADY:return ki.PLAYREADY;case ss.WIDEVINE:return ki.WIDEVINE;case ss.CLEARKEY:return ki.CLEARKEY}}function rt(a){switch(a){case ki.FAIRPLAY:return ss.FAIRPLAY;case ki.PLAYREADY:return ss.PLAYREADY;case ki.WIDEVINE:return ss.WIDEVINE;case ki.CLEARKEY:return ss.CLEARKEY}}function Tt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,i=e?[ki.FAIRPLAY,ki.WIDEVINE,ki.PLAYREADY,ki.CLEARKEY].filter(s=>!!e[s]):[];return!i[ki.WIDEVINE]&&t&&i.push(ki.WIDEVINE),i}const Li=function(a){return Xs!=null&&(a=Xs.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Yi(a,e,t,i){let s;switch(a){case ki.FAIRPLAY:s=["cenc","sinf"];break;case ki.WIDEVINE:case ki.PLAYREADY:s=["cenc"];break;case ki.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return Ni(s,e,t,i)}function Ni(a,e,t,i){return[{initDataTypes:a,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function pn(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Os(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.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 u=wi(o).subarray(0,16);return Ks(u),u}}return null}let vn={};class Qs{static clearKeyUriToKeyIdMap(){vn={}}constructor(e,t,i,s=[1],n=null,r){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ss(e),r!=null&&r.startsWith("0x")&&(this.keyId=new Uint8Array(X(r)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&us(e.keyFormatVersions,this.keyFormatVersions)&&_s(e.iv,this.iv)&&_s(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ss(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ss.FAIRPLAY:case ss.WIDEVINE:case ss.PLAYREADY:case ss.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(Ss(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(J.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=dr(e);return new Qs(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.pssh&&this.keyId)return this;const t=an(this.uri);if(t)switch(this.keyFormat){case ss.WIDEVINE:if(this.pssh=t,!this.keyId&&t.length>=22){const i=t.length-22;this.keyId=t.subarray(i,i+16)}break;case ss.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=qi(i,null,t),this.keyId=Os(t);break}default:{let i=t.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=vn[this.uri];if(!i){const s=Object.keys(vn).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),vn[this.uri]=i}this.keyId=i}return this}}function dr(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const hr=/#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,fr=/#EXT-X-MEDIA:(.*)/g,Wr=/^#EXT(?:INF|-X-TARGETDURATION):/m,Fn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Mn=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 Hs{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return me.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Wr.test(e)}static parseMasterPlaylist(e,t){const i=$s(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];hr.lastIndex=0;let r;for(;(r=hr.exec(e))!=null;)if(r[1]){var o;const l=new ai(r[1],s),c=Ms(s,r[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:Hs.resolve(c,t)},m=l.decimalResolution("RESOLUTION");m&&(h.width=m.width,h.height=m.height),mr(l.CODECS,h);const v=l["SUPPLEMENTAL-CODECS"];v&&(h.supplemental={},mr(v,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||n.push(h),s.levels.push(h)}else if(r[3]){const l=r[3],c=r[4];switch(l){case"SESSION-DATA":{const h=new ai(c,s),m=h["DATA-ID"];m&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[m]=h);break}case"SESSION-KEY":{const h=Zn(c,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):J.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const h=new ai(c,s);Bs(s,h,t)}break}case"CONTENT-STEERING":{const h=new ai(c,s);s.contentSteering={uri:Hs.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=qn(c);break}}}const u=n.length>0&&n.length<s.levels.length;return s.levels=u?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,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 u=0;for(fr.lastIndex=0;(s=fr.exec(e))!==null;){const l=new ai(s[1],i),c=l.TYPE;if(c){const h=o[c],m=n[c]||[];n[c]=m;const v=l.LANGUAGE,y=l["ASSOC-LANGUAGE"],S=l.CHANNELS,E=l.CHARACTERISTICS,x=l["INSTREAM-ID"],R={attrs:l,bitrate:0,id:u++,groupId:l["GROUP-ID"]||"",name:l.NAME||v||"",type:c,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:v,url:l.URI?Hs.resolve(l.URI,t):""};if(y&&(R.assocLang=y),S&&(R.channels=S),E&&(R.characteristics=E),x&&(R.instreamId=x),h!=null&&h.length){const L=Hs.findGroup(h,R.groupId)||h[0];Xn(R,L,"audioCodec"),Xn(R,L,"textCodec")}m.push(R)}}return n}static parseLevelPlaylist(e,t,i,s,n,r){var o;const u={url:t},l=new Vs(t),c=l.fragments,h=[];let m=null,v=0,y=0,S=0,E=0,x=0,R=null,L=new st(s,u),P,V,re,N=-1,j=!1,Y=null,U;if(Fn.lastIndex=0,l.m3u8=e,l.hasVariableRefs=$s(e),((o=Fn.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(P=Fn.exec(e))!==null;){j&&(j=!1,L=new st(s,u),L.playlistOffset=S,L.setStart(S),L.sn=v,L.cc=E,x&&(L.bitrate=x),L.level=i,m&&(L.initSegment=m,m.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),Y&&(L.setByteRange(Y),Y=null)));const yt=P[1];if(yt){L.duration=parseFloat(yt);const ct=(" "+P[2]).slice(1);L.title=ct||null,L.tagList.push(ct?["INF",yt,ct]:["INF",yt])}else if(P[3]){if(b(L.duration)){L.playlistOffset=S,L.setStart(S),re&&pr(L,re,l),L.sn=v,L.level=i,L.cc=E,c.push(L);const ct=(" "+P[3]).slice(1);L.relurl=Ms(l,ct),Nn(L,R,h),R=L,S+=L.duration,v++,y=0,j=!0}}else{if(P=P[0].match(Mn),!P){J.warn("No matches on slow regex match for level playlist!");continue}for(V=1;V<P.length&&P[V]===void 0;V++);const ct=(" "+P[V]).slice(1),Ue=(" "+P[V+1]).slice(1),pt=P[V+2]?(" "+P[V+2]).slice(1):null;switch(ct){case"BYTERANGE":R?L.setByteRange(Ue,R):L.setByteRange(Ue);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=Ue,L.tagList.push(["PROGRAM-DATE-TIME",Ue]),N===-1&&(N=c.length);break;case"PLAYLIST-TYPE":l.type&&Js(l,ct,P),l.type=Ue.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Js(l,ct,P):c.length>0&&vr(l,ct,P),v=l.startSN=parseInt(Ue);break;case"SKIP":{l.skippedSegments&&Js(l,ct,P);const tt=new ai(Ue,l),vt=tt.decimalInteger("SKIPPED-SEGMENTS");if(b(vt)){l.skippedSegments+=vt;for(let Ge=vt;Ge--;)c.push(null);v+=vt}const Mt=tt.enumeratedString("RECENTLY-REMOVED-DATERANGES");Mt&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(Mt.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Js(l,ct,P),l.targetduration=Math.max(parseInt(Ue),1);break;case"VERSION":l.version!==null&&Js(l,ct,P),l.version=parseInt(Ue);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Js(l,ct,P),l.live=!1;break;case"#":(Ue||pt)&&L.tagList.push(pt?[Ue,pt]:[Ue]);break;case"DISCONTINUITY":E++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([ct]);break;case"BITRATE":L.tagList.push([ct,Ue]),x=parseInt(Ue)*1e3,b(x)?L.bitrate=x:x=0;break;case"DATERANGE":{const tt=new ai(Ue,l),vt=new Zs(tt,l.dateRanges[tt.ID],l.dateRangeTagCount);l.dateRangeTagCount++,vt.isValid||l.skippedSegments?l.dateRanges[vt.id]=vt:J.warn(`Ignoring invalid DATERANGE tag: "${Ue}"`),L.tagList.push(["EXT-X-DATERANGE",Ue]);break}case"DEFINE":{{const tt=new ai(Ue,l);"IMPORT"in tt?rn(l,tt,r):Bs(l,tt,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Js(l,ct,P):c.length>0&&vr(l,ct,P),l.startCC=E=parseInt(Ue);break;case"KEY":{const tt=Zn(Ue,t,l);if(tt.isSupported()){if(tt.method==="NONE"){re=void 0;break}re||(re={});const vt=re[tt.keyFormat];vt!=null&&vt.matches(tt)||(vt&&(re=Re({},re)),re[tt.keyFormat]=tt)}else J.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${Ue}"`);break}case"START":l.startTimeOffset=qn(Ue);break;case"MAP":{const tt=new ai(Ue,l);if(L.duration){const vt=new st(s,u);gr(vt,tt,i,re),m=vt,L.initSegment=m,m.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime)}else{const vt=L.byteRangeEndOffset;if(vt){const Mt=L.byteRangeStartOffset;Y=`${vt-Mt}@${Mt}`}else Y=null;gr(L,tt,i,re),m=L,j=!0}m.cc=E;break}case"SERVER-CONTROL":{U&&Js(l,ct,P),U=new ai(Ue),l.canBlockReload=U.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=U.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&U.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=U.optionalFloat("PART-HOLD-BACK",0),l.holdBack=U.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Js(l,ct,P);const tt=new ai(Ue);l.partTarget=tt.decimalFloatingPoint("PART-TARGET");break}case"PART":{let tt=l.partList;tt||(tt=l.partList=[]);const vt=y>0?tt[tt.length-1]:void 0,Mt=y++,Ge=new ai(Ue,l),Ve=new xt(Ge,L,u,Mt,vt);tt.push(Ve),L.duration+=Ve.duration;break}case"PRELOAD-HINT":{const tt=new ai(Ue,l);l.preloadHint=tt;break}case"RENDITION-REPORT":{const tt=new ai(Ue,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(tt);break}default:J.warn(`line parsed but not handled: ${P}`);break}}}R&&!R.relurl?(c.pop(),S-=R.duration,l.partList&&(l.fragmentHint=R)):l.partList&&(Nn(L,R,h),L.cc=E,l.fragmentHint=L,re&&pr(L,re,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const ce=c.length,He=c[0],ut=c[ce-1];if(S+=l.skippedSegments*l.targetduration,S>0&&ce&&ut){l.averagetargetduration=S/ce;const yt=ut.sn;l.endSN=yt!=="initSegment"?yt:0,l.live||(ut.endList=!0),N>0&&(jr(c,N),He&&h.unshift(He))}return l.fragmentHint&&(S+=l.fragmentHint.duration),l.totalduration=S,h.length&&l.dateRangeTagCount&&He&&Bn(h,l),l.endCC=E,l}}function Bn(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const i=a[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const u=e.dateRanges[n[o]],l=u.startDate.getTime();u.tagAnchor=i.ref;for(let c=t;c--;){var r;if(((r=a[c])==null?void 0:r.sn)<e.startSN)break;const h=yn(e,l,a,c,s);if(h!==-1){u.tagAnchor=e.fragments[h].ref;break}}}}function yn(a,e,t,i,s){const n=t[i];if(n){const o=n.programDateTime;if(e>=o||i===0){var r;const u=(((r=t[i+1])==null?void 0:r.start)||s)-n.start;if(e<=o+u*1e3){const l=t[i].sn-a.startSN;if(l<0)return-1;const c=a.fragments;if(c.length>t.length){const m=(t[i+1]||c[c.length-1]).sn-a.startSN;for(let v=m;v>l;v--){const y=c[v].programDateTime;if(e>=y&&e<y+c[v].duration*1e3)return v}}return l}}}return-1}function Zn(a,e,t){var i,s;const n=new ai(a,t),r=(i=n.METHOD)!=null?i:"",o=n.URI,u=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!u&&J.error(`Invalid IV: ${n.IV}`);const h=o?Hs.resolve(o,e):"",m=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Qs(r,h,c,m,u,n.KEYID)}function qn(a){const t=new ai(a).decimalFloatingPoint("TIME-OFFSET");return b(t)?t:null}function mr(a,e){let t=(a||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=t.filter(n=>rs(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Xn(a,e,t){const i=e[t];i&&(a[t]=i)}function jr(a,e){let t=a[e];for(let i=e;i--;){const s=a[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function Nn(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function gr(a,e,t,i){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",i&&(a.levelkeys=i),a.initSegment=null}function pr(a,e,t){a.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(a)}function Js(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function vr(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Un(a,e){const t=e.startPTS;if(b(t)){let i=0,s;e.sn>a.sn?(i=t-a.start,s=a):(i=a.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function xn(a,e,t,i,s,n,r){i-t<=0&&(r.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let u=t,l=i;const c=e.startPTS,h=e.endPTS;if(b(c)){const x=Math.abs(c-t);a&&x>a.totalduration?r.warn(`media timestamps and playlist times differ by ${x}s for level ${e.level} ${a.url}`):b(e.deltaPTS)?e.deltaPTS=Math.max(x,e.deltaPTS):e.deltaPTS=x,u=Math.max(t,c),t=Math.min(t,c),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,l=Math.min(i,h),i=Math.max(i,h),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const m=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=u,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const v=e.sn;if(!a||v<a.startSN||v>a.endSN)return 0;let y;const S=v-a.startSN,E=a.fragments;for(E[S]=e,y=S;y>0;y--)Un(E[y],E[y-1]);for(y=S;y<E.length-1;y++)Un(E[y],E[y+1]);return a.fragmentHint&&Un(E[E.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,m}function Qn(a,e,t){if(a===e)return;let i=null;const s=a.fragments;for(let c=s.length-1;c>=0;c--){const h=s[c].initSegment;if(h){i=h;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let n;Zr(a,e,(c,h,m,v)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==c.cc){const y=c.cc-h.cc;for(let S=m;S<v.length;S++)v[S].cc+=y;e.endCC=v[v.length-1].cc}b(c.startPTS)&&b(c.endPTS)&&(h.setStart(h.startPTS=c.startPTS),h.startDTS=c.startDTS,h.maxStartPTS=c.maxStartPTS,h.endPTS=c.endPTS,h.endDTS=c.endDTS,h.minEndPTS=c.minEndPTS,h.setDuration(c.endPTS-c.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(h.elementaryStreams=c.elementaryStreams),h.loader=c.loader,c.hasStats&&(h.stats=c.stats),c.initSegment&&(h.initSegment=c.initSegment,i=c.initSegment)});const r=e.fragments,o=e.fragmentHint?r.concat(e.fragmentHint):r;if(i&&o.forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(c.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=r.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)r.shift();e.startSN=r[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=zr(a.dateRanges,e,t));const c=a.fragments.filter(h=>h.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&Nn(o[h],o[h-1],c);Bn(c,e)}e.endCC=r[r.length-1].cc}if(!e.startCC){var u;const c=Er(a,e.startSN-1);e.startCC=(u=c==null?void 0:c.cc)!=null?u:r[0].cc}Yr(a.partList,e.partList,(c,h)=>{h.elementaryStreams=c.elementaryStreams,h.stats=c.stats}),n?xn(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):In(a,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const c=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=c),e.driftEndTime=l,e.driftEnd=c}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function zr(a,e,t){const{dateRanges:i,recentlyRemovedDateranges:s}=e,n=Re({},a);s&&s.forEach(u=>{delete n[u]});const o=Object.keys(n).length;return o?(Object.keys(i).forEach(u=>{const l=n[u],c=new Zs(i[u].attr,l);c.isValid?(n[u]=c,l||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ce(i[u].attr)}"`)}),n):i}function Yr(a,e,t){if(a&&e){let i=0;for(let s=0,n=a.length;s<=n;s++){const r=a[s],o=e[s+i];r&&o&&r.index===o.index&&r.fragment.sn===o.fragment.sn?t(r,o):i--}}}function Zr(a,e,t){const i=e.skippedSegments,s=Math.max(a.startSN,e.startSN)-e.startSN,n=(a.fragmentHint?1:0)+(i?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,r=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=s;l<=n;l++){const c=u[r+l];let h=o[l];if(i&&!h&&c&&(h=e.fragments[l]=c),c&&h){t(c,h,l,o);const m=c.relurl,v=h.relurl;if(m&&qr(m,v)){e.playlistParsingError=Jn(`media sequence mismatch ${h.sn}:`,a,e,c,h);return}else if(c.cc!==h.cc){e.playlistParsingError=Jn(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,a,e,c,h);return}}}}function Jn(a,e,t,i,s){return new Error(`${a} ${s.url}
Playlist starting @${e.startSN}
${e.m3u8}
Playlist starting @${t.startSN}
${t.m3u8}`)}function In(a,e,t=!0){const i=e.startSN+e.skippedSegments-a.startSN,s=a.fragments,n=i>=0;let r=0;if(n&&i<s.length)r=s[i].start;else if(n&&e.startSN===a.endSN+1)r=a.fragmentEnd;else if(n&&t)r=a.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)r=a.fragmentStart;else return;er(e,r)}function er(a,e){if(e){const t=a.fragments;for(let i=a.skippedSegments;i<t.length;i++)t[i].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function yr(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const i=a.fragments;if(i.length&&t*4>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Er(a,e,t){if(!a)return null;let i=a.fragments[e-a.startSN];return i||(i=a.fragmentHint,i&&i.sn===e)?i:e<a.startSN&&t&&t.sn===e?t:null}function tr(a,e,t){return a?_r(a.partList,e,t):null}function _r(a,e,t){if(a)for(let i=a.length;i--;){const s=a[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function Sr(a){a.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function qr(a,e){return a!==e&&e?Tr(a)!==Tr(e):!1}function Tr(a){return a.replace(/\?[^?]*$/,"")}function Cn(a,e){for(let i=0,s=a.length;i<s;i++){var t;if(((t=a[i])==null?void 0:t.cc)===e)return a[i]}return null}function Zi(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function Ri(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Fi(a,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)Ri(t[i],a);e.fragmentHint&&Ri(e.fragmentHint,a),e.alignedSliding=!0}function Is(a,e){a&&(Ts(e,a),e.alignedSliding||En(e,a),!e.alignedSliding&&!e.skippedSegments&&In(a,e,!1))}function Ts(a,e){if(!Zi(e,a))return;const t=Math.min(e.endCC,a.endCC),i=Cn(e.fragments,t),s=Cn(a.fragments,t);if(!i||!s)return;J.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=i.start-s.start;Fi(n,a)}function En(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,i=e.fragments;if(!t.length||!i.length)return;let s,n;const r=Math.min(e.endCC,a.endCC);e.startCC<r&&a.startCC<r&&(s=Cn(i,r),n=Cn(t,r)),(!s||!n)&&(s=i[Math.floor(i.length/2)],n=Cn(t,s.cc)||t[Math.floor(t.length/2)]);const o=s.programDateTime,u=n.programDateTime;if(!o||!u)return;const l=(u-o)/1e3-(n.start-s.start);Fi(l,a)}function ms(a,e,t){xs(a,e,t),a.addEventListener(e,t)}function xs(a,e,t){a.removeEventListener(e,t)}const xr={toString:function(a){let e="";const t=a.length;for(let i=0;i<t;i++)e+=`[${a.start(i).toFixed(3)}-${a.end(i).toFixed(3)}]`;return e}},ue={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 _n extends Ps{constructor(e,t,i,s,n){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ue.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:u,mediaBuffer:l,state:c}=this,h=u?u.currentTime:0,m=bt.bufferInfo(l||u,h,r.maxBufferHole),v=!m.len;if(this.log(`Media seeking to ${b(h)?h.toFixed(3):h}, state: ${c}, ${v?"out of":"in"} buffer`),this.state===ue.ENDED)this.resetLoadingState();else if(o){const y=r.maxFragLookUpTolerance,S=o.start-y,E=o.start+o.duration+y;if(v||E<m.start||S>m.end){const x=h>E;(h<S||x)&&(x&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(u){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const y=this.lastCurrentTime;if(h>y&&(this.lastCurrentTime=h),!this.loadingParts){const S=Math.max(m.end,h),E=this.shouldLoadParts(this.getLevelDetails(),S);E&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${S.toFixed(2)}`),this.loadingParts=E)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,v&&(this.startPosition=h)),v&&this.state===ue.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new ys(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new os(e.config)}registerListeners(){const{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ue.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ue.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=bt.bufferedInfo(n,e.start,0));const r=e.nextStart;if(r&&r>s&&r<t.edge||this.media.currentTime<e.start)return!1;const u=t.partList;if(u!=null&&u.length){const c=u[u.length-1];return bt.isBuffered(this.media,c.start+c.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;ms(i,"seeking",this.onMediaSeeking),ms(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===ue.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),xs(s,"seeking",this.onMediaSeeking),xs(s,"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(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ue.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,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(e,t,i,s).then(n=>{if(!n)return;const r=this.state,o=n.frag;if(this.fragContextChanged(o)){(r===ue.FRAG_LOADING||!this.fragCurrent&&r===ue.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=ue.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(g.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===ue.STOPPED||this.state===ue.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Jt.APPENDING){const n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,r?r.len:this.config.maxBufferLength),u=this.backtrackFragment;((u?e.sn-u.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Jt.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(g.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).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&&Ss(o.method)){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer,Qi(o.method)).catch(l=>{throw s.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const c=self.performance.now();return s.trigger(g.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:u,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===ue.STOPPED||this.state===ue.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==ue.STOPPED&&(this.state=ue.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(s=n.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const r=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${r?"attached mediaKeys: "+r.mediaKeys:"detached"})`);return this.warn(o.message),!r||r.mediaKeys?!1:(this.hls.trigger(g.ERROR,{type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?xr.toString(bt.getBuffered(i)):"(detached)"})`),Ie(e)){var s;if(e.type!==ae.SUBTITLE){const r=e.elementaryStreams;if(!Object.keys(r).some(o=>!!r[o])){this.state=ue.IDLE;return}}const n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=ue.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,r=!n||n.length===0||n.some(u=>!u),o=new ts(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!r);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ue.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(g.KEY_LOADED,m),this.state===ue.KEY_LOADING&&(this.state=ue.IDLE),m}),this.hls.trigger(g.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,r.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const u=this.fragPrevious;if(Ie(e)&&(!u||e.sn!==u.sn)){const m=this.shouldLoadParts(t.details,e.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} loading sn ${u==null?void 0:u.sn}->${e.sn}`),this.loadingParts=m)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ie(e)){const m=r.partList;if(m&&s){i>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const v=this.getNextPart(m,e,i);if(v>-1){const y=m[v];e=this.fragCurrent=y.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${y.index} (${v}/${m.length-1}) of ${this.fragInfo(e,!1,y)}) cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=y.start+y.duration,this.state=ue.FRAG_LOADING;let S;return o?S=o.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,y,t,s)).catch(E=>this.handleFragLoadError(E)):S=this.doFragPartsLoad(e,y,t,s).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(g.FRAG_LOADING,{frag:e,part:y,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):S}else if(!e.url||this.loadedEndOfParts(m,i))return Promise.resolve(null)}}if(Ie(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=r.partList)==null?void 0:l.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),b(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ue.FRAG_LOADING;const c=this.config.progressive;let h;return c&&o?h=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.fragmentLoader.load(e,s)).catch(m=>this.handleFragLoadError(m)):h=Promise.all([this.fragmentLoader.load(e,c?s:void 0),o]).then(([m])=>(!c&&s&&s(m),m)).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(g.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise((n,r)=>{var o;const u=[],l=(o=i.details)==null?void 0:o.partList,c=h=>{this.fragmentLoader.loadPart(e,h,s).then(m=>{u[h.index]=m;const v=m.part;this.hls.trigger(g.FRAG_LOADED,m);const y=tr(i.details,e.sn,h.index+1)||_r(l,e.sn,h.index+1);if(y)c(y);else return n({frag:e,part:v,partsLoaded:u})}).catch(r)};c(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Z.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetFragmentLoading(t.frag)):this.hls.trigger(g.ERROR,t)}else this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==ue.PARSING){!this.fragCurrent&&this.state!==ue.STOPPED&&this.state!==ue.ERROR&&(this.state=ue.IDLE);return}const{frag:i,part:s,level:n}=t,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,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const n=e.partList[0];if(n.fragment.type===ae.SUBTITLE)return!1;const r=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=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(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:r}=e;if(!(t!=null&&t[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=t[s],u=o.details,l=r>-1?tr(u,n,r):null,c=l?l.fragment:Er(u,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,s,n){if(this.state!==ue.PARSING)return;const{data1:r,data2:o}=e;let u=r;if(o&&(u=Bt(r,o)),!u.length)return;const l=this.initPTS[t.cc],c=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:c,parent:t.type,data:u};if(this.hls.trigger(g.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!bt.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=bt.bufferInfo(t,i,0),n=e.duration,r=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-r,s.end-r),i+r);e.start-o>r&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!b(s))return null;const r=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const n=bt.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const r=this.fragmentTracker.getBufferedFrag(t,i);if(r&&(n.nextStart<=r.end||r.gap)){const o=Math.max(Math.min(n.nextStart,r.end)-t,s);return bt.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=ae.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,r=i[0].start,o=n.lowLatencyMode&&!!t.partList;let u=null;if(t.live){const h=n.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<r){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),u=this.getInitialLiveFragment(t);const m=this.hls.startPosition,v=this.hls.liveSyncPosition,y=u?(m!==-1&&m>=r?m:v)||u.start:e;this.log(`Setting startPosition to ${y} to match start frag at live edge. mainStart: ${m} liveSyncPosition: ${v} frag.start: ${(l=u)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=y}}else e<=r&&(u=i[0]);if(!u){const h=this.loadingParts?t.partEnd:t.fragmentEnd;u=this.getFragmentAtPosition(e,h,t)}let c=this.filterReplacedPrimary(u,t);if(!c&&u){const h=u.sn-t.startSN;c=this.filterReplacedPrimary(i[h+1]||null,t)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Jt.OK||i===Jt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){let r=null;if(e.gap&&(r=this.getNextFragment(this.nextLoadPosition,t),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 u=r.sn;return this.loopSn!==u&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${u}`),this.loopSn=u),null}}return this.loopSn=void 0,r}get primaryPrefetch(){if($n(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if($n(this.config)&&e.type!==ae.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(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&(t==null?void 0:t.live)===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.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&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,n=!1,r=!0;for(let o=0,u=e.length;o<u;o++){const l=e[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===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=o),n=c}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=$t(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const r=t[n-e.startSN];i.cc===r.cc&&(s=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=pi(e,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?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:r,endSN:o}=i;const{fragmentHint:u}=i,{maxFragLookUpTolerance:l}=s,c=i.partList,h=!!(this.loadingParts&&c!=null&&c.length&&u);h&&!this.bitrateTest&&c[c.length-1].fragment.sn===u.sn&&(r=r.concat(u),o=u.sn);let m;if(e<t){var v;const S=e<this.lastCurrentTime||e>t-l||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:l;m=zt(n,r,e,S)}else m=r[r.length-1];if(m){const y=m.sn-i.startSN,S=this.fragmentTracker.getState(m);if((S===Jt.OK||S===Jt.PARTIAL&&m.gap)&&(n=m),n&&m.sn===n.sn&&(!h||c[0].fragment.sn>m.sn||!i.live)&&m.level===n.level){const x=r[y+1];m.sn<o&&this.fragmentTracker.getState(x)!==Jt.OK?m=x:m=null}}return m}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,r=!t,o=e.alignedSliding&&b(n);if(r||!o&&!n){Is(i,e);const u=e.fragmentStart;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),u}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(i===-1){const n=this.startTimeOffset!==null,r=n?this.startTimeOffset:e.startTimeOffset;r!==null&&b(r)?(i=t+r,r<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${r} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,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 e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ie(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==ue.FRAG_LOADING_WAITING_RETRY)&&(this.state=ue.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const x=this.getCurrentContext(t.chunkMeta);x&&(t.frag=x.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const r=t.details===A.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const o=t.errorAction;if(!o){this.state=ue.ERROR;return}const{action:u,flags:l,retryCount:c=0,retryConfig:h}=o,m=!!h,v=m&&u===li.RetryRequest,y=m&&!o.resolved&&l===ui.MoveAllAlternatesMatchingHost,S=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&y&&Ie(s)&&!s.endList&&S)this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((v||y)&&c<h.maxNumRetry){var E;const x=bi((E=t.response)==null?void 0:E.code),R=Ei(h,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+R,this.state=ue.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,x){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${c+1}/${h.maxNumRetry} in ${R}ms`)}else if(h)if(this.resetFragmentErrors(e),c<h.maxNumRetry)!r&&u!==li.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else u===li.SendAlternateToPenaltyBox?this.state=ue.WAITING_LEVEL:this.state=ue.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!bi(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ue.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===ue.PARSING||this.state===ue.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);const r=!n;return r&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(e){e===ae.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ue.STOPPED&&(this.state=ue.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=bt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===ue.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ue.STOPPED&&(this.state=ue.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((u,l)=>{const c=e.elementaryStreams[l];if(c){const h=c.endPTS-c.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${h})`),u||!1;const m=s?0:xn(n,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this);return this.hls.trigger(g.LEVEL_PTS_UPDATED,{details:n,level:i,drift:m,type:l,frag:e,start:c.startPTS,end:c.endPTS}),!0}return u},!1)){var o;if(i.fragmentError===0&&this.treatAsGap(e,i),((o=this.transmuxer)==null?void 0:o.error)===null){const u=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(u.message),this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:u,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ue.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(g.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ae.MAIN?"level":"track"}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function $n(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Ar{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=ml(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function ml(a,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<a.length;s++){const n=a[s];t.set(n,i),i+=n.length}return t}var Xr={exports:{}},Ua;function gl(){return Ua||(Ua=1,function(a){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,l,c){this.fn=u,this.context=l,this.once=c||!1}function n(u,l,c,h,m){if(typeof c!="function")throw new TypeError("The listener must be a function");var v=new s(c,h||u,m),y=t?t+l:l;return u._events[y]?u._events[y].fn?u._events[y]=[u._events[y],v]:u._events[y].push(v):(u._events[y]=v,u._eventsCount++),u}function r(u,l){--u._eventsCount===0?u._events=new i:delete u._events[l]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],c,h;if(this._eventsCount===0)return l;for(h in c=this._events)e.call(c,h)&&l.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},o.prototype.listeners=function(l){var c=t?t+l:l,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,v=h.length,y=new Array(v);m<v;m++)y[m]=h[m].fn;return y},o.prototype.listenerCount=function(l){var c=t?t+l:l,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(l,c,h,m,v,y){var S=t?t+l:l;if(!this._events[S])return!1;var E=this._events[S],x=arguments.length,R,L;if(E.fn){switch(E.once&&this.removeListener(l,E.fn,void 0,!0),x){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,c),!0;case 3:return E.fn.call(E.context,c,h),!0;case 4:return E.fn.call(E.context,c,h,m),!0;case 5:return E.fn.call(E.context,c,h,m,v),!0;case 6:return E.fn.call(E.context,c,h,m,v,y),!0}for(L=1,R=new Array(x-1);L<x;L++)R[L-1]=arguments[L];E.fn.apply(E.context,R)}else{var P=E.length,V;for(L=0;L<P;L++)switch(E[L].once&&this.removeListener(l,E[L].fn,void 0,!0),x){case 1:E[L].fn.call(E[L].context);break;case 2:E[L].fn.call(E[L].context,c);break;case 3:E[L].fn.call(E[L].context,c,h);break;case 4:E[L].fn.call(E[L].context,c,h,m);break;default:if(!R)for(V=1,R=new Array(x-1);V<x;V++)R[V-1]=arguments[V];E[L].fn.apply(E[L].context,R)}}return!0},o.prototype.on=function(l,c,h){return n(this,l,c,h,!1)},o.prototype.once=function(l,c,h){return n(this,l,c,h,!0)},o.prototype.removeListener=function(l,c,h,m){var v=t?t+l:l;if(!this._events[v])return this;if(!c)return r(this,v),this;var y=this._events[v];if(y.fn)y.fn===c&&(!m||y.once)&&(!h||y.context===h)&&r(this,v);else{for(var S=0,E=[],x=y.length;S<x;S++)(y[S].fn!==c||m&&!y[S].once||h&&y[S].context!==h)&&E.push(y[S]);E.length?this._events[v]=E.length===1?E[0]:E:r(this,v)}return this},o.prototype.removeAllListeners=function(l){var c;return l?(c=t?t+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=t,o.EventEmitter=o,a.exports=o}(Xr)),Xr.exports}var pl=gl(),Qr=oe(pl);const ir="1.6.11",Gn={};function vl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function yl(){const a=Gn[ir];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return Gn[ir]=s,s}function El(a){const e=Gn[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Gn[a]=s,s}function _l(a){const e=Gn[a||ir];if(e&&e.clientCount--===1){const{worker:i,objectURL:s}=e;delete Gn[a||ir],s&&self.URL.revokeObjectURL(s),i.terminate()}}function $a(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Jr(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function br(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function sr(a,e){const t=e;let i=0;for(;Jr(a,e);){i+=10;const s=br(a,e+6);i+=s,$a(a,e+10)&&(i+=10),e+=i}if(i>0)return a.subarray(t,t+i)}function Sl(a,e,t,i){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],r=n>>2&15;if(r>12){const v=new Error(`invalid ADTS sampling index:${r}`);a.emit(g.ERROR,g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const o=(n>>6&3)+1,u=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,c=s[r];let h=r;(o===5||o===29)&&(h-=3);const m=[o<<3|(h&14)>>1,(h&1)<<7|u<<3];return J.log(`manifest codec:${i}, parsed codec:${l}, channels:${u}, rate:${c} (ADTS object type:${o} sampling index:${r})`),{config:m,samplerate:c,channelCount:u,codec:l,parsedCodec:l,manifestCodec:i}}function Ga(a,e){return a[e]===255&&(a[e+1]&246)===240}function Va(a,e){return a[e+1]&1?7:9}function ea(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Tl(a,e){return e+5<a.length}function Lr(a,e){return e+1<a.length&&Ga(a,e)}function xl(a,e){return Tl(a,e)&&Ga(a,e)&&ea(a,e)<=a.length-e}function Al(a,e){if(Lr(a,e)){const t=Va(a,e);if(e+t>=a.length)return!1;const i=ea(a,e);if(i<=t)return!1;const s=e+i;return s===a.length||Lr(a,s)}return!1}function Ka(a,e,t,i,s){if(!a.samplerate){const n=Sl(e,t,i,s);if(!n)return;Re(a,n)}}function Ha(a){return 1024*9e4/a}function bl(a,e){const t=Va(a,e);if(e+t<=a.length){const i=ea(a,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Wa(a,e,t,i,s){const n=Ha(a.samplerate),r=i+s*n,o=bl(e,t);let u;if(o){const{frameLength:h,headerLength:m}=o,v=m+h,y=Math.max(0,t+v-e.length);y?(u=new Uint8Array(v-m),u.set(e.subarray(t+m,e.length),0)):u=e.subarray(t+m,t+v);const S={unit:u,pts:r};return y||a.samples.push(S),{sample:S,length:v,missing:y}}const l=e.length-t;return u=new Uint8Array(l),u.set(e.subarray(t,e.length),0),{sample:{unit:u,pts:r},length:l,missing:-1}}function Ll(a,e){return Jr(a,e)&&br(a,e+6)+10<=a.length-e}function Rl(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function ta(a,e=0,t=1/0){return Il(a,e,t,Uint8Array)}function Il(a,e,t,i){const s=Cl(a);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const r=Dl(a)?a.byteOffset:0,o=(r+a.byteLength)/n,u=(r+e)/n,l=Math.floor(Math.max(0,Math.min(u,o))),c=Math.floor(Math.min(l+Math.max(t,0),o));return new i(s,l,c-l)}function Cl(a){return a instanceof ArrayBuffer?a:a.buffer}function Dl(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function wl(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=a.data.subarray(1).indexOf(0);if(i===-1)return;const s=_t(ta(a.data,1,i)),n=a.data[2+i],r=a.data.subarray(3+i).indexOf(0);if(r===-1)return;const o=_t(ta(a.data,3+i,r));let u;return s==="-->"?u=_t(ta(a.data,4+i+r)):u=Rl(a.data.subarray(4+i+r)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=u,e}function kl(a){if(a.size<2)return;const e=_t(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Pl(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const i=_t(a.data.subarray(t),!0);t+=i.length+1;const s=_t(a.data.subarray(t));return{key:a.type,info:i,data:s}}const e=_t(a.data.subarray(1));return{key:a.type,info:"",data:e}}function Ol(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const i=_t(a.data.subarray(t),!0);t+=i.length+1;const s=_t(a.data.subarray(t));return{key:a.type,info:i,data:s}}const e=_t(a.data);return{key:a.type,info:"",data:e}}function Fl(a){return a.type==="PRIV"?kl(a):a.type[0]==="W"?Ol(a):a.type==="APIC"?wl(a):Pl(a)}function Ml(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=br(a,4),i=10;return{type:e,size:t,data:a.subarray(i,i+t)}}const Rr=10,Bl=10;function ja(a){let e=0;const t=[];for(;Jr(a,e);){const i=br(a,e+6);a[e+5]>>6&1&&(e+=Rr),e+=Rr;const s=e+i;for(;e+Bl<s;){const n=Ml(a.subarray(e)),r=Fl(n);r&&t.push(r),e+=n.size+Rr}$a(a,e)&&(e+=Rr)}return t}function za(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Nl(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function ia(a){const e=ja(a);for(let t=0;t<e.length;t++){const i=e[t];if(za(i))return Nl(i)}}let Ns=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 ln(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class sa{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Bt(this.cachedData,e),this.cachedData=null);let i=sr(e,0),s=i?i.length:0,n;const r=this._audioTrack,o=this._id3Track,u=i?ia(i):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&b(u))&&(this.basePTS=Ul(u,t,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:Ns.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const c=this.appendFrame(r,e,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=l}else Ll(e,s)?(i=sr(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ns.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===l&&n!==l){const c=e.slice(n);this.cachedData?this.cachedData=Bt(this.cachedData,c):this.cachedData=c}}return{audioTrack:r,videoTrack:ln(),id3Track:o,textTrack:ln()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ln(),id3Track:this._id3Track,textTrack:ln()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Ul=(a,e,t)=>{if(b(a))return a*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Ir=null;const $l=[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],Gl=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Vl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Kl=[0,1,1,4];function Ya(a,e,t,i,s){if(t+24>e.length)return;const n=Za(e,t);if(n&&t+n.frameLength<=e.length){const r=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*r,u={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=n.channelCount,a.samplerate=n.sampleRate,a.samples.push(u),{sample:u,length:n.frameLength,missing:0}}}function Za(a,e){const t=a[e+1]>>3&3,i=a[e+1]>>1&3,s=a[e+2]>>4&15,n=a[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const r=a[e+2]>>1&1,o=a[e+3]>>6,u=t===3?3-i:i===3?3:4,l=$l[u*14+s-1]*1e3,h=Gl[(t===3?0:t===2?1:2)*3+n],m=o===3?1:2,v=Vl[t][i],y=Kl[i],S=v*8*y,E=Math.floor(v*l/h+r)*y;if(Ir===null){const L=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ir=L?parseInt(L[1]):0}return!!Ir&&Ir<=87&&i===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:h,channelCount:m,frameLength:E,samplesPerFrame:S}}}function na(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function qa(a,e){return e+1<a.length&&na(a,e)}function Hl(a,e){return na(a,e)&&4<=a.length-e}function Xa(a,e){if(e+1<a.length&&na(a,e)){const i=Za(a,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===a.length||qa(a,n)}return!1}class Wl extends sa{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=sr(e,0);let s=(i==null?void 0:i.length)||0;if(Xa(e,s))return!1;for(let n=e.length;s<n;s++)if(Al(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return xl(e,t)}appendFrame(e,t,i){Ka(e,this.observer,t,i,e.manifestCodec);const s=Wa(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const Qa=(a,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),r=new Uint8Array(1);for(;i>0;){r[0]=a[e];const o=Math.min(i,8),u=8-o;n[0]=4278190080>>>24+u<<u,s[0]=(r[0]&n[0])>>u,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class jl extends sa{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Ja(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=sr(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&ia(t)!==void 0&&Qa(e,i)<16}}function Ja(a,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],u=e[t+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][u*3+n]*2;if(t+c>e.length)return-1;const h=e[t+6]>>5;let m=0;h===2?m+=2:(h&1&&h!==1&&(m+=2),h&4&&(m+=2));const v=(e[t+6]<<8|e[t+7])>>12-m&1,S=[2,1,2,3,3,4,4,5][h]+v,E=e[t+5]>>3,x=e[t+5]&7,R=new Uint8Array([n<<6|E<<1|x>>2,(x&3)<<6|h<<3|v<<2|u>>4,u<<4&224]),L=1536/o*9e4,P=i+s*L,V=e.subarray(t,t+c);return a.config=R,a.channelCount=S,a.samplerate=o,a.samples.push({unit:V,pts:P}),c}class zl extends sa{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=sr(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&ia(t)!==void 0&&Qa(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Xa(e,i))return J.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Hl(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Ya(e,t,i,this.basePTS,this.frameIndex)}}const Yl=/\/emsg[-/]ID3/i;class Zl{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const n=this.videoTrack=ln("video",1),r=this.audioTrack=ln("audio",1),o=this.txtTrack=ln("text",1);if(this.id3Track=ln("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const u=Oe(e);if(u.video){const{id:l,timescale:c,codec:h,supplemental:m}=u.video;n.id=l,n.timescale=o.timescale=c,n.codec=h,n.supplemental=m}if(u.audio){const{id:l,timescale:c,codec:h}=u.audio;r.id=l,r.timescale=c,r.codec=h}o.id=hi.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Te(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Bt(this.remainderData,e));const o=Vt(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const r=this.extractID3Track(s,t);return n.samples=Lt(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:r,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Lt(e,t),{videoTrack:t,audioTrack:ln(),id3Track:s,textTrack:ln()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=B(e.samples,["emsg"]);s&&s.forEach(n=>{const r=pe(n);if(Yl.test(r.schemeIdUri)){const o=eo(r,t);let u=r.eventDuration===4294967295?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;u<=.001&&(u=Number.POSITIVE_INFINITY);const l=r.payload;i.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ns.emsg,duration:u})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=eo(r,t);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:o,pts:o,type:Ns.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,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 eo(a,e){return b(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class ql{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new os(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ci.cbc)}decryptAacSample(e,t,i){const s=e[t].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 u=new Uint8Array(o);s.set(u,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){const r=Ii(n.data),o=this.getAvcEncryptedData(r);this.decryptBuffer(o.buffer).then(u=>{n.data=this.getAvcDecryptedUnit(r,u),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const r=n[i];if(!(r.data.length<=48||r.type!==1&&r.type!==5)&&(this.decryptAvcSample(e,t,i,s,r),!this.decrypter.isSync()))return}}}}class to{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let n=e.naluState||0;const r=n,o=[];let u=0,l,c,h,m=-1,v=0;for(n===-1&&(m=0,v=this.getNALuType(t,0),n=0,u=1);u<s;){if(l=t[u++],!n){n=l?0:1;continue}if(n===1){n=l?0:2;continue}if(!l)n=3;else if(l===1){if(c=u-n-1,m>=0){const y={data:t.subarray(m,c),type:v};o.push(y)}else{const y=this.getLastNalUnit(e.samples);y&&(r&&u<=4-r&&y.state&&(y.data=y.data.subarray(0,y.data.byteLength-r)),c>0&&(y.data=Bt(y.data,t.subarray(0,c)),y.state=0))}u<s?(h=this.getNALuType(t,u),m=u,v=h,n=0):n=-1}else n=0}if(m>=0&&n>=0){const y={data:t.subarray(m,s),type:v,state:n};o.push(y)}if(o.length===0){const y=this.getLastNalUnit(e.samples);y&&(y.data=Bt(y.data,t))}return e.naluState=n,o}}class nr{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&J.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Xl extends to{parsePES(e,t,i,s){const n=this.parseNALu(e,i.data,s);let r=this.VideoSample,o,u=!1;i.data=null,r&&n.length&&!e.audFound&&(this.pushAccessUnit(r,e),r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(l=>{var c,h;switch(l.type){case 1:{let S=!1;o=!0;const E=l.data;if(u&&E.length>4){const x=this.readSliceType(E);(x===2||x===4||x===7||x===9)&&(S=!0)}if(S){var m;(m=r)!=null&&m.frame&&!r.key&&(this.pushAccessUnit(r,e),r=this.VideoSample=null)}r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.frame=!0,r.key=S;break}case 5:o=!0,(c=r)!=null&&c.frame&&!r.key&&(this.pushAccessUnit(r,e),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,Xt(l.data,1,i.pts,t.samples);break}case 7:{var v,y;o=!0,u=!0;const S=l.data,E=this.readSPS(S);if(!e.sps||e.width!==E.width||e.height!==E.height||((v=e.pixelRatio)==null?void 0:v[0])!==E.pixelRatio[0]||((y=e.pixelRatio)==null?void 0:y[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[S];const x=S.subarray(1,4);let R="avc1.";for(let L=0;L<3;L++){let P=x[L].toString(16);P.length<2&&(P="0"+P),R+=P}e.codec=R}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(h=r)!=null&&h.frame&&(this.pushAccessUnit(r,e),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,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new nr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,n;for(let r=0;r<e;r++)s!==0&&(n=t.readEG(),s=(i+n+256)%256),i=s===0?i:s}readSPS(e){const t=new nr(e);let i=0,s=0,n=0,r=0,o,u,l;const c=t.readUByte.bind(t),h=t.readBits.bind(t),m=t.readUEG.bind(t),v=t.readBoolean.bind(t),y=t.skipBits.bind(t),S=t.skipEG.bind(t),E=t.skipUEG.bind(t),x=this.skipScalingList.bind(this);c();const R=c();if(h(5),y(3),c(),E(),R===100||R===110||R===122||R===244||R===44||R===83||R===86||R===118||R===128){const j=m();if(j===3&&y(1),E(),E(),y(1),v())for(u=j!==3?8:12,l=0;l<u;l++)v()&&(l<6?x(16,t):x(64,t))}E();const L=m();if(L===0)m();else if(L===1)for(y(1),S(),S(),o=m(),l=0;l<o;l++)S();E(),y(1);const P=m(),V=m(),re=h(1);re===0&&y(1),y(1),v()&&(i=m(),s=m(),n=m(),r=m());let N=[1,1];if(v()&&v())switch(c()){case 1:N=[1,1];break;case 2:N=[12,11];break;case 3:N=[10,11];break;case 4:N=[16,11];break;case 5:N=[40,33];break;case 6:N=[24,11];break;case 7:N=[20,11];break;case 8:N=[32,11];break;case 9:N=[80,33];break;case 10:N=[18,11];break;case 11:N=[15,11];break;case 12:N=[64,33];break;case 13:N=[160,99];break;case 14:N=[4,3];break;case 15:N=[3,2];break;case 16:N=[2,1];break;case 255:{N=[c()<<8|c(),c()<<8|c()];break}}return{width:Math.ceil((P+1)*16-i*2-s*2),height:(2-re)*(V+1)*16-(re?2:4)*(n+r),pixelRatio:N}}}class Ql extends to{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const n=this.parseNALu(e,i.data,s);let r=this.VideoSample,o,u=!1;i.data=null,r&&n.length&&!e.audFound&&(this.pushAccessUnit(r,e),r=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(l=>{var c,h;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,u){var m;(m=r)!=null&&m.frame&&!r.key&&(this.pushAccessUnit(r,e),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,e),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,Xt(l.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Re(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,u=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const v=this.readSPS(l.data);e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const y in v.params)e.params[y]=v.params[y]}this.pushParameterSet(e.sps,l.data,e.vps),r||(r=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),r.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const v=this.readPPS(l.data);for(const y in v)e.params[y]=v[y]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(h=r)!=null&&h.frame&&(this.pushAccessUnit(r,e),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,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new nr(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new nr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),n=t.readBoolean(),r=t.readBits(5),o=t.readUByte(),u=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),m=t.readUByte(),v=t.readUByte(),y=t.readUByte(),S=t.readUByte(),E=t.readUByte(),x=t.readUByte(),R=[],L=[];for(let xi=0;xi<i;xi++)R.push(t.readBoolean()),L.push(t.readBoolean());if(i>0)for(let xi=i;xi<8;xi++)t.readBits(2);for(let xi=0;xi<i;xi++)R[xi]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),L[xi]&&t.readUByte();t.readUEG();const P=t.readUEG();P==3&&t.skipBits(1);const V=t.readUEG(),re=t.readUEG(),N=t.readBoolean();let j=0,Y=0,U=0,ce=0;N&&(j+=t.readUEG(),Y+=t.readUEG(),U+=t.readUEG(),ce+=t.readUEG());const He=t.readUEG(),ut=t.readUEG(),yt=t.readUEG(),ct=t.readBoolean();for(let xi=ct?0:i;xi<=i;xi++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let bs=0;bs<4;bs++)for(let zs=0;zs<(bs===3?2:6);zs++)if(!t.readBoolean())t.readUEG();else{const nn=Math.min(64,1<<4+(bs<<1));bs>1&&t.readEG();for(let Yn=0;Yn<nn;Yn++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const tt=t.readUEG();let vt=0;for(let xi=0;xi<tt;xi++){let bs=!1;if(xi!==0&&(bs=t.readBoolean()),bs){xi===tt&&t.readUEG(),t.readBoolean(),t.readUEG();let zs=0;for(let Pn=0;Pn<=vt;Pn++){const nn=t.readBoolean();let Yn=!1;nn||(Yn=t.readBoolean()),(nn||Yn)&&zs++}vt=zs}else{const zs=t.readUEG(),Pn=t.readUEG();vt=zs+Pn;for(let nn=0;nn<zs;nn++)t.readUEG(),t.readBoolean();for(let nn=0;nn<Pn;nn++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const xi=t.readUEG();for(let bs=0;bs<xi;bs++){for(let zs=0;zs<yt+4;zs++)t.readBits(1);t.readBits(1)}}let Ge=0,Ve=1,ii=1,Di=!0,ri=1,vi=0;t.readBoolean(),t.readBoolean();let As=!1;if(t.readBoolean()){if(t.readBoolean()){const On=t.readUByte(),ll=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Hr=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];On>0&&On<16?(Ve=ll[On-1],ii=Hr[On-1]):On===255&&(Ve=t.readBits(16),ii=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),As=t.readBoolean(),As&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ri=t.readBits(32),vi=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Hr=t.readBoolean(),ul=t.readBoolean();let ur=!1;(Hr||ul)&&(ur=t.readBoolean(),ur&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ur&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let cl=0;cl<=i;cl++){Di=t.readBoolean();const wd=Di||t.readBoolean();let dl=!1;wd?t.readEG():dl=t.readBoolean();const hl=dl?1:t.readUEG()+1;if(Hr)for(let cr=0;cr<hl;cr++)t.readUEG(),t.readUEG(),ur&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ul)for(let cr=0;cr<hl;cr++)t.readUEG(),t.readUEG(),ur&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Ge=t.readUEG())}let js=V,hn=re;if(N){let xi=1,bs=1;P===1?xi=bs=2:P==2&&(xi=2),js=V-xi*Y-xi*j,hn=re-bs*ce-bs*U}const kn=s?["A","B","C"][s]:"",Dd=o<<24|u<<16|l<<8|c;let Ba=0;for(let xi=0;xi<32;xi++)Ba=(Ba|(Dd>>xi&1)<<31-xi)>>>0;let Na=Ba.toString(16);return r===1&&Na==="2"&&(Na="6"),{codecString:`hvc1.${kn}${r}.${Na}.${n?"H":"L"}${x}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[o,u,l,c],general_constraint_indicator_flags:[h,m,v,y,S,E],general_level_idc:x,bit_depth:He+8,bit_depth_luma_minus8:He,bit_depth_chroma_minus8:ut,min_spatial_segmentation_idc:Ge,chroma_format_idc:P,frame_rate:{fixed:Di,fps:vi/ri}},width:js,height:hn,pixelRatio:[Ve,ii]}}readPPS(e){const t=new nr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),n=t.readBoolean();let r=1;return n&&s?r=0:n?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const ps=188;class An{constructor(e,t,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=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=An.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(ps*5,t-ps)+1,s=0;for(;s<i;){let n=!1,r=-1,o=0;for(let u=s;u<t;u+=ps)if(e[u]===71&&(t-u===ps||e[u+ps]===71)){if(o++,r===-1&&(r=u,r!==0&&(i=Math.min(r+ps*99,e.length-ps)+1)),n||(n=ra(e,u)===0),n&&o>1&&(r===0&&o>2||u+ps>i))return r}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:hi[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=An.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=An.createTrack("audio",s),this._id3Track=An.createTrack("id3"),this._txtTrack=An.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let n;const r=this._videoTrack,o=this._audioTrack,u=this._id3Track,l=this._txtTrack;let c=r.pid,h=r.pesData,m=o.pid,v=u.pid,y=o.pesData,S=u.pesData,E=null,x=this.pmtParsed,R=this._pmtId,L=e.length;if(this.remainderData&&(e=Bt(this.remainderData,e),L=e.length,this.remainderData=null),L<ps&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:r,id3Track:u,textTrack:l};const P=Math.max(0,An.syncOffset(e));L-=(L-P)%ps,L<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,L,e.buffer.byteLength-L));let V=0;for(let N=P;N<L;N+=ps)if(e[N]===71){const j=!!(e[N+1]&64),Y=ra(e,N),U=(e[N+3]&48)>>4;let ce;if(U>1){if(ce=N+5+e[N+4],ce===N+ps)continue}else ce=N+4;switch(Y){case c:j&&(h&&(n=Vn(h,this.logger))&&(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(r,l,n,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(ce,N+ps)),h.size+=N+ps-ce);break;case m:if(j){if(y&&(n=Vn(y,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}y={data:[],size:0}}y&&(y.data.push(e.subarray(ce,N+ps)),y.size+=N+ps-ce);break;case v:j&&(S&&(n=Vn(S,this.logger))&&this.parseID3PES(u,n),S={data:[],size:0}),S&&(S.data.push(e.subarray(ce,N+ps)),S.size+=N+ps-ce);break;case 0:j&&(ce+=e[ce]+1),R=this._pmtId=Jl(e,ce);break;case R:{j&&(ce+=e[ce]+1);const He=eu(e,ce,this.typeSupported,i,this.observer,this.logger);c=He.videoPid,c>0&&(r.pid=c,r.segmentCodec=He.segmentVideoCodec),m=He.audioPid,m>0&&(o.pid=m,o.segmentCodec=He.segmentAudioCodec),v=He.id3Pid,v>0&&(u.pid=v),E!==null&&!x&&(this.logger.warn(`MPEG-TS PMT found at ${N} after unknown PID '${E}'. Backtracking to sync byte @${P} to parse all TS packets.`),E=null,N=P-188),x=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=Y;break}}else V++;V>0&&aa(this.observer,new Error(`Found ${V} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=h,o.pesData=y,u.pesData=S;const re={audioTrack:o,videoTrack:r,id3Track:u,textTrack:l};return s&&this.extractRemainingSamples(re),re}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:n}=e,r=i.pesData,o=t.pesData,u=s.pesData;let l;if(r&&(l=Vn(r,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,l,!0),i.pesData=null)):i.pesData=r,o&&(l=Vn(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;u&&(l=Vn(u,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=u}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new ql(this.observer,this.config,t);return this.decrypt(s,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Xl:e==="hevc"&&(this.videoParser=new Ql))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}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(e,t){let i=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const h=s.missing,m=s.sample.unit.byteLength;if(h===-1)n=Bt(s.sample.unit,n);else{const v=m-h;s.sample.unit.set(n.subarray(0,h),v),e.samples.push(s.sample),i=s.missing}}let r,o;for(r=i,o=n.length;r<o-1&&!Lr(n,r);r++);if(r!==i){let h;const m=r<o-1;if(m?h=`AAC PES did not start with ADTS header,offset:${r}`:h="No ADTS header found in AAC PES",aa(this.observer,new Error(h),m,this.logger),!m)return}Ka(e,this.observer,n,r,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(s){const h=Ha(e.samplerate);u=s.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,c;for(;r<o;)if(c=Wa(e,n,r,u,l),r+=c.length,c.missing){this.aacOverFlow=c;break}else for(l++;r<o-1&&!Lr(n,r);r++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let n=0,r=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;r<s;)if(qa(i,r)){const u=Ya(e,i,r,o,n);if(u)r+=u.length,n++;else break}else r++}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let r=0,o=0,u;for(;o<n&&(u=Ja(e,i,o,s,r++))>0;)o+=u}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Re({},t,{type:this._videoTrack?Ns.emsg:Ns.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function ra(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Jl(a,e){return(a[e+10]&31)<<8|a[e+11]}function eu(a,e,t,i,s,n){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],u=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<u;){const c=ra(a,e),h=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!i){oa("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){oa("H.264",n);break}case 27:r.videoPid===-1&&(r.videoPid=c);break;case 3:case 4:!t.mpeg&&!t.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){oa("AC-3",n);break}case 129:t.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&&h>0){let m=e+5,v=h;for(;v>2;){switch(a[m]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3");break}const S=a[m+1]+2;m+=S,v-=S}}break;case 194:case 135:return aa(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}e+=h+5}return r}function aa(a,e,t,i){i.warn(`parsing error: ${e.message}`),a.emit(g.ERROR,g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function oa(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Vn(a,e){let t=0,i,s,n,r,o;const u=a.data;if(!a||a.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=Bt(u[0],u[1]),u.splice(1,1);if(i=u[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&&(e.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),n=i[8];let h=n+9;if(a.size<=h)return null;a.size-=h;const m=new Uint8Array(a.size);for(let v=0,y=u.length;v<y;v++){i=u[v];let S=i.byteLength;if(h)if(h>S){h-=S;continue}else i=i.subarray(h),S-=h,h=0;m.set(i,t),t+=S}return s&&(s-=n+3),{data:m,pts:r,dts:o,len:s}}return null}class tu{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const bn=Math.pow(2,32)-1;class K{static init(){K.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 e;for(e in K.types)K.types.hasOwnProperty(e)&&(K.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),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]);K.HDLR_TYPES={video:t,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]);K.STTS=K.STSC=K.STCO=n,K.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),K.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),K.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),K.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]),u=new Uint8Array([0,0,0,1]);K.FTYP=K.box(K.types.ftyp,r,u,r,o),K.DINF=K.box(K.types.dinf,K.box(K.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(e,4),s=0,i=8;s<n;s++)r.set(t[s],i),i+=t[s].byteLength;return r}static hdlr(e){return K.box(K.types.hdlr,K.HDLR_TYPES[e])}static mdat(e){return K.box(K.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(bn+1)),s=Math.floor(t%(bn+1));return K.box(K.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,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(e){return K.box(K.types.mdia,K.mdhd(e.timescale||0,e.duration||0),K.hdlr(e.type),K.minf(e))}static mfhd(e){return K.box(K.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?K.box(K.types.minf,K.box(K.types.smhd,K.SMHD),K.DINF,K.stbl(e)):K.box(K.types.minf,K.box(K.types.vmhd,K.VMHD),K.DINF,K.stbl(e))}static moof(e,t,i){return K.box(K.types.moof,K.mfhd(e),K.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=K.trak(e[t]);return K.box.apply(null,[K.types.moov,K.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(K.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=K.trex(e[t]);return K.box.apply(null,[K.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(bn+1)),s=Math.floor(t%(bn+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,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 K.box(K.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return K.box(K.types.sdtp,i)}static stbl(e){return K.box(K.types.stbl,K.stsd(e),K.box(K.types.stts,K.STTS),K.box(K.types.stsc,K.STSC),K.box(K.types.stsz,K.STSZ),K.box(K.types.stco,K.STCO))}static avc1(e){let t=[],i=[],s,n,r;for(s=0;s<e.sps.length;s++)n=e.sps[s],r=n.byteLength,t.push(r>>>8&255),t.push(r&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],r=n.byteLength,i.push(r>>>8&255),i.push(r&255),i=i.concat(Array.prototype.slice.call(n));const o=K.box(K.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),u=e.width,l=e.height,c=e.pixelRatio[0],h=e.pixelRatio[1];return K.box(K.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,u>>8&255,u&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,K.box(K.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),K.box(K.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.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,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return K.box(K.types.mp4a,K.audioStsd(e),K.box(K.types.esds,K.esds(e)))}static mp3(e){return K.box(K.types[".mp3"],K.audioStsd(e))}static ac3(e){return K.box(K.types["ac-3"],K.audioStsd(e),K.box(K.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return K.box(K.types.stsd,K.STSD,K.mp4a(e));if(t==="ac3"&&e.config)return K.box(K.types.stsd,K.STSD,K.ac3(e));if(t==="mp3"&&e.codec==="mp3")return K.box(K.types.stsd,K.STSD,K.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return K.box(K.types.stsd,K.STSD,K.avc1(e));if(t==="hevc"&&e.vps)return K.box(K.types.stsd,K.STSD,K.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,r=Math.floor(i/(bn+1)),o=Math.floor(i%(bn+1));return K.box(K.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,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(e,t){const i=K.sdtp(e),s=e.id,n=Math.floor(t/(bn+1)),r=Math.floor(t%(bn+1));return K.box(K.types.traf,K.box(K.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),K.box(K.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])),K.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,K.box(K.types.trak,K.tkhd(e),K.mdia(e))}static trex(e){const t=e.id;return K.box(K.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,n=12+16*s,r=new Uint8Array(n);let o,u,l,c,h,m;for(t+=8+n,r.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)u=i[o],l=u.duration,c=u.size,h=u.flags,m=u.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,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,m>>>24&255,m>>>16&255,m>>>8&255,m&255],12+16*o);return K.box(K.types.trun,r)}static initSegment(e){K.types||K.init();const t=K.moov(e);return Bt(K.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let r=n.length;for(let y=0;y<i.length;y+=1){r+=3;for(let S=0;S<i[y].length;S+=1)r+=2+i[y][S].length}const o=new Uint8Array(r);o.set(n,0),r=n.length;const u=i.length-1;for(let y=0;y<i.length;y+=1){o.set(new Uint8Array([32+y|(y===u?128:0),0,i[y].length]),r),r+=3;for(let S=0;S<i[y].length;S+=1)o.set(new Uint8Array([i[y][S].length>>8,i[y][S].length&255]),r),r+=2,o.set(i[y][S],r),r+=i[y][S].length}const l=K.box(K.types.hvcC,o),c=e.width,h=e.height,m=e.pixelRatio[0],v=e.pixelRatio[1];return K.box(K.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,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,K.box(K.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),K.box(K.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,v>>24,v>>16&255,v>>8&255,v&255])))}}K.types=void 0,K.HDLR_TYPES=void 0,K.STTS=void 0,K.STSC=void 0,K.STCO=void 0,K.STSZ=void 0,K.VMHD=void 0,K.SMHD=void 0,K.STSD=void 0,K.FTYP=void 0,K.DINF=void 0;const io=9e4;function la(a,e,t=1,i=!1){const s=a*e*t;return i?Math.round(s):s}function iu(a,e,t=1,i=!1){return la(a,e,1/t,i)}function rr(a,e=!1){return la(a,1e3,1/io,e)}function su(a,e=1){return la(a,io,1/e)}const nu=10*1e3,ru=1024,au=1152,ou=1536;let Kn=null,ua=null;function so(a,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class Cr extends De{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Kn===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Kn=r?parseInt(r[1]):0}if(ua===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);ua=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((n,r)=>{let o=r.pts,u=o-n;return u<-4294967296&&(t=!0,o=Ws(o,i),u=o-n),u>0?n:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,n,r,o,u){let l,c,h,m,v,y,S=n,E=n;const x=e.pid>-1,R=t.pid>-1,L=t.samples.length,P=e.samples.length>0,V=o&&L>0||L>1;if((!x||P)&&(!R||V)||this.ISGenerated||o){if(this.ISGenerated){var N,j,Y,U;const yt=this.videoTrackConfig;(yt&&(t.width!==yt.width||t.height!==yt.height||((N=t.pixelRatio)==null?void 0:N[0])!==((j=yt.pixelRatio)==null?void 0:j[0])||((Y=t.pixelRatio)==null?void 0:Y[1])!==((U=yt.pixelRatio)==null?void 0:U[1]))||!yt&&V||this.nextAudioTs===null&&P)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,r));const ce=this.isVideoContiguous;let He=-1,ut;if(V&&(He=lu(t.samples),!ce&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,He>0){this.warn(`Dropped ${He} out of ${L} video samples due to a missing keyframe`);const yt=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(He),t.dropped+=He,E+=(t.samples[0].pts-yt)/t.inputTimeScale,ut=E}else He===-1&&(this.warn(`No keyframe found out of ${L} video samples`),y=!1);if(this.ISGenerated){if(P&&V){const yt=this.getVideoStartPts(t.samples),Ue=(Ws(e.samples[0].pts,yt)-yt)/t.inputTimeScale;S+=Math.max(0,Ue),E+=Math.max(0,-Ue)}if(P){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,r)),c=this.remuxAudio(e,S,this.isAudioContiguous,r,R||V||u===ae.AUDIO?E:void 0),V){const yt=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,r)),l=this.remuxVideo(t,E,ce,yt)}}else V&&(l=this.remuxVideo(t,E,ce,0));l&&(l.firstKeyFrame=He,l.independent=He!==-1,l.firstKeyFramePTS=ut)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=no(i,n,this._initPTS,this._initDTS)),s.samples.length&&(m=ro(s,n,this._initPTS))),{audio:c,video:l,initSegment:h,independent:y,text:m,id3:v}}generateIS(e,t,i,s){const n=e.samples,r=t.samples,o=this.typeSupported,u={},l=this._initPTS;let c=!l||s,h="audio/mp4",m,v,y,S=-1;if(c&&(m=v=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}u.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):K.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(S=e.id,y=e.inputTimeScale,!l||y!==l.timescale?m=v=n[0].pts-Math.round(y*i):c=!1)}if(t.sps&&t.pps&&r.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:K.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(S=t.id,y=t.inputTimeScale,!l||y!==l.timescale){const E=this.getVideoStartPts(r),x=Math.round(y*i);v=Math.min(v,Ws(r[0].dts,E)-x),m=Math.min(m,E-x)}else c=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${m/y} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${m/y} (${m}/${y}) trackId: ${S}`),this._initPTS={baseTime:m,timescale:y,trackId:S},this._initDTS={baseTime:v,timescale:y,trackId:S}):m=y=void 0,{tracks:u,initPTS:m,timescale:y,trackId:S}}remuxVideo(e,t,i,s){const n=e.inputTimeScale,r=e.samples,o=[],u=r.length,l=this._initPTS,c=l.baseTime*n/l.timescale;let h=this.nextVideoTs,m=8,v=this.videoSampleDuration,y,S,E=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,R=!1;if(!i||h===null){const Ge=c+t*n,Ve=r[0].pts-Ws(r[0].dts,r[0].pts);Kn&&h!==null&&Math.abs(Ge-Ve-(h+c))<15e3?i=!0:h=Ge-Ve-c}const L=h+c;for(let Ge=0;Ge<u;Ge++){const Ve=r[Ge];Ve.pts=Ws(Ve.pts,L),Ve.dts=Ws(Ve.dts,L),Ve.dts<r[Ge>0?Ge-1:Ge].dts&&(R=!0)}R&&r.sort(function(Ge,Ve){const ii=Ge.dts-Ve.dts,Di=Ge.pts-Ve.pts;return ii||Di}),y=r[0].dts,S=r[r.length-1].dts;const P=S-y,V=P?Math.round(P/(u-1)):v||e.inputTimeScale/30;if(i){const Ge=y-L,Ve=Ge>V,ii=Ge<-1;if((Ve||ii)&&(Ve?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rr(Ge,!0)} ms (${Ge}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rr(-Ge,!0)} ms (${Ge}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ii||L>=r[0].pts||Kn)){y=L;const Di=r[0].pts-Ge;if(Ve)r[0].dts=y,r[0].pts=Di;else{let ri=!0;for(let vi=0;vi<r.length&&!(r[vi].dts>Di&&ri);vi++){const As=r[vi].pts;if(r[vi].dts-=Ge,r[vi].pts-=Ge,vi<r.length-1){const Es=r[vi+1].pts,js=r[vi].pts,hn=Es<=js,kn=Es<=As;ri=hn==kn}}}this.log(`Video: Initial PTS/DTS adjusted: ${rr(Di,!0)}/${rr(y,!0)}, delta: ${rr(Ge,!0)} ms`)}}y=Math.max(0,y);let re=0,N=0,j=y;for(let Ge=0;Ge<u;Ge++){const Ve=r[Ge],ii=Ve.units,Di=ii.length;let ri=0;for(let vi=0;vi<Di;vi++)ri+=ii[vi].data.length;N+=ri,re+=Di,Ve.length=ri,Ve.dts<j?(Ve.dts=j,j+=V/4|0||1):j=Ve.dts,E=Math.min(Ve.pts,E),x=Math.max(Ve.pts,x)}S=r[u-1].dts;const Y=N+4*re+8;let U;try{U=new Uint8Array(Y)}catch(Ge){this.observer.emit(g.ERROR,g.ERROR,{type:Z.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:Ge,bytes:Y,reason:`fail allocating video mdat ${Y}`});return}const ce=new DataView(U.buffer);ce.setUint32(0,Y),U.set(K.types.mdat,4);let He=!1,ut=Number.POSITIVE_INFINITY,yt=Number.POSITIVE_INFINITY,ct=Number.NEGATIVE_INFINITY,Ue=Number.NEGATIVE_INFINITY;for(let Ge=0;Ge<u;Ge++){const Ve=r[Ge],ii=Ve.units;let Di=0;for(let As=0,Es=ii.length;As<Es;As++){const js=ii[As],hn=js.data,kn=js.data.byteLength;ce.setUint32(m,kn),m+=4,U.set(hn,m),m+=kn,Di+=4+kn}let ri;if(Ge<u-1)v=r[Ge+1].dts-Ve.dts,ri=r[Ge+1].pts-Ve.pts;else{const As=this.config,Es=Ge>0?Ve.dts-r[Ge-1].dts:V;if(ri=Ge>0?Ve.pts-r[Ge-1].pts:V,As.stretchShortVideoTrack&&this.nextAudioTs!==null){const js=Math.floor(As.maxBufferHole*n),hn=(s?E+s*n:this.nextAudioTs+c)-Ve.pts;hn>js?(v=hn-Es,v<0?v=Es:He=!0,this.log(`It is approximately ${hn/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=Es}else v=Es}const vi=Math.round(Ve.pts-Ve.dts);ut=Math.min(ut,v),ct=Math.max(ct,v),yt=Math.min(yt,ri),Ue=Math.max(Ue,ri),o.push(so(Ve.key,v,Di,vi))}if(o.length){if(Kn){if(Kn<70){const Ge=o[0].flags;Ge.dependsOn=2,Ge.isNonSync=0}}else if(ua&&Ue-yt<ct-ut&&V/ct<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let Ge=y;for(let Ve=0,ii=o.length;Ve<ii;Ve++){const Di=Ge+o[Ve].duration,ri=Ge+o[Ve].cts;if(Ve<ii-1){const vi=Di+o[Ve+1].cts;o[Ve].duration=vi-ri}else o[Ve].duration=Ve?o[Ve-1].duration:V;o[Ve].cts=0,Ge=Di}}}v=He||!v?V:v;const pt=S+v;this.nextVideoTs=h=pt-c,this.videoSampleDuration=v,this.isVideoContiguous=!0;const Mt={data1:K.moof(e.sequenceNumber++,y,Re(e,{samples:o})),data2:U,startPTS:(E-c)/n,endPTS:(x+v-c)/n,startDTS:(y-c)/n,endDTS:h/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Mt}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return au;case"ac3":return ou;default:return ru}}remuxAudio(e,t,i,s,n){const r=e.inputTimeScale,o=e.samplerate?e.samplerate:r,u=r/o,l=this.getSamplesPerFrame(e),c=l*u,h=this._initPTS,m=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,v=[],y=n!==void 0;let S=e.samples,E=m?0:8,x=this.nextAudioTs||-1;const R=h.baseTime*r/h.timescale,L=R+t*r;if(this.isAudioContiguous=i=i||S.length&&x>0&&(s&&Math.abs(L-(x+R))<9e3||Math.abs(Ws(S[0].pts,L)-(x+R))<20*c),S.forEach(function(Ue){Ue.pts=Ws(Ue.pts,L)}),!i||x<0){if(S=S.filter(Ue=>Ue.pts>=0),!S.length)return;n===0?x=0:s&&!y?x=Math.max(0,L-R):x=S[0].pts-R}if(e.segmentCodec==="aac"){const Ue=this.config.maxAudioFramesDrift;for(let pt=0,tt=x+R;pt<S.length;pt++){const vt=S[pt],Mt=vt.pts,Ge=Mt-tt,Ve=Math.abs(1e3*Ge/r);if(Ge<=-Ue*c&&y)pt===0&&(this.warn(`Audio frame @ ${(Mt/r).toFixed(3)}s overlaps marker by ${Math.round(1e3*Ge/r)} ms.`),this.nextAudioTs=x=Mt-R,tt=Mt);else if(Ge>=Ue*c&&Ve<nu&&y){let ii=Math.round(Ge/c);for(tt=Mt-ii*c;tt<0&&ii&&c;)ii--,tt+=c;pt===0&&(this.nextAudioTs=x=tt-R),this.warn(`Injecting ${ii} audio frames @ ${((tt-R)/r).toFixed(3)}s due to ${Math.round(1e3*Ge/r)} ms gap.`);for(let Di=0;Di<ii;Di++){let ri=tu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ri||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ri=vt.unit.subarray()),S.splice(pt,0,{unit:ri,pts:tt}),tt+=c,pt++}}vt.pts=tt,tt+=c}}let P=null,V=null,re,N=0,j=S.length;for(;j--;)N+=S[j].unit.byteLength;for(let Ue=0,pt=S.length;Ue<pt;Ue++){const tt=S[Ue],vt=tt.unit;let Mt=tt.pts;if(V!==null){const Ve=v[Ue-1];Ve.duration=Math.round((Mt-V)/u)}else if(i&&e.segmentCodec==="aac"&&(Mt=x+R),P=Mt,N>0){N+=E;try{re=new Uint8Array(N)}catch(Ve){this.observer.emit(g.ERROR,g.ERROR,{type:Z.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:Ve,bytes:N,reason:`fail allocating audio mdat ${N}`});return}m||(new DataView(re.buffer).setUint32(0,N),re.set(K.types.mdat,4))}else return;re.set(vt,E);const Ge=vt.byteLength;E+=Ge,v.push(so(!0,l,Ge,0)),V=Mt}const Y=v.length;if(!Y)return;const U=v[v.length-1];x=V-R,this.nextAudioTs=x+u*U.duration;const ce=m?new Uint8Array(0):K.moof(e.sequenceNumber++,P/u,Re({},e,{samples:v}));e.samples=[];const He=(P-R)/r,ut=x/r,ct={data1:ce,data2:re,startPTS:He,endPTS:ut,startDTS:He,endDTS:ut,type:"audio",hasAudio:!0,hasVideo:!1,nb:Y};return this.isAudioContiguous=!0,ct}}function Ws(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function lu(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function no(a,e,t,i){const s=a.samples.length;if(!s)return;const n=a.inputTimeScale;for(let o=0;o<s;o++){const u=a.samples[o];u.pts=Ws(u.pts-t.baseTime*n/t.timescale,e*n)/n,u.dts=Ws(u.dts-i.baseTime*n/i.timescale,e*n)/n}const r=a.samples;return a.samples=[],{samples:r}}function ro(a,e,t){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=Ws(o.pts-t.baseTime*s/t.timescale,e*s)/s}a.samples.sort((r,o)=>r.pts-o.pts);const n=a.samples;return a.samples=[],{samples:n}}class uu extends De{constructor(e,t,i,s){super("passthrough-remuxer",s),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}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:r}=this.initData=Oe(e);if(t)Ae(e,t);else{const u=n||r;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}n&&(i=ao(n,Fe.AUDIO,this)),r&&(s=ao(r,Fe.VIDEO,this));const o={};n&&r?o.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:r.supplemental,encrypted:r.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:r?o.video={container:"video/mp4",codec:s,supplemental:r.supplemental,encrypted:r.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,i,s,n,r){var o,u;let{initPTS:l,lastEndTime:c}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};b(c)||(c=this.lastEndTime=n||0);const m=t.samples;if(!m.length)return h;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let y=this.initData;if((o=y)!=null&&o.length||(this.generateInitSegment(m),y=this.initData),!((u=y)!=null&&u.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const S=je(m,y,this),E=y.audio?S[y.audio.id]:null,x=y.video?S[y.video.id]:null,R=Dr(x,1/0),L=Dr(E,1/0),P=Dr(x,0,!0),V=Dr(E,0,!0);let re=n,N=0;const j=E&&(!x||!l&&L<R||l&&l.trackId===y.audio.id),Y=j?E:x;if(Y){const tt=Y.timescale,vt=Y.start-n*tt,Mt=j?y.audio.id:y.video.id;re=Y.start/tt,N=j?V-L:P-R,(r||!l)&&(cu(l,re,n,N)||tt!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${n} ${vt/tt} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${re-n} (${vt}/${tt}) trackId: ${Mt}`),l=null,v.initPTS=vt,v.timescale=tt,v.trackId=Mt)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(v.initPTS=l.baseTime,v.timescale=l.timescale,v.trackId=l.trackId):((!v.timescale||v.trackId===void 0||v.initPTS===void 0)&&(this.warn("Could not set initPTS"),v.initPTS=re,v.timescale=1,v.trackId=-1),this.initPTS=l={baseTime:v.initPTS,timescale:v.timescale,trackId:v.trackId});const U=re-l.baseTime/l.timescale,ce=U+N;N>0?this.lastEndTime=ce:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const He=!!y.audio,ut=!!y.video;let yt="";He&&(yt+="audio"),ut&&(yt+="video");const ct=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),Ue={data1:m,startPTS:U,startDTS:U,endPTS:ce,endDTS:ce,type:yt,hasAudio:He,hasVideo:ut,nb:1,dropped:0,encrypted:ct};h.audio=He&&!ut?Ue:void 0,h.video=ut?Ue:void 0;const pt=x==null?void 0:x.sampleCount;if(pt){const tt=x.keyFrameIndex,vt=tt!==-1;Ue.nb=pt,Ue.dropped=tt===0||this.isVideoContiguous?0:vt?tt:pt,Ue.independent=vt,Ue.firstKeyFrame=tt,vt&&x.keyFrameStart&&(Ue.firstKeyFramePTS=(x.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=vt),this.isVideoContiguous||(this.isVideoContiguous=vt),Ue.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${tt}/${pt} dropped: ${Ue.dropped} start: ${Ue.firstKeyFramePTS||"NA"}`)}return h.initSegment=v,h.id3=no(i,n,l,l),s.samples.length&&(h.text=ro(s,n,l)),h}}function Dr(a,e,t=!1){return(a==null?void 0:a.start)!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function cu(a,e,t,i){if(a===null)return!0;const s=Math.max(i,1),n=e-a.baseTime/a.timescale;return Math.abs(n-t)>s}function ao(a,e,t){const i=a.codec;return i&&i.length>4?i:e===Fe.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?gi(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Sn;try{Sn=self.performance.now.bind(self.performance)}catch(a){Sn=Date.now}const wr=[{demux:Zl,remux:uu},{demux:An,remux:Cr},{demux:Wl,remux:Cr},{demux:zl,remux:Cr}];wr.splice(2,0,{demux:jl,remux:Cr});class oo{constructor(e,t,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=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const n=i.transmuxing;n.executeStart=Sn();let r=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:u}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:c,trackSwitch:h,accurateTimeOffset:m,timeOffset:v,initSegmentChange:y}=s||o,{audioCodec:S,videoCodec:E,defaultInitPts:x,duration:R,initSegmentData:L}=u,P=du(r,t);if(P&&Ss(P.method)){const j=this.getDecrypter(),Y=Qi(P.method);if(j.isSync()){let U=j.softwareDecrypt(r,P.key.buffer,P.iv.buffer,Y);if(i.part>-1){const He=j.flush();U=He&&He.buffer}if(!U)return n.executeEnd=Sn(),ca(i);r=new Uint8Array(U)}else return this.asyncResult=!0,this.decryptionPromise=j.webCryptoDecrypt(r,P.key.buffer,P.iv.buffer,Y).then(U=>{const ce=this.push(U,null,i);return this.decryptionPromise=null,ce}),this.decryptionPromise}const V=this.needsProbing(c,h);if(V){const j=this.configureTransmuxer(r);if(j)return this.logger.warn(`[transmuxer] ${j.message}`),this.observer.emit(g.ERROR,g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:j,reason:j.message}),n.executeEnd=Sn(),ca(i)}(c||h||y||V)&&this.resetInitSegment(L,S,E,R,t),(c||y||V)&&this.resetInitialTimestamp(x),l||this.resetContiguity();const re=this.transmux(r,P,v,m,i);this.asyncResult=ar(re);const N=this.currentTransmuxState;return N.contiguous=!0,N.discontinuity=!1,N.trackSwitch=!1,n.executeEnd=Sn(),re}flush(e){const t=e.transmuxing;t.executeStart=Sn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const r=[],{timeOffset:o}=s;if(i){const h=i.flush();h&&r.push(this.push(h.buffer,null,e))}const{demuxer:u,remuxer:l}=this;if(!u||!l){t.executeEnd=Sn();const h=[ca(e)];return this.asyncResult?Promise.resolve(h):h}const c=u.flush(o);return ar(c)?(this.asyncResult=!0,c.then(h=>(this.flushRemux(r,h,e),r))):(this.flushRemux(r,c,e),this.asyncResult?Promise.resolve(r):r)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:r,textTrack:o}=t,{accurateTimeOffset:u,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===ae.MAIN?"level":"track"} ${i.level}`);const c=this.remuxer.remux(s,n,r,o,l,u,!0,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Sn()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){const{demuxer:r,remuxer:o}=this;!r||!o||(r.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,n){let r;return t&&t.method==="SAMPLE-AES"?r=this.transmuxSampleAes(e,t,i,s,n):r=this.transmuxUnencrypted(e,i,s,n),r}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,o,u,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(r=>({remuxResult:this.remuxer.remux(r.audioTrack,r.videoTrack,r.id3Track,r.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let n;for(let h=0,m=wr.length;h<m;h++){var r;if((r=wr[h].demux)!=null&&r.probe(e,this.logger)){n=wr[h];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,u=this.remuxer,l=n.remux,c=n.demux;(!u||!(u instanceof l))&&(this.remuxer=new l(i,t,s,this.logger)),(!o||!(o instanceof c))&&(this.demuxer=new c(i,t,s,this.logger),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new os(this.config)),e}}function du(a,e){let t=null;return a.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ca=a=>({remuxResult:{},chunkMeta:a});function ar(a){return"then"in a&&a.then instanceof Function}class hu{constructor(e,t,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=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class fu{constructor(e,t,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=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=r}}let lo=0;class uo{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=lo++,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=u=>{const l=u.data,c=this.hls;if(!(!c||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var h;const m=(h=this.workerContext)==null?void 0:h.objectURL;m&&self.URL.revokeObjectURL(m);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=u=>{if(!this.hls)return;const l=new Error(`${u.message} (${u.filename}:${u.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const r=(u,l)=>{l=l||{},l.frag=this.frag||void 0,u===g.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(u,l)};this.observer=new Qr,this.observer.on(g.FRAG_DECRYPTED,r),this.observer.on(g.ERROR,r);const o=Si(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){const u=this.hls.logger;if(n.workerPath||vl()){try{n.workerPath?(u.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=El(n.workerPath)):(u.log(`injecting Web Worker for "${t}"`),this.workerContext=yl());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:t,config:Ce(n)})}catch(c){u.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new oo(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new oo(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=lo++;const t=this.hls.config,i=Si(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),_l(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,r,o,u,l,c){var h,m;l.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:y}=this,S=r?r.start:n.start,E=n.decryptdata,x=this.frag,R=!(x&&n.cc===x.cc),L=!(x&&l.level===x.level),P=x?l.sn-x.sn:-1,V=this.part?l.part-this.part.index:-1,re=P===0&&l.id>1&&l.id===(x==null?void 0:x.stats.chunkCount),N=!L&&(P===1||P===0&&(V===1||re&&V<=0)),j=self.performance.now();(L||P||n.stats.parsing.start===0)&&(n.stats.parsing.start=j),r&&(V||!N)&&(r.stats.parsing.start=j);const Y=!(x&&((h=n.initSegment)==null?void 0:h.url)===((m=x.initSegment)==null?void 0:m.url)),U=new fu(R,N,u,L,S,Y);if(!N||R||Y){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===ae.MAIN?"level":"track"}: ${l.level} id: ${l.id}
discontinuity: ${R}
trackSwitch: ${L}
contiguous: ${N}
accurateTimeOffset: ${u}
timeOffset: ${S}
initSegmentChange: ${Y}`);const ce=new hu(i,s,t,o,c);this.configureTransmuxer(ce)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:E,chunkMeta:l,state:U},e instanceof ArrayBuffer?[e]:[]);else if(y){const ce=y.push(e,E,l,U);ar(ce)?ce.then(He=>{this.handleTransmuxComplete(He)}).catch(He=>{this.transmuxerError(He,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(ce)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);ar(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const co=100;class mu extends _n{constructor(e,t,i){super(e,t,i,"audio-stream-controller",ae.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:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:r}){if(i===ae.MAIN){const o=t.cc,u=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:r},this.log(`InitPTS for cc: ${o} found from main: ${s/n} (${s}/${n}) trackId: ${r}`),this.mainAnchor=t,this.state===ue.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==o?(u.abortRequests(),this.syncWithAnchor(t,u)):this.state===ue.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(s==null?void 0:s.cc)===t.cc)return;const n=(s||e).cc,r=this.getLevelDetails(),o=this.getLoadPosition(),u=pi(r,n,o);u&&(this.log(`Syncing with main frag at ${u.start} cc ${u.cc}`),this.startFragRequested=!1,this.nextLoadPosition=u.start,this.resetLoadingState(),this.state===ue.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=ue.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(co),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=ue.IDLE):this.state=ue.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case ue.IDLE:this.doTickIdle();break;case ue.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=ue.WAITING_INIT_PTS}break}case ue.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case ue.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:n}=e,r=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=ue.FRAG_LOADING;const o=s.flush().buffer,u={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(u),n&&super._handleFragmentLoadComplete(u)}else r&&r.cc!==e.frag.cc&&this.syncWithAnchor(r,e.frag)}else this.state=ue.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:n}=this,r=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||!(i!=null&&i[n]))return;const o=i[n],u=o.details;if(!u||this.waitForLive(o)||this.waitForCdnTuneIn(u)){this.state=ue.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Fe.AUDIO,ae.AUDIO));const c=this.getFwdBufferInfo(l,ae.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,u)){t.trigger(g.BUFFER_EOS,{type:"audio"}),this.state=ue.ENDED;return}const h=c.len,m=t.maxBufferLength,v=u.fragments,y=v[0].start,S=this.getLoadPosition(),E=this.flushing?S:c.end;if(this.switchingTrack&&s){const L=S;u.PTSKnown&&L<y&&(c.end>y||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=y+.05)}if(h>=m&&!this.switchingTrack&&E<v[v.length-1].start)return;let x=this.getNextFragment(E,u);if(x&&this.isLoopLoading(x,E)&&(x=this.getNextFragmentLoopLoading(x,u,c,ae.MAIN,m)),!x){this.bufferFlushed=!0;return}let R=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&R&&Ie(x)&&!x.endList&&(!u.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(R)===Jt.OK&&(this.mainFragLoading=R=null),R&&Ie(R))){if(x.start>R.end){const P=this.fragmentTracker.getFragAtPos(E,ae.MAIN);P&&P.end>R.end&&(R=P,this.mainFragLoading={frag:P,targetBufferTime:null})}if(x.start>R.end)return}this.loadFragment(x,o,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new et(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==ue.STOPPED&&(this.setInterval(co),this.state=ue.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(g.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:n,id:r,groupId:o,track:u}=t;if(!s){this.warn(`Audio tracks reset while loading track ${r} "${u.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==ue.STOPPED&&(this.state=ue.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${u.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const c=s[r];let h=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var m;h=this.alignPlaylists(n,c.details,(m=this.levelLastLoaded)==null?void 0:m.details)}n.alignedSliding||(Ts(n,l),n.alignedSliding||En(n,l),h=n.fragmentStart)}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(g.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:t.groupId}),this.state===ue.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=ue.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{config:r,trackId:o,levels:u}=this;if(!u){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=u[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 h=r.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let m=this.transmuxer;m||(m=this.transmuxer=new uo(this.hls,ae.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const v=this.initPTS[i.cc],y=(t=i.initSegment)==null?void 0:t.data;if(v!==void 0){const E=s?s.index:-1,x=E!==-1,R=new ts(i.level,i.sn,i.stats.chunkCount,n.byteLength,E,x);m.push(n,y,h,"",i,s,c.totalduration,!1,R,v)}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:S}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Ar,complete:!1};S.push(new Uint8Array(n)),this.state!==ue.STOPPED&&(this.state=ue.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ae.MAIN&&Ie(t.frag)&&(this.mainFragLoading=t,this.state===ue.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==ae.AUDIO){!this.audioOnly&&i.type===ae.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(Ie(i)){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(g.AUDIO_TRACK_SWITCHED,z({},n)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=ue.ERROR;return}switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae.AUDIO,t);break;case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ue.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===xe.AUDIO_TRACK&&(this.state=ue.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Fe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Fe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ue.ENDED&&(this.state=ue.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,ae.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:u,part:l,level:c}=o,{details:h}=c,{audio:m,text:v,id3:y,initSegment:S}=n;if(this.fragContextChanged(u)||!h){this.fragmentTracker.removeFragment(u);return}if(this.state=ue.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),S!=null&&S.tracks){const E=u.initSegment||u;if(this.unhandledEncryptionError(S,u))return;this._bufferInitSegment(c,S.tracks,E,r),s.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:S.tracks})}if(m){const{startPTS:E,endPTS:x,startDTS:R,endDTS:L}=m;l&&(l.elementaryStreams[Fe.AUDIO]={startPTS:E,endPTS:x,startDTS:R,endDTS:L}),u.setElementaryStreamInfo(Fe.AUDIO,E,x,R,L),this.bufferFragmentData(m,u,l,r)}if(y!=null&&(t=y.samples)!=null&&t.length){const E=Re({id:i,frag:u,details:h},y);s.trigger(g.FRAG_PARSING_METADATA,E)}if(v){const E=Re({id:i,frag:u,details:h},v);s.trigger(g.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,i,s){if(this.state!==ue.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=ae.AUDIO;const r=e.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(g.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const u={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(g.BUFFER_APPENDING,u)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===Jt.NOT_LOADED||s===Jt.PARTIAL){var n;if(!Ie(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ue.WAITING_INIT_PTS;const r=this.mainDetails;r&&r.fragmentStart!==t.details.fragmentStart&&En(t.details,r)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o}=this.bufferedTrack;le({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o},e,Ke)||(Pt(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(g.AUDIO_TRACK_SWITCHED,z({},e))}}class da extends De{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t==null?void 0:t.renditionReports;if(s){let n=-1;for(let r=0;r<s.length;r++){const o=s[r];let u;try{u=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),u=o.URI||""}if(u===e){n=r;break}else u===e.substring(0,u.length)&&(n=r)}if(n!==-1){const r=s[n],o=parseInt(r["LAST-MSN"])||t.lastPartSn;let u=parseInt(r["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const c=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&c>t.partTarget&&(u+=1)}const l=i&&Se(i);return new ve(o,u>=0?u:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:n}=t,r=self.performance.now(),o=n.loading.first?Math.max(0,r-n.loading.first):0;s.advancedDateTime=Date.now()-o;const u=this.hls.config.timelineOffset;if(u!==s.appliedTimelineOffset){const c=Math.max(u||0,0);s.appliedTimelineOffset=c,s.fragments.forEach(h=>{h.setStart(h.playlistOffset+c)})}if(s.live||i!=null&&i.live){const c="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){Qn(i,s,this);const R=s.playlistParsingError;if(R){this.warn(R);const L=this.hls;if(!L.config.ignorePlaylistParsingErrors){var l;const{networkDetails:P}=t;L.trigger(g.ERROR,{type:Z.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:R,reason:R.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:P,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const h=this.hls.mainForwardBufferInfo,m=h?h.end-h.len:0,v=(s.edge-m)*1e3,y=yr(s,v);if(s.requestScheduled+y<r?s.requestScheduled=r:s.requestScheduled+=y,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let S,E,x;if(s.canBlockReload&&s.endSN&&s.advanced){const R=this.hls.config.lowLatencyMode,L=s.lastPartSn,P=s.endSN,V=s.lastPartIndex,re=V!==-1,N=L===P;re?N?(E=P+1,x=R?0:V):(E=L,x=R?V+1:s.maxPartIndex):E=P+1;const j=s.age,Y=j+s.ageHeader;let U=Math.min(Y-s.partTarget,s.targetduration*1.5);if(U>0){if(Y>s.targetduration*3)this.log(`Playlist last advanced ${j.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,x=void 0;else if(i!=null&&i.tuneInGoal&&Y-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${U} with playlist age: ${s.age}`),U=0;else{const ce=Math.floor(U/s.targetduration);if(E+=ce,x!==void 0){const He=Math.round(U%s.targetduration/s.partTarget);x+=He}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${j.toFixed(2)}s goal: ${U} skip sn ${ce} to part ${x}`)}s.tuneInGoal=U}if(S=this.getDeliveryDirectives(s,t.deliveryDirectives,E,x),R||!N){s.requestScheduled=r,this.loadingPlaylist(c,S);return}}else(s.canBlockReload||s.canSkipUntil)&&(S=this.getDeliveryDirectives(s,t.deliveryDirectives,E,x));S&&E!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(y-o*2,y/2)),this.scheduleLoading(c,S,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const n=self.performance.now(),r=s.requestScheduled;if(n>=r){this.loadingPlaylist(e,t);return}const o=r-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let n=Se(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=$e.No),new ve(i,s,n)}checkRetry(e){const t=e.details,i=Wt(e),s=e.errorAction,{action:n,retryCount:r=0,retryConfig:o}=s||{},u=!!s&&!!o&&(n===li.RetryRequest||!s.resolved&&n===li.SendAlternateToPenaltyBox);if(u){var l;if(r>=o.maxNumRetry)return!1;if(i&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const c=Ei(o,r);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" in ${c}ms`)}e.levelRetry=!0,s.resolved=!0}return u}}function ho(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!or(a[t].attrs,e[t].attrs))return!1;return!0}function or(a,e,t){const i=a["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>a[s]!==e[s])}function ha(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class gu extends da{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,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=t.details,this.log(`Audio track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.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(m=>!i||i.indexOf(m.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(m=>m.default)&&(this.selectDefaultTrack=!1),o.forEach((m,v)=>{m.id=v});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.audioPreference;if(!n&&u){const m=q(u,o,Ke);if(m>-1)n=o[m];else{const v=q(u,this.tracks);n=this.tracks[v]}}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(g.AUDIO_TRACKS_UPDATED,c);const h=this.trackId;if(l!==-1&&h===-1)this.setAudioTrack(l);else if(o.length&&h===-1){var r;const m=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(m.message),this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(e,t){t.fatal||!t.context||t.context.type===xe.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&le(e,s,Ke))return s;const n=q(e,this.tracksInGroup,Ke);if(n>-1){const r=this.tracksInGroup[n];return this.setAudioTrack(n),r}else if(s){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);const o=Ut(e,t.levels,i,r,Ke);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const r=q(e,i);if(r>-1)return i[r]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===i&&n||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(g.AUDIO_TRACK_SWITCHING,z({},s)),n))return;const r=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(r)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||le(e,s,Ke)))return i}if(e){const{name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:u}=e;for(let l=0;l<t.length;l++){const c=t[l];if(le({name:i,lang:s,assocLang:n,characteristics:r,audioCodec:o,channels:u},c,Ke))return l}for(let l=0;l<t.length;l++){const c=t[l];if(or(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const c=t[l];if(or(e.attrs,c.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Pt(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),r=e.details,o=r==null?void 0:r.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||0:""):""} ${n}`),this.hls.trigger(g.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}}class pu{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;const r=(i=this.tracks[e])==null?void 0:i.buffer;r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],s=i==null?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const fo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,mo="HlsJsTrackRemovedError";class vu extends Error{constructor(e){super(e),this.name=mo}}class yu extends De{constructor(e,t){super("buffer-controller",e.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(g.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=e,this.fragmentTracker=t,this.appendSource=Et(dt(e.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:e}=this;e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_APPENDING,this.onBufferAppending,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.BUFFER_EOS,this.onBufferEos,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.FRAG_PARSED,this.onFragParsed,this),e.on(g.FRAG_CHANGED,this.onFragChanged,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_APPENDING,this.onBufferAppending,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_EOS,this.onBufferEos,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.FRAG_PARSED,this.onFragParsed,this),e.off(g.FRAG_CHANGED,this.onFragChanged,this),e.off(g.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)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===t?Re(i,s.tracks):this.sourceBuffers.forEach(n=>{const[r]=n;r&&(i[r]=Re({},this.tracks[r]),this.removeBuffer(r)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.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(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=dt(this.appendSource);if(s){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.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 u=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||u&&r instanceof u,go(i),Eu(i,o),i.load()}catch(u){i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,r=n?n.length:0,o=()=>{Promise.resolve().then(()=>{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})
required tracks: ${Ce(i,(u,l)=>u==="initSegment"?void 0:l)};
transfer tracks: ${Ce(s,(u,l)=>u==="initSegment"?void 0:l)}}`),!Gt(s,i)){t.mediaSource=null,t.tracks=void 0;const u=e.currentTime,l=this.details,c=Math.max(u,(l==null?void 0:l.fragments[0].start)||0);if(c-u>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${u}`),this.onMediaDetaching(g.MEDIA_DETACHING,{}),this.onMediaAttaching(g.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(u=>{const l=u,c=s[l];if(c){const h=c.buffer;if(h){const m=this.fragmentTracker,v=c.id;if(m.hasFragments(v)||m.hasParts(v)){const E=bt.getBuffered(h);m.detectEvictedFragments(l,E,v,null,!0)}const y=fa(l),S=[l,h];this.sourceBuffers[y]=S,h.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 e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.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 u=n.sourceBuffers;for(let l=u.length;l--;)o&&u[l].abort(),n.removeSourceBuffer(u[l]);o&&n.endOfStream()}catch(u){this.warn(`onMediaDetaching: ${u.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&&go(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(g.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fa(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pu(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),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 u,l;const c=t[o],{id:h,codec:m,levelCodec:v,container:y,metadata:S,supplemental:E}=c;let x=i[o];const R=(u=this.transferData)==null||(u=u.tracks)==null?void 0:u[o],L=R!=null&&R.buffer?R:x,P=(L==null?void 0:L.pendingCodec)||(L==null?void 0:L.codec),V=L==null?void 0:L.levelCodec;x||(x=i[o]={buffer:void 0,listeners:[],codec:m,supplemental:E,container:y,levelCodec:v,metadata:S,id:h});const re=yi(P,V),N=re==null?void 0:re.replace(fo,"$1");let j=yi(m,v);const Y=(l=j)==null?void 0:l.replace(fo,"$1");j&&re&&N!==Y&&(o.slice(0,5)==="audio"&&(j=gi(j,this.appendSource)),this.log(`switching codec ${P} to ${j}`),j!==(x.pendingCodec||x.codec)&&(x.pendingCodec=j),x.container=y,this.appendChangeType(o,y,j))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{const r=this.tracks[e];if(r){const o=r.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,ae.MAIN))==null?void 0:t.gap)===!0)return;const r={label:"block-audio",execute:()=>{var o;const u=this.tracks.video;(this.lastVideoAppendEnd>s||u!=null&&u.buffer&&bt.isBuffered(u.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,ae.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:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:n,parent:r,frag:o,part:u,chunkMeta:l,offset:c}=t,h=l.buffering[n],{sn:m,cc:v}=o,y=self.performance.now();h.start=y;const S=o.stats.buffering,E=u?u.stats.buffering:null;S.start===0&&(S.start=y),E&&E.start===0&&(E.start=y);const x=i.audio;let R=!1;n==="audio"&&(x==null?void 0:x.container)==="audio/mpeg"&&(R=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const L=i.video,P=L==null?void 0:L.buffer;if(P&&m!=="initSegment"){const N=u||o,j=this.blockedAudioAppend;if(n==="audio"&&r!=="main"&&!this.blockedAudioAppend&&!(L.ending||L.ended)){const U=N.start+N.duration*.05,ce=P.buffered,He=this.currentOp("video");!ce.length&&!He?this.blockAudio(N):!He&&!bt.isBuffered(P,U)&&this.lastVideoAppendEnd<U&&this.blockAudio(N)}else if(n==="video"){const Y=N.end;if(j){const U=j.frag.start;(Y>U||Y<this.lastVideoAppendEnd||bt.isBuffered(P,U))&&this.unblockAudio()}this.lastVideoAppendEnd=Y}}const V=(u||o).start,re={label:`append-${n}`,execute:()=>{var N;h.executeStart=self.performance.now();const j=(N=this.tracks[n])==null?void 0:N.buffer;j&&(R?this.updateTimestampOffset(j,V,.1,n,m,v):c!==void 0&&b(c)&&this.updateTimestampOffset(j,c,1e-6,n,m,v)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const N=self.performance.now();h.executeEnd=h.end=N,S.first===0&&(S.first=N),E&&E.first===0&&(E.first=N);const j={};this.sourceBuffers.forEach(([Y,U])=>{Y&&(j[Y]=bt.getBuffered(U))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(g.BUFFER_APPENDED,{type:n,frag:o,part:u,chunkMeta:l,parent:o.type,timeRanges:j})},onError:N=>{var j;const Y={type:Z.MEDIA_ERROR,parent:o.type,details:A.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:u,chunkMeta:l,error:N,err:N,fatal:!1},U=(j=this.media)==null?void 0:j.error;if(N.code===DOMException.QUOTA_EXCEEDED_ERR||N.name=="QuotaExceededError"||"quota"in N)Y.details=A.BUFFER_FULL_ERROR;else if(N.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!U)Y.errorAction=$i(!0);else if(N.name===mo&&this.sourceBufferCount===0)Y.errorAction=$i(!0);else{const ce=++this.appendErrors[n];this.warn(`Failed ${ce}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${U||"no media error"})`),(ce>=this.hls.config.appendErrorMaxRetry||U)&&(Y.fatal=!0)}this.hls.trigger(g.ERROR,Y)}};this.append(re,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(g.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:n}=t;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([r])=>{r&&this.append(this.getFlushOp(r,s,n),r)})}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],r=s?s.elementaryStreams:i.elementaryStreams;r[Fe.AUDIOVIDEO]?n.push("audiovideo"):(r[Fe.AUDIO]&&n.push("audio"),r[Fe.VIDEO]&&n.push("video"));const o=()=>{const u=self.performance.now();i.stats.buffering.end=u,s&&(s.stats.buffering.end=u);const l=s?s.stats:i.stats;this.hls.trigger(g.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(u=>{this.warn(`Fragment buffered callback ${u}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([r])=>{if(r){const o=this.tracks[r];(!t.type||t.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(g.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(g.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===A.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;b(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const s=e.config,n=i.currentTime,r=t.levelTargetDuration,o=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(b(o)&&o>=0){const l=Math.max(o,r),c=Math.floor(n/r)*r-l;this.flushBackBuffer(n,r,c)}const u=s.frontBufferFlushThreshold;if(b(u)&&u>0){const l=Math.max(s.maxBufferLength,u),c=Math.max(l,r),h=Math.floor(n/r)*r+c;this.flushFrontBuffer(n,r,h)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const o=bt.getBuffered(n);if(o.length>0&&i>o.start(0)){var r;this.hls.trigger(g.BACK_BUFFER_REACHED,{bufferEnd:i});const u=this.tracks[s];if((r=this.details)!=null&&r.live)this.hls.trigger(g.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(u!=null&&u.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const r=bt.getBuffered(n),o=r.length;if(o<2)return;const u=r.start(o-1),l=r.end(o-1);if(i>u||e>=u&&e<=l)return;this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),c=Math.max(l,s);return{duration:1/0,start:l,end:c}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return b(n)?{duration:n}:null;const r=this.media.duration,o=b(i.duration)?i.duration:0;return s>o&&s>r||!b(r)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(b(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ce(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 e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(g.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const r=n,o=e[r];if(this.isPending(o)){const u=this.getTrackCodec(o,r),l=`${o.container};codecs=${u}`;o.codec=u,this.log(`creating sourceBuffer(${l})${this.currentOp(r)?" Queued":""} ${Ce(o)}`);try{const c=i.addSourceBuffer(l),h=fa(r),m=[r,c];t[h]=m,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(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l,parent:o.id});return}this.trackSourceBuffer(r,o)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&cs(i,"video")&&(s=_i(s,i));const n=yi(s,e.levelCodec);return n?t.slice(0,5)==="audio"?gi(n,this.appendSource):n:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,r)=>{const o=r.removedRanges;o!=null&&o.length&&this.hls.trigger(g.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const n=this.currentOp(e);n&&n.onError(s)}updateTimestampOffset(e,t,i,s,n,r){const o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${r})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:n}=this,r=this.tracks[e],o=r==null?void 0:r.buffer;if(!s||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const u=b(s.duration)?s.duration:1/0,l=b(n.duration)?n.duration:1/0,c=Math.max(0,t),h=Math.min(i,u,l);h>c&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${c},${h}] from the ${e} SourceBuffer`),o.remove(c,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=i==null?void 0:i.buffer;if(!s)throw new vu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(r=>this.appendBlocker(r));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(r=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const n=s.buffer;if(!n)return;const r=i.bind(this,e);s.listeners.push({event:t,listener:r}),n.addEventListener(t,r)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}}function go(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Eu(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function fa(a){return a==="audio"?1:0}class ma{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&b(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.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 e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,ma.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 e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,u)=>u?o.width!==u.width||o.height!==u.height:!0;let n=e.length-1;const r=Math.max(t,i);for(let o=0;o<e.length;o+=1){const u=e[o];if((u.width>=r||u.height>=r)&&s(u,e[o+1])){n=o;break}}return n}}const Fs={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},_u={HLS:"h"};class un{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof un?i:new un(i))),this.value=e,this.params=t}}const Su="Dict";function Tu(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 xu(a,e,t,i){return new Error(`failed to ${a} "${Tu(e)}" as ${t}`,{cause:i})}function cn(a,e,t){return xu("serialize",a,e,t)}class po{constructor(e){this.description=e}}const vo="Bare Item",Au="Boolean";function bu(a){if(typeof a!="boolean")throw cn(a,Au);return a?"?1":"?0"}function Lu(a){return btoa(String.fromCharCode(...a))}const Ru="Byte Sequence";function Iu(a){if(ArrayBuffer.isView(a)===!1)throw cn(a,Ru);return`:${Lu(a)}:`}const Cu="Integer";function Du(a){return a<-999999999999999||999999999999999<a}function yo(a){if(Du(a))throw cn(a,Cu);return a.toString()}function wu(a){return`@${yo(a.getTime()/1e3)}`}function Eo(a,e){if(a<0)return-Eo(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const s=Math.floor(a*t);return(s%2===0?s:s+1)/t}else return Math.round(a*t)/t}const ku="Decimal";function Pu(a){const e=Eo(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw cn(a,ku);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Ou="String",Fu=/[\x00-\x1f\x7f]+/;function Mu(a){if(Fu.test(a))throw cn(a,Ou);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Bu(a){return a.description||a.toString().slice(7,-1)}const Nu="Token";function _o(a){const e=Bu(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw cn(e,Nu);return e}function ga(a){switch(typeof a){case"number":if(!b(a))throw cn(a,vo);return Number.isInteger(a)?yo(a):Pu(a);case"string":return Mu(a);case"symbol":return _o(a);case"boolean":return bu(a);case"object":if(a instanceof Date)return wu(a);if(a instanceof Uint8Array)return Iu(a);if(a instanceof po)return _o(a);default:throw cn(a,vo)}}const Uu="Key";function pa(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw cn(a,Uu);return a}function va(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${pa(e)}`:`;${pa(e)}=${ga(t)}`).join("")}function So(a){return a instanceof un?`${ga(a.value)}${va(a.params)}`:ga(a)}function $u(a){return`(${a.value.map(So).join(" ")})${va(a.params)}`}function Gu(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw cn(a,Su);const t=a instanceof Map?a.entries():Object.entries(a),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof un||(n=new un(n));let r=pa(s);return n.value===!0?r+=va(n.params):(r+="=",Array.isArray(n.value)?r+=$u(n):r+=So(n)),r}).join(`,${i}`)}function To(a,e){return Gu(a,e)}const dn="CMCD-Object",ns="CMCD-Request",Dn="CMCD-Session",Ln="CMCD-Status",Vu={br:dn,ab:dn,d:dn,ot:dn,tb:dn,tpb:dn,lb:dn,tab:dn,lab:dn,url:dn,pb:ns,bl:ns,tbl:ns,dl:ns,ltc:ns,mtp:ns,nor:ns,nrr:ns,rc:ns,sn:ns,sta:ns,su:ns,ttfb:ns,ttfbb:ns,ttlb:ns,cmsdd:ns,cmsds:ns,smrt:ns,df:ns,cs:ns,ts:ns,cid:Dn,pr:Dn,sf:Dn,sid:Dn,st:Dn,v:Dn,msd:Dn,bs:Ln,bsd:Ln,cdn:Ln,rtp:Ln,bg:Ln,pt:Ln,ec:Ln,e:Ln},Ku={REQUEST:ns};function Hu(a){return Object.keys(a).reduce((e,t)=>{var i;return(i=a[t])===null||i===void 0||i.forEach(s=>e[s]=t),e},{})}function Wu(a,e){const t={};if(!a)return t;const i=Object.keys(a),s=e?Hu(e):{};return i.reduce((n,r)=>{var o;const u=Vu[r]||s[r]||Ku.REQUEST,l=(o=n[u])!==null&&o!==void 0?o:n[u]={};return l[r]=a[r],n},t)}function ju(a){return["ot","sf","st","e","sta"].includes(a)}function zu(a){return typeof a=="number"?b(a):a!=null&&a!==""&&a!==!1}const xo="event";function Yu(a,e){const t=new URL(a),i=new URL(e);if(t.origin!==i.origin)return a;const s=t.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("/")+t.search+t.hash}const kr=a=>Math.round(a),ya=(a,e)=>Array.isArray(a)?a.map(t=>ya(t,e)):a instanceof un&&typeof a.value=="string"?new un(ya(a.value,e),a.params):(e.baseUrl&&(a=Yu(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Pr=a=>kr(a/100)*100,Zu={br:kr,d:kr,bl:Pr,dl:Pr,mtp:Pr,nor:(a,e)=>{let t=a;return e.version>=2&&(a instanceof un&&typeof a.value=="string"?t=new un([a]):typeof a=="string"&&(t=[a])),ya(t,e)},rtp:Pr,tb:kr},Ao="request",bo="response",Ea=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],qu=["e"],Xu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Or(a){return Xu.test(a)}function Qu(a){return Ea.includes(a)||qu.includes(a)||Or(a)}const Lo=["d","dl","nor","ot","rtp","su"];function Ju(a){return Ea.includes(a)||Lo.includes(a)||Or(a)}const ec=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function tc(a){return Ea.includes(a)||Lo.includes(a)||ec.includes(a)||Or(a)}const ic=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sc(a){return ic.includes(a)||Or(a)}const nc={[bo]:tc,[xo]:Qu,[Ao]:Ju};function Ro(a,e={}){const t={};if(a==null||typeof a!="object")return t;const i=e.version||a.v||1,s=e.reportingMode||Ao,n=i===1?sc:nc[s];let r=Object.keys(a).filter(n);const o=e.filter;typeof o=="function"&&(r=r.filter(o));const u=s===bo||s===xo;u&&!r.includes("ts")&&r.push("ts"),i>1&&!r.includes("v")&&r.push("v");const l=Re({},Zu,e.formatters),c={version:i,reportingMode:s,baseUrl:e.baseUrl};return r.sort().forEach(h=>{let m=a[h];const v=l[h];if(typeof v=="function"&&(m=v(m,c)),h==="v"){if(i===1)return;m=i}h=="pr"&&m===1||(u&&h==="ts"&&!b(m)&&(m=Date.now()),zu(m)&&(ju(h)&&typeof m=="string"&&(m=new po(m)),t[h]=m))}),t}function rc(a,e={}){const t={};if(!a)return t;const i=Ro(a,e),s=Wu(i,e==null?void 0:e.customHeaderMap);return Object.entries(s).reduce((n,[r,o])=>{const u=To(o,{whitespace:!1});return u&&(n[r]=u),n},t)}function ac(a,e,t){return Re(a,rc(e,t))}const oc="CMCD";function lc(a,e={}){return a?To(Ro(a,e),{whitespace:!1}):""}function uc(a,e={}){if(!a)return"";const t=lc(a,e);return encodeURIComponent(t)}function cc(a,e={}){if(!a)return"";const t=uc(a,e);return`${oc}=${t}`}const Io=/CMCD=[^&#]+/;function dc(a,e,t){const i=cc(e,t);if(!i)return a;if(Io.test(a))return a.replace(Io,i);const s=a.includes("?")?"&":"?";return`${a}${s}${i}`}class hc{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:Fs.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],u=this.getObjectType(n),l={d:(r||n).duration*1e3,ot:u};(u===Fs.VIDEO||u===Fs.AUDIO||u==Fs.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(u)/1e3,l.bl=this.getBufferLength(u));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=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHED,this.onMediaDetached,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHED,this.onMediaDetached,this),e.off(g.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(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:_u.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Re(t,this.createData());const i=t.ot===Fs.INIT||t.ot===Fs.VIDEO||t.ot===Fs.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((r,o)=>(s.includes(o)&&(r[o]=t[o]),r),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),ac(e.headers,t,n)):e.url=dc(e.url,t,n)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:r}=s;for(let o=n.length-1;o>=0;o--){const u=n[o];if(u.index===i&&u.fragment.sn===r)return n[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Fs.TIMED_TEXT;if(e.sn==="initSegment")return Fs.INIT;if(t==="audio")return Fs.AUDIO;if(t==="main")return this.hls.audioTracks.length?Fs.VIDEO:Fs.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===Fs.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>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Fs.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:bt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||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){t(n),this.loader.load(n,r,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||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){t(n),this.loader.load(n,r,o)}}}}const fc=3e5;class mc extends De{constructor(e){super("content-steering",e.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=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===li.SendAlternateToPenaltyBox&&i.flags===ui.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:o,pathwayId:u,type:l}=t.context;o&&s?r=this.getPathwayForGroupId(o,l,r):u&&(r=u)}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),t.details===A.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${s&&s.length} priorities: ${Ce(n)} penalized: ${Ce(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>fc&&delete i[n]});for(let n=0;n<e.length;n++){const r=e[n];if(r in i)continue;if(r===this.pathwayId)return;const o=this.hls.nextLoadLevel,u=this.hls.levels[o];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Sr(t),this.hls.trigger(g.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];u&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==u.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==u.bitrate&&this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===xe.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===xe.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(n=>{const{ID:r,"BASE-ID":o,"URI-REPLACEMENT":u}=n;if(t.some(c=>c.pathwayId===r))return;const l=this.getLevelsForPathway(o).map(c=>{const h=new ai(c.attrs);h["PATHWAY-ID"]=r;const m=h.AUDIO&&`${h.AUDIO}_clone_${r}`,v=h.SUBTITLES&&`${h.SUBTITLES}_clone_${r}`;m&&(i[h.AUDIO]=m,h.AUDIO=m),v&&(s[h.SUBTITLES]=v,h.SUBTITLES=v);const y=Do(c.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",u),S=new et({attrs:h,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:y,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let E=1;E<c.audioGroups.length;E++)S.addGroupId("audio",`${c.audioGroups[E]}_clone_${r}`);if(c.subtitleGroups)for(let E=1;E<c.subtitleGroups.length;E++)S.addGroupId("text",`${c.subtitleGroups[E]}_clone_${r}`);return S});t.push(...l),Co(this.audioTracks,i,u,r),Co(this.subtitleTracks,s,u,r)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch(c){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}const n={responseType:"json",url:s.href},r=t.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,h,m,v)=>{this.log(`Loaded steering manifest: "${s}"`);const y=c.data;if((y==null?void 0:y.VERSION)!==1){this.log(`Steering VERSION ${y.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=y.TTL;const{"RELOAD-URI":S,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":x}=y;if(S)try{this.uri=new self.URL(S,s).href}catch(L){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${S}`);return}this.scheduleRefresh(this.uri||m.url),E&&this.clonePathways(E);const R={steeringManifest:y,url:s.toString()};this.hls.trigger(g.STEERING_MANIFEST_LOADED,R),x&&this.updatePathwayPriority(x)},onError:(c,h,m,v)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${h.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let y=this.timeToLoad*1e3;if(c.code===429){const S=this.loader;if(typeof(S==null?void 0:S.getResponseHeader)=="function"){const E=S.getResponseHeader("Retry-After");E&&(y=parseFloat(E)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,y)},onTimeout:(c,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,u,l)}scheduleRefresh(e,t=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(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Co(a,e,t,i){a&&Object.keys(e).forEach(s=>{const n=a.filter(r=>r.groupId===s).map(r=>{const o=Re({},r);return o.details=void 0,o.attrs=new ai(o.attrs),o.url=o.attrs.URI=Do(r.url,r.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});a.push(...n)})}function Do(a,e,t,i){const{HOST:s,PARAMS:n,[t]:r}=i;let o;e&&(o=r==null?void 0:r[e],o&&(a=o));const u=new self.URL(a);return s&&!o&&(u.host=s),n&&Object.keys(n).sort().forEach(l=>{l&&u.searchParams.set(l,n[l])}),u.href}class Hn extends De{constructor(e){super("eme",e.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=Hn.CDMCleanupPromise?[Hn.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),s!==null){if(!this.keyFormatPromise){let r=Object.keys(this.keySystemAccessPromises);r.length||(r=Tt(this.config));const o=r.map(rt).filter(u=>!!u);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(r=>{const o=on(r);if(i!=="sinf"||o!==ki.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let u;try{const v=St(new Uint8Array(s)),y=wi(JSON.parse(v).sinf),S=Je(y);if(!S)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");u=new Uint8Array(S.subarray(8,24))}catch(v){this.warn(`${n} Failed to parse sinf: ${v}`);return}const l=te(u),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let m=c[l];for(let v=0;v<h.length;v++){const y=h[v],S=y.decryptdata;if(!S.keyId)continue;const E=te(S.keyId);if(l===E||S.uri.replace(/-/g,"").indexOf(l)!==-1){if(m=c[E],!m)continue;if(S.pssh)break;delete c[E],S.pssh=new Uint8Array(s),S.keyId=u,m=c[l]=m.then(()=>this.generateRequestWithPreferredKeySession(y,i,s,"encrypted-event-key-match")),m.catch(x=>this.handleError(x));break}}m||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(r=>this.handleError(r))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(g.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(g.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t==null?void 0:t[e];if(s)return s.licenseUrl;if(e===ki.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t==null?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(r,o,u)=>!!r&&u.indexOf(r)===o,s=t.map(r=>r.audioCodec).filter(i),n=t.map(r=>r.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((r,o)=>{const u=l=>{const c=l.shift();this.getMediaKeysPromise(c,s,n).then(h=>r({keySystem:c,mediaKeys:h})).catch(h=>{l.length?u(l):h instanceof en?o(h):o(new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};u(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Li===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;const n=Yi(e,t,i,this.config.drmSystemOptions||{});let r=this.keySystemAccessPromises[e],o=(s=r)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ce(n)}`),o=this.requestMediaKeySystemAccess(e,n);const u=r=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const h=u.mediaKeys=l.createMediaKeys().then(m=>(this.log(`Media-keys created for "${e}"`),u.hasMediaKeys=!0,c.then(v=>v?this.setMediaKeysServerCertificate(m,e,v):m)));return h.catch(m=>{this.error(`Failed to create media-keys for "${e}"}: ${m}`)}),h})}return o.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${te(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return te(e.keyId)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${te(e.decryptdata.keyId||[])}
} (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>rt(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:s})=>{const n=rt(s);n?t(n):i(new Error(`Unable to find format for key-system "${s}"`))}).catch(i)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Tt(this.config),i=e.map(on).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=this.bannedKeyIds[i];if(s){const o=wo(s,t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const r=this.keyIdToKeySessionPromise[i];if(!r){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:u,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(u,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:u,mediaKeys:l,decryptdata:t}))))).then(u=>{const l="cenc",c=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(u,l,c,"playlist-key")});return o.catch(u=>this.handleError(u,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){this.hls&&(this.error(e.message),e instanceof en?(t&&(e.data.frag=t),this.hls.trigger(g.ERROR,e.data)):this.hls.trigger(g.ERROR,{type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=on(e.keyFormat),n=s?[s]:Tt(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Tt(this.config)),e.length===0)throw new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);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(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n;const r=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(r)try{const m=r.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=m.initData?m.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const o=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${o} (init data type: ${t} length: ${i.byteLength})`);const u=new Qr,l=e._onmessage=m=>{const v=e.mediaKeysSession;if(!v){u.emit("error",new Error("invalid state"));return}const{messageType:y,message:S}=m;this.log(`"${y}" message event for session "${v.sessionId}" message size: ${S.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,S).catch(E=>{u.eventNames().length?u.emit("error",E):this.handleError(E)}):y==="license-release"?e.keySystem===ki.FAIRPLAY&&(this.updateKeySession(e,is("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},c=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}const y=e.keyStatus;this.onKeyStatusChange(e);const S=e.keyStatus;S!==y&&(u.emit("keyStatus",S,e),S==="expired"&&(this.log(`${e.keySystem} expired for key ${o}`),this.renewKeySession(e)))};ms(e.mediaKeysSession,"message",l),ms(e.mediaKeysSession,"keystatuseschange",c);const h=new Promise((m,v)=>{u.on("error",v),u.on("keyStatus",(y,{decryptdata:S})=>{y.startsWith("usable")?m():y==="internal-error"||y==="output-restricted"?v(wo(y,S)):y==="expired"?v(new Error(`key expired while generating request (keyId: ${o})`)):this.warn(`unhandled key status change "${y}" (keyId: ${o})`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o}`)}).catch(m=>{throw new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>h).catch(m=>{throw u.removeAllListeners(),this.removeSession(e),m}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){const t=te(new Uint8Array(e.decryptdata.keyId||[]));e.mediaKeysSession.keyStatuses.forEach((i,s)=>{if(typeof s=="string"&&typeof i=="object"){const o=s;s=i,i=o}const n=te("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s));i==="internal-error"&&(this.bannedKeyIds[n]=i);const r=n===t;this.log(`${r?"":"un"}matched key status change "${i}" for keyStatuses keyId: ${n} session keyId: ${t} uri: ${e.decryptdata.uri}`),r&&(e.keyStatus=i)})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,o)=>{const u={responseType:"arraybuffer",url:n},l=t.certLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,v,y,S)=>{r(m.data)},onError:(m,v,y,S)=>{o(new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:z({url:u.url,data:void 0},m)},`"${e}" certificate request failed (${n}). Status: ${m.code} (${m.text})`))},onTimeout:(m,v,y)=>{o(new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:u.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(m,v,y)=>{o(new Error("aborted"))}};s.load(u,c,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(r=>{n(new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:r,fatal:!0},r.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:s,fatal:!1},s.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,m=n.length;h<m;h++){var r,o;c=n[h];const v=(r=c.querySelector("name"))==null?void 0:r.textContent,y=(o=c.querySelector("value"))==null?void 0:o.textContent;v&&y&&e.setRequestHeader(v,y)}}const u=s.querySelector("Challenge"),l=u==null?void 0:u.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return is(atob(l))}setupLicenseXHR(e,t,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,e,t,i,s)}).catch(r=>{if(!i.decryptdata)throw r;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(r=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const r=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${r}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let u=o.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const l=this.config.licenseResponseCallback;if(l)try{u=l.call(this.hls,o,r,e)}catch(c){this.error(c)}s(u)}else{const u=i.errorRetry,l=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new en({type:Z.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,r,e,t).then(({xhr:u,licenseChallenge:l})=>{e.keySystem==ki.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(u,l)),u.send(l)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,ms(i,"encrypted",this.onMediaEncrypted),ms(i,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(xs(e,"encrypted",this.onMediaEncrypted),xs(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Qs.clearKeyUriToKeyIdMap();const s=i.length;Hn.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat(t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.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,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.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(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${te((s==null?void 0:s.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{drmSystemOptions:r}=this.config;return(pn(r)?new Promise((u,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(u).catch(l)}):Promise.resolve()).catch(u=>{this.log(`Could not remove session: ${u}`),this.hls&&this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${u}`)})}).then(()=>t.close()).catch(u=>{this.log(`Could not close session: ${u}`),this.hls&&this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${u}`)})})}}}Hn.CDMCleanupPromise=void 0;class en extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function wo(a,e){const t=a==="output-restricted",i=t?A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:A.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new en({type:Z.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class gc{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(g.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(g.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.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(e,t,i){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,r=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,u=1e3*r/n,l=this.hls;if(l.trigger(g.FPS_DROP,{currentDropped:r,currentDecoded:o,totalDroppedFrames:i}),u>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(g.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:l.currentLevel}),l.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function ko(a,e){let t;try{t=new Event("addtrack")}catch(i){t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Po(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){J.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,a.addCue(s)}catch(s){J.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(a.mode=t)}function Wn(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let i=a.cues.length;i--;)e&&a.cues[i].removeEventListener("enter",e),a.removeCue(a.cues[i]);t==="disabled"&&(a.mode=t)}function _a(a,e,t,i){const s=a.mode;if(s==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const n=vc(a.cues,e,t);for(let r=0;r<n.length;r++)(!i||i(n[r]))&&a.removeCue(n[r])}s==="disabled"&&(a.mode=s)}function pc(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let i=0,s=t,n;for(;i<=s;)if(n=Math.floor((s+i)/2),e<a[n].startTime)s=n-1;else if(e>a[n].startTime&&i<t)i=n+1;else return n;return a[i].startTime-e<e-a[s].startTime?i:s}function vc(a,e,t){const i=[],s=pc(a,e);if(s>-1)for(let n=s,r=a.length;n<r;n++){const o=a[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Fr(a){const e=[];for(let t=0;t<a.length;t++){const i=a[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(a[t])}return e}class yc extends da{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.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 t=null;const i=Fr(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}const s=this.findTrackForTextTrack(t);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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.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;Fr(i.textTracks).forEach(r=>{Wn(r)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,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=t.details,this.log(`Subtitle track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.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,h)=>{c.id=h});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=r;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const c=q(o,r);if(c>-1)n=r[c];else{const h=q(o,this.tracks);n=this.tracks[h]}}let u=this.findTrackId(n);u===-1&&n&&(u=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(g.SUBTITLE_TRACKS_UPDATED,l),u!==-1&&this.trackId===-1&&this.setSubtitleTrack(u)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||le(n,e)))return s}if(e){for(let s=0;s<t.length;s++){const n=t[s];if(or(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const n=t[s];if(or(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(ha(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===xe.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&le(e,i))return i;const s=q(e,this.tracksInGroup);if(s>-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(i)return null;{const n=q(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),r=e.details,o=r==null?void 0:r.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||0:""):""} ${n}`),this.hls.trigger(g.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Fr(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(n=>ha(i,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){const n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!b(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:r,groupId:o="",name:u,type:l,url:c}=s;this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:r,groupId:o,name:u,type:l,url:c});const h=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(h)}}function Ec(){try{return crypto.randomUUID()}catch(a){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}function lr(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const jn=.025;let Mr=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function _c(a,e,t){return`${a.identifier}-${t+1}-${lr(e)}`}class Sc{constructor(e,t){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=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Sa(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=Sa(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=b(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Sa(e,t)}return e}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)<jn))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Mr.Range:Mr.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 Tc(this)}}function Sa(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<jn)?e.start:e.start+e.duration}function Oo(a,e,t){const i=new self.URL(a,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function Ta(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function Tc(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function zn(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class xc{constructor(e,t,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&&this.hls.trigger(g.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const r=()=>{this.hasDetails=!0};n.once(g.LEVEL_LOADED,r),n.once(g.AUDIO_TRACK_LOADED,r),n.once(g.SUBTITLE_TRACK_LOADED,r),n.on(g.MEDIA_ATTACHING,(o,{media:u})=>{this.removeMediaListeners(),this.mediaAttached=u,this.interstitial.playoutLimit&&(u.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(g.BUFFER_APPENDED,()=>{const c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(g.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Oo(t,e.config.primarySessionId||"").href}catch(i){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,n=bt.bufferInfo(e,s,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=bt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${zn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fo=.033;class Ac extends De{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.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(t===o||t>o&&(t<o+(r.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,n=this.events,r=this.parseDateRanges(s,{url:i.url},t),o=Object.keys(s),u=n?n.filter(l=>!o.includes(l.identifier)):[];r.length&&r.sort((l,c)=>{const h=l.cue.pre,m=l.cue.post,v=c.cue.pre,y=c.cue.post;if(h&&!v)return-1;if(v&&!h||m&&!y)return 1;if(y&&!m)return-1;if(!h&&!v&&!m&&!y){const S=l.startTime,E=c.startTime;if(S!==E)return S-E}return l.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=r,u.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,u)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const n=this.items,r=this.parseSchedule(s,e);(i||t.length||(n==null?void 0:n.length)!==r.length||r.some((u,l)=>Math.abs(u.playout.start-n[l].playout.start)>.005||Math.abs(u.playout.end-n[l].playout.end)>.005))&&(this.items=r,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,i){const s=[],n=Object.keys(e);for(let r=0;r<n.length;r++){const o=n[r],u=e[o];if(u.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(u):(l=new Sc(u,t),this.eventMap[o]=l,i===!1&&(l.appendInPlace=i)),s.push(l)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,n=s.live?1/0:s.edge;let r=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,l=0;if(e.forEach((c,h)=>{const m=c.cue.pre,v=c.cue.post,y=e[h-1]||null,S=c.appendInPlace,E=v?n:c.startOffset,x=c.duration,R=c.timelineOccupancy===Mr.Range?x:0,L=c.resumptionOffset,P=(y==null?void 0:y.startTime)===E,V=E+c.cumulativeDuration;let re=S?V+x:E+L;if(m||!v&&E<=0){const j=l;l+=R,c.timelineStart=V;const Y=r;r+=x,i.push({event:c,start:V,end:re,playout:{start:Y,end:r},integrated:{start:j,end:l}})}else if(E<=n){if(!P){const U=E-u;if(U>Fo){const ce=u,He=l;l+=U;const ut=r;r+=U;const yt={previousEvent:e[h-1]||null,nextEvent:c,start:ce,end:ce+U,playout:{start:ut,end:r},integrated:{start:He,end:l}};i.push(yt)}else U>0&&y&&(y.cumulativeDuration+=U,i[i.length-1].end=E)}v&&(re=V),c.timelineStart=V;const j=l;l+=R;const Y=r;r+=x,i.push({event:c,start:V,end:re,playout:{start:Y,end:r},integrated:{start:j,end:l}})}else return;const N=c.resumeTime;v||N>n?u=n:u=N}),u<n){var o;const c=u,h=l,m=n-u;l+=m;const v=r;r+=m,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:u,end:c+m,playout:{start:v,end:r},integrated:{start:h,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(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let n=0,r=-1;e.forEach((o,u)=>{const l=o.cue.pre,c=o.cue.post,h=l?0:c?s:o.startTime;this.updateAssetDurations(o),r===h?o.cumulativeDuration=n:(n=0,r=h),!c&&o.snapOptions.in&&(o.resumeAnchor=zt(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&u+1<e.length&&e[u+1].startTime-e[u].resumeTime<Fo&&(e[u+1].appendInPlace=!1,e[u+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const v=b(o.resumeOffset)?o.resumeOffset:o.duration;n+=v})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>jn?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(r=>{const o=t[r].details,u=o.edge;if(i>=u)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${u}`),!1;const l=zt(null,o.fragments,i);if(!l)return this.log(`"${e.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)<jn+c||Math.abs(l.end-i)<jn+c?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,n=!1;for(let r=0;r<e.assetList.length;r++){const o=e.assetList[r],u=t+i;o.startOffset=i,o.timelineStart=u,s||(s=o.duration===null),n||(n=!!o.error);const l=o.error?0:o.duration||0;i+=l}s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function tn(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class bc{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=Oo(i,this.hls.sessionId,e.baseUrl)}catch(m){const v=this.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,m,i);this.hls.trigger(g.ERROR,v);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,r=n.loader,o=new r(n),u={responseType:"json",url:s.href},l=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,v,y,S)=>{const E=m.data,x=E==null?void 0:E.ASSETS;if(!Array.isArray(x)){const R=this.assignAssetListError(e,A.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),y.url,v,S);this.hls.trigger(g.ERROR,R);return}e.assetListResponse=E,this.hls.trigger(g.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:S})},onError:(m,v,y,S)=>{const E=this.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${v.url})`),v.url,S,y);this.hls.trigger(g.ERROR,E)},onTimeout:(m,v,y)=>{const S=this.assignAssetListError(e,A.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,m,y);this.hls.trigger(g.ERROR,S)}};return o.load(u,c,h),this.hls.trigger(g.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,r){return e.error=i,{type:Z.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:r,stats:n}}}function Mo(a){a==null||a.play().catch(()=>{})}function Br(a,e){return`[${a}] Advancing timeline position to ${e}`}class Lc extends De{constructor(e,t){super("interstitials",e.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||!this.schedule)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(!0),this.checkBuffer(),r&&i<o.start||i>=o.end){var u;const v=this.findItemIndex(o);let y=this.schedule.findItemIndexAtTime(i);if(y===-1&&(y=v+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${i} (resolving from ${v} to ${y})`)),!this.isInterstitial(o)&&(u=this.media)!=null&&u.paused&&(this.shouldPlay=!1),!r&&y>v){const S=this.schedule.findJumpRestrictedIndex(v+1,y);if(S>v){this.setSchedulePosition(S);return}}this.setSchedulePosition(y);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const v=o.event.assetList[0];v&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,v))}return}const c=l.timelineStart,h=l.duration||0;if(r&&i<c||i>=c+h){var m;(m=o.event)!=null&&m.appendInPlace&&(this.clearInterstitial(o.event,o),this.flushFrontBuffer(i)),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;if(!n)return;const r=this.playingItem,o=n.events||[],u=n.items||[],l=n.durations,c=i.map(S=>S.identifier),h=!!(o.length||c.length);(h||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
Schedule: ${u.map(S=>tn(S))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let m=null,v=null;r&&(m=this.updateItem(r,this.timelinePos),this.itemsMatch(r,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const y=this.bufferingItem;if(y&&(v=this.updateItem(y,this.bufferedPos),this.itemsMatch(y,v)?this.bufferingItem=v:y.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(y.event,null))),i.forEach(S=>{S.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(S=>{if(S.interstitial.appendInPlace){const E=S.assetItem.timelineStart,x=S.timelineOffset-E;if(x)try{S.timelineOffset=E}catch(R){Math.abs(x)>jn&&this.warn(`${R} ("${S.assetId}" ${S.timelineOffset}->${E})`)}}}),h||s){if(this.hls.trigger(g.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:u.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}r&&this.trimInPlace(m,r),y&&v!==m&&this.trimInPlace(v,y),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new bc(e),this.schedule=new Ac(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(g.MEDIA_ENDED,this.onMediaEnded,this),e.on(g.ERROR,this.onError,this),e.on(g.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(g.MEDIA_ENDED,this.onMediaEnded,this),e.off(g.ERROR,this.onError,this),e.off(g.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.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.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){xs(e,"play",this.onPlay),xs(e,"pause",this.onPause),xs(e,"seeking",this.onSeeking),xs(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;ms(i,"seeking",this.onSeeking),ms(i,"timeupdate",this.onTimeupdate),ms(i,"play",this.onPlay),ms(i,"pause",this.onPause)}onMediaAttached(e,t){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.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=h=>h&&e.getAssetPlayer(h.identifier),s=(h,m,v,y,S)=>{if(h){let E=h[m].start;const x=h.event;if(x){if(m==="playout"||x.timelineOccupancy!==Mr.Point){const R=i(v);(R==null?void 0:R.interstitial)===x&&(E+=R.assetItem.startOffset+R[S])}}else{const R=y==="bufferedPos"?r():e[y];E+=R-h.start}return E}return 0},n=(h,m)=>{var v;if(h!==0&&m!=="primary"&&(v=e.schedule)!=null&&v.length){var y;const S=e.schedule.findItemIndexAtTime(h),E=(y=e.schedule.items)==null?void 0:y[S];if(E){const x=E[m].start-E.start;return h+x}}return h},r=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,v;return(m=e.primaryDetails)!=null&&m.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[h])||0},u=(h,m)=>{var v,y;const S=e.effectivePlayingItem;if(S!=null&&(v=S.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${m}"`);const E=e.effectivePlayingItem,x=e.schedule.findItemIndexAtTime(h,m),R=(y=e.schedule.items)==null?void 0:y[x],L=e.getBufferingPlayer(),P=L==null?void 0:L.interstitial,V=P==null?void 0:P.appendInPlace,re=E&&e.itemsMatch(E,R);if(E&&(V||re)){const N=i(e.playingAsset),j=(N==null?void 0:N.media)||e.primaryMedia;if(j){const Y=m==="primary"?j.currentTime:s(E,m,e.playingAsset,"timelinePos","currentTime"),U=h-Y,ce=(V?Y:j.currentTime)+U;if(ce>=0&&(!N||V||ce<=N.duration)){j.currentTime=ce;return}}}if(R){let N=h;if(m!=="primary"){const Y=R[m].start,U=h-Y;N=R.start+U}const j=!e.isInterstitial(R);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(j||R.event.appendInPlace)){const Y=e.media||(V?L==null?void 0:L.media:null);Y&&(Y.currentTime=N)}else if(E){const Y=e.findItemIndex(E);if(x>Y){const ce=e.schedule.findJumpRestrictedIndex(Y+1,x);if(ce>Y){e.setSchedulePosition(ce);return}}let U=0;if(j)e.timelinePos=N,e.checkBuffer();else{const ce=R.event.assetList,He=h-(R[m]||R).start;for(let ut=ce.length;ut--;){const yt=ce[ut];if(yt.duration&&He>=yt.startOffset&&He<yt.startOffset+yt.duration){U=ut;break}}}e.setSchedulePosition(x,U)}}},l=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const m=t();return e.isInterstitial(m)?m:null},c={get bufferedEnd(){const h=t(),m=e.bufferingItem;if(m&&m===h){var v;return s(m,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const h=l(),m=e.effectivePlayingItem;return m&&m===h?s(m,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=l(),v=e.effectivePlayingItem;v&&v===m&&u(h+v.playout.start,"playout")},get duration(){const h=l();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=l())==null?void 0:h.event.assetList;return m?m.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var h;const m=(h=l())==null?void 0:h.event;return m&&e.effectivePlayingAsset?m.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return l()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return r()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){u(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){u(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return n(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,m=h==null?void 0:h.event;if(m&&!m.restrictions.skip){const v=e.findItemIndex(h);if(m.appendInPlace){const y=h.playout.start+h.event.duration;u(y+.001,"playout")}else e.advanceAfterAssetEnded(m,v,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!b(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Ce(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null;const r=this.hls,o=e!==r,u=o&&e.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource;let c;if(r.media)u&&(n=r.transferMedia(),this.detachedData=n),c="Primary";else if(l){const y=this.getBufferingPlayer();y?(n=y.transferMedia(),c=`${y}`):c="detached MediaSource"}else c="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${Ce(n)}`);else if(!this.detachedData||r.media===t){const y=this.playerQueue;y.length>1&&y.forEach(S=>{if(o&&S.interstitial.appendInPlace!==u){const E=S.interstitial;this.clearInterstitial(S.interstitial,null),E.appendInPlace=!1,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const h=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed",m=h&&n?n:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(m===n&&v){const y=o&&e.assetId===v.assetIdAtEnd;m.overrides={duration:v.duration,endOfStream:!o||y,cueRemoval:!o}}e.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||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.log(Br("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){const r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(n>=0||!this.primaryLive){const r=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(r);this.setSchedulePosition(o)}}else if(s&&!this.playingItem){const n=e.findItemIndex(s);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),n=Ta(i,s);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var r;const o=(r=this.schedule.items)==null?void 0:r[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,i){const s=Ta(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const n=this.schedule.items;if(n){const r=t+1,o=n.length;if(r>=o){this.setSchedulePosition(-1);return}const u=e.resumeTime;this.timelinePos<u&&(this.log(Br("advanceAfterAssetEnded",u)),this.timelinePos=u,e.appendInPlace&&this.advanceInPlace(u),this.checkBuffer(this.bufferedPos<u)),this.setSchedulePosition(r)}}}else{if(e.appendInPlace){const n=e.assetList[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,n=i.getEvent(s);if(n){const r=i.findEventIndex(s),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,r,o-1)}}setSchedulePosition(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;const n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&tn(n)}) pos: ${this.timelinePos}`);const r=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(r)){const c=r.event,h=this.playingAsset,m=h==null?void 0:h.identifier,v=m?this.getAssetPlayer(m):null;if(v&&m&&(!this.eventItemsMatch(r,n)||t!==void 0&&m!==c.assetList[t].identifier)){var u;const y=c.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${y+1}/${c.assetList.length} ${zn(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(g.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:y,event:c,schedule:s.slice(0),scheduleIndex:e,player:v}),r!==this.playingItem){this.itemsMatch(r,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),y);return}this.retreiveMediaSource(m,n),v.media&&!((u=this.detachedData)!=null&&u.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(r,n)&&(this.endedItem=r,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${tn(r)}`),c.hasPlayed=!0,this.hls.trigger(g.INTERSTITIAL_ENDED,{event:c,schedule:s.slice(0),scheduleIndex:e}),c.cue.once)){var l;this.updateSchedule();const y=(l=this.schedule)==null?void 0:l.items;if(n&&y){const S=this.findItemIndex(n);this.advanceSchedule(S,y,t,r,o)}return}}this.advanceSchedule(e,s,t,r,o)}advanceSchedule(e,t,i,s,n){const r=this.schedule;if(!r)return;const o=t[e]||null,u=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(c=>{const h=c.interstitial,m=r.findEventIndex(h.identifier);(m<e||m>e+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const c=o.event;if(i===void 0){i=r.findAssetIndex(c,this.timelinePos);const y=Ta(c,i-1);if(c.isAssetPastPlayoutLimit(y)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,i);return}i=y}const h=this.waitingItem;this.assetsBuffered(o,u)||this.setBufferingItem(o);let m=this.preloadAssets(c,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${tn(o)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(g.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!u){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const v=c.assetList[i];if(!v){this.advanceAfterAssetEnded(c,e,i||0);return}if(m||(m=this.getAssetPlayer(v.identifier)),m===null||m.destroyed){const y=c.assetList.length;this.warn(`asset ${i+1}/${y} player destroyed ${c}`),m=this.createAssetPlayer(c,v,i),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(m,i,t,e,u),this.shouldPlay&&Mo(m.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&Mo(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(r.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${tn(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Br("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;const r=(n=this.schedule)==null?void 0:n.items;r&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${tn(e)}`),this.hls.trigger(g.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(i<s.fragmentStart||i>s.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:bt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):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(e,i)),i||(this.log(Br("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.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(g.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(g.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level],s=z(z({},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(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=z(z({},this.altSelection),{},{audio:i});return}const n=z(z({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=z(z({},this.altSelection),{},{subtitles:i});return}const n=z(z({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){const i=ne(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=ne(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const n=t[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(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(e&&s){const n=this.findItemIndex(e,t);return s[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,r)=>{e.event.isAssetPastPlayoutLimit(r)&&this.clearAssetPlayer(n.identifier,null)});const i=e.end+.25,s=bt.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${tn(e)} (was ${tn(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const s=bt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){const s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const r=this.playingItem,o=this.findItemIndex(r);let u=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const c=this.findItemIndex(n),h=Math.min(c+1,t.length-1),m=t[h];if((u===-1&&n&&e>=n.end||(l=m.event)!=null&&l.appendInPlace&&e+.01>=m.start)&&(u=h),this.isInterstitial(n)){const v=n.event;if(h-o>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,u>c&&u>o)this.bufferedToItem(m);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&m.start<v.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(m)&&this.preloadAssets(m.event,0)}}else i&&r&&!this.itemsMatch(r,n)&&(u===o?this.bufferedToItem(r):u===o+1&&this.bufferedToItem(t[u]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{const n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:n}=i;if(!s||!n)return t;const r=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const u=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${tn(e)}`+(t?` (${u.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(r){const l=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,h)=>{const m=this.getAssetPlayer(c.identifier);m&&(h===l&&m.loadSource(),m.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(g.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){const r=this.preloadAssets(i,t);if(r!=null&&r.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(r,o)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,r=e.cue.once;if(n){const u=e.timelineStart;if(e.appendInPlace){var o;const m=this.playingItem;!this.isInterstitial(m)&&(m==null||(o=m.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(u+.25)}let l,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){const m=c-u;m>0&&(l=Math.round(m*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${l?` live-start: ${c} start-offset: ${l}`:""}`),i)return this.createAsset(e,0,0,u,e.duration,i);const h=this.assetListLoader.loadAssetList(e,l);h&&(e.assetListLoader=h)}else if(!r&&s){for(let l=t;l<s;l++){const c=e.assetList[l],h=this.getAssetPlayerQueueIndex(c.identifier);(h===-1||this.playerQueue[h].destroyed)&&!c.error&&this.createAssetPlayer(e,c,l)}const u=e.assetList[t];if(u){const l=this.getAssetPlayer(u.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(s=>{this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,n,r){const o={parentIdentifier:e.identifier,identifier:_c(e,r,t),duration:n,startOffset:i,timelineStart:s,uri:r};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){const s=this.hls,n=s.userConfig;let r=n.videoPreference;const o=s.loadLevelObj||s.levels[s.currentLevel];(r||o)&&(r=Re({},r),o.videoCodec&&(r.videoCodec=o.videoCodec),o.videoRange&&(r.allowedVideoRanges=[o.videoRange]));const u=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let c=0;if(this.primaryLive||e.appendInPlace){const P=this.timelinePos-t.timelineStart;if(P>1){const V=t.duration;V&&P<V&&(c=P)}}const h=t.identifier,m=z(z({},n),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:r,audioPreference:u||n.audioPreference,subtitlePreference:l||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(m.timelineOffset=t.timelineStart));const v=m.cmcd;v!=null&&v.sessionId&&v.contentId&&(m.cmcd=Re({},v,{contentId:lr(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const y=new xc(this.HlsPlayerClass,m,e,t);this.playerQueue.push(y),e.assetList[i]=t;let S=!0;const E=P=>{if(P.live){var V;const j=new Error(`Interstitials MUST be VOD assets ${e}`),Y={fatal:!0,type:Z.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:j},U=((V=this.schedule)==null?void 0:V.findEventIndex(e.identifier))||-1;this.handleAssetItemError(Y,e,U,i,j.message);return}const re=P.edge-P.fragmentStart,N=t.duration;(S||N===null||re>N)&&(S=!1,this.log(`Interstitial asset "${h}" duration change ${N} > ${re}`),t.duration=re,this.updateSchedule())};y.on(g.LEVEL_UPDATED,(P,{details:V})=>E(V)),y.on(g.LEVEL_PTS_UPDATED,(P,{details:V})=>E(V)),y.on(g.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const x=(P,V)=>{const re=this.getAssetPlayer(h);if(re&&V.tracks){re.off(g.BUFFER_CODECS,x),re.tracks=V.tracks;const N=this.primaryMedia;this.bufferingAsset===re.assetItem&&N&&!re.media&&this.bufferAssetPlayer(re,N)}};y.on(g.BUFFER_CODECS,x);const R=()=>{var P;const V=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${V}`),!V||!this.schedule)return;const re=this.schedule.findEventIndex(e.identifier),N=(P=this.schedule.items)==null?void 0:P[re];this.isInterstitial(N)&&this.advanceAssetBuffering(N,t)};y.on(g.BUFFERED_TO_END,R);const L=P=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const re=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,re,P)};return y.once(g.MEDIA_ENDED,L(i)),y.once(g.PLAYOUT_LIMIT_REACHED,L(1/0)),y.on(g.ERROR,(P,V)=>{if(!this.schedule)return;const re=this.getAssetPlayer(h);if(V.details===A.BUFFER_STALLED_ERROR){if(re!=null&&re.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(V,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${V.error} ${e}`)}),y.on(g.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const V=new Error(`Asset player destroyed unexpectedly ${h}`),re={fatal:!0,type:Z.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:V};this.handleAssetItemError(re,e,this.schedule.findEventIndex(e.identifier),i,V.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${zn(t)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&tn(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){const{interstitial:r,assetItem:o,assetId:u}=e,l=r.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!c||c.identifier!==u)&&(c&&(this.clearAssetPlayer(c.identifier,i[s]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${zn(o)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:r,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:n,assetItem:r}=e,o=this.schedule.findEventIndex(n.identifier),u=(i=this.schedule.items)==null?void 0:i[o];if(!u)return;e.loadSource(),this.setBufferingItem(u),this.bufferingAsset=r;const l=this.getBufferingPlayer();if(l===e)return;const c=n.appendInPlace;if(c&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const h=(l==null?void 0:l.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(c&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!Gt(h,e.tracks)){const m=new Error(`Asset ${zn(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),v={fatal:!0,type:Z.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},y=n.findAssetIndex(r);this.handleAssetItemError(v,n,o,y,m.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,n=t.findAssetIndex(e,s),r=e.assetList[n];if(r){const o=this.getAssetPlayer(r.identifier);if(o){const u=o.currentTime||s-r.timelineStart,l=o.duration-u;if(this.warn(`Stalled at ${u} of ${u+l} in ${o} ${e} (media.currentTime: ${s})`),u&&(l/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){const c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,n){if(e.details===A.BUFFER_STALLED_ERROR)return;const r=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${r&&zn(r)} ${e.error}`),!this.schedule)return;const o=(r==null?void 0:r.identifier)||"",u=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[u]||null,c=this.schedule.items,h=Re({},e,{fatal:!1,errorAction:$i(!0),asset:r,assetListIndex:s,event:t,schedule:c,scheduleIndex:i,player:l});if(this.hls.trigger(g.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const m=this.playingAsset,v=this.bufferingAsset,y=new Error(n);if(r&&(this.clearAssetPlayer(o,null),r.error=y),!t.assetList.some(S=>!S.error))t.error=y;else for(let S=s;S<t.assetList.length;S++)this.resetAssetPlayer(t.assetList[S].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):m&&m.identifier===o?this.advanceAfterAssetEnded(t,i,s):v&&v.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,v)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${tn(i)} error: ${e.error}`);let s=this.timelinePos;s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);if(this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}else this.checkStart()}onAssetListLoaded(e,t){var i,s;const n=t.event,r=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(r)))return;const u=n.timelineStart,l=n.duration;let c=0;o.forEach((S,E)=>{const x=parseFloat(S.DURATION);this.createAsset(n,E,c,u+c,x,S.URI),c+=x}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${l}) ${n}`);const h=this.waitingItem,m=(h==null?void 0:h.event.identifier)===r;this.updateSchedule();const v=(s=this.bufferingItem)==null?void 0:s.event;if(m){var y;const S=this.schedule.findEventIndex(r),E=(y=this.schedule.items)==null?void 0:y[S];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==S){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(E)}this.setSchedulePosition(S)}else if((v==null?void 0:v.identifier)===r){const S=n.assetList[0];if(S){const E=this.getAssetPlayer(S.identifier);if(v.appendInPlace){const x=this.primaryMedia;E&&x&&this.bufferAssetPlayer(E,x)}else E&&E.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case A.ASSET_LIST_PARSING_ERROR:case A.ASSET_LIST_LOAD_ERROR:case A.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case A.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Bo=500;class Rc extends _n{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",ae.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=ue.IDLE,this.setInterval(Bo),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragContextChanged(i)||(Ie(i)&&(this.fragPrevious=i),this.state=ue.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 u=i.start+i.duration;r?r.end=u:(r={start:o,end:u},n.push(r)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;t.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,ae.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===ae.SUBTITLE&&(t.details===A.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ue.STOPPED&&(this.state=ue.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ho(this.levels,t)){this.levels=t.map(i=>new et(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new et(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ae.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.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!==ue.STOPPED&&this.setInterval(Bo)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:n}=this,{details:r,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const u=n[o];if(o>=n.length||!u)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=u.details)!=null&&i.live){if(r.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const m=h.fragments[0];if(!u.details)r.hasProgramDateTime&&h.hasProgramDateTime?(En(r,h),l=r.fragmentStart):m&&(l=m.start,er(r,l));else{var c;l=this.alignPlaylists(r,u.details,(c=this.levelLastLoaded)==null?void 0:c.details),l===0&&m&&(l=m.start,er(r,l))}h&&!this.startFragRequested&&this.setStartPosition(h,l)}u.details=r,this.levelLastLoaded=u,o===s&&(this.hls.trigger(g.SUBTITLE_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===ue.IDLE&&(zt(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),u.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&Ss(s.method)){const r=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Qi(s.method)).catch(o=>{throw n.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const u=performance.now();n.trigger(g.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:r,tdecrypt:u}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=ue.IDLE})}}doTick(){if(!this.media){this.state=ue.IDLE;return}if(this.state===ue.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:s}=this,n=this.getLoadPosition(),r=bt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:u}=r,l=i.details,c=this.hls.maxBufferLength+l.levelTargetDuration;if(u>c)return;const h=l.fragments,m=h.length,v=l.edge;let y=null;const S=this.fragPrevious;if(o<v){const R=s.maxFragLookUpTolerance,L=o>v-R?0:R;y=zt(S,h,Math.max(h[0].start,o),L),!y&&S&&S.start<h[0].start&&(y=h[0])}else y=h[m-1];if(y=this.filterReplacedPrimary(y,i.details),!y)return;const E=y.sn-l.startSN,x=h[E-1];if(x&&x.cc===y.cc&&this.fragmentTracker.getState(x)===Jt.NOT_LOADED&&(y=x),this.fragmentTracker.getState(y)===Jt.NOT_LOADED){const R=this.mapToInitFragWhenRequired(y);R&&this.loadFragment(R,i,o)}}}loadFragment(e,t,i){Ie(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ic(this.tracksBuffered[this.currentTrackId]||[])}}class Ic{constructor(e){this.buffered=void 0;const t=(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 e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const Cc={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},No=a=>String.fromCharCode(Cc[a]||a),sn=15,Tn=100,Dc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},wc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},kc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Pc={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Oc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Fc{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;J.log(`${this.time} [${e}] ${i}`)}}}const wn=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Uo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Mc{constructor(){this.uchar=" ",this.penState=new Uo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Bc{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Uo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Tn;t++)this.chars.push(new Mc);this.logger=e}equals(e){for(let t=0;t<Tn;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Tn;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Tn;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Tn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Tn)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=No(e);if(this.pos>=Tn){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Tn;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Tn;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class xa{constructor(e){this.rows=[],this.currRow=sn-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<sn;t++)this.rows.push(new Bc(e));this.logger=e}reset(){for(let e=0;e<sn;e++)this.rows[e].clear();this.currRow=sn-1}equals(e){let t=!0;for(let i=0;i<sn;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<sn;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<sn;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Ce(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<sn;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const o=r.rows[n].cueStartTime,u=this.logger.time;if(o!==null&&u!==null&&o<u)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(r.rows[n+l])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,r=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[r].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Ce(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let n=0;n<sn;n++){const r=this.rows[n].getTextString();r&&(s=n+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
`)),i}getTextAndFormat(){return this.rows}}class $o{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new xa(i),this.nonDisplayedMemory=new xa(i),this.lastOutputScreen=new xa(i),this.currRollUpRow=this.displayedMemory.rows[sn-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[sn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+Ce(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Go{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Uc(),this.logger=void 0;const s=this.logger=new Fc;this.channels=[null,new $o(e,t,s),new $o(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,n=t[i+1]&127;let r=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+wn([t[i],t[i+1]])+"] -> ("+wn([s,n])+")");const u=this.cmdHistory;if(s>=16&&s<=31){if(Nc(s,n,u)){Nr(null,null,u),this.logger.log(3,()=>"Repeated command ("+wn([s,n])+") is dropped");continue}Nr(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 Nr(null,null,u);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 "+wn([s,n])+" orig: "+wn([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;const n=e===20||e===21||e===23?1:2,r=this.channels[n];return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===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(t),this.logger.log(3,()=>"MIDROW ("+wn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;const r=e<=23?1:2;t>=64&&t<=95?i=r===1?Dc[e]:kc[e]:i=r===1?wc[e]:Pc[e];const o=this.channels[r];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-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(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let r;n===17?r=t+80:n===18?r=t+112:r=t+144,this.logger.log(2,()=>"Special char '"+No(r)+"' in channel "+i),s=[r]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+wn(s).join(",")),s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n;const r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=Oc[n],t%2===1&&(r.background=r.background+"_semi")):t===45?r.background="transparent":(r.foreground="black",t===47&&(r.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Nr(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Nr(a,e,t){t.a=a,t.b=e}function Nc(a,e,t){return t.a===a&&t.b===e}function Uc(){return{a:null,b:null}}var Aa=function(){if(Xs!=null&&Xs.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,u){if(typeof u!="string"||!Array.isArray(o))return!1;const l=u.toLowerCase();return~o.indexOf(l)?l:!1}function i(o){return t(a,o)}function s(o){return t(e,o)}function n(o,...u){let l=1;for(;l<arguments.length;l++){const c=arguments[l];for(const h in c)o[h]=c[h]}return o}function r(o,u,l){const c=this,h={enumerable:!0};c.hasBeenReset=!1;let m="",v=!1,y=o,S=u,E=l,x=null,R="",L=!0,P="auto",V="start",re=50,N="middle",j=50,Y="middle";Object.defineProperty(c,"id",n({},h,{get:function(){return m},set:function(U){m=""+U}})),Object.defineProperty(c,"pauseOnExit",n({},h,{get:function(){return v},set:function(U){v=!!U}})),Object.defineProperty(c,"startTime",n({},h,{get:function(){return y},set:function(U){if(typeof U!="number")throw new TypeError("Start time must be set to a number.");y=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},h,{get:function(){return S},set:function(U){if(typeof U!="number")throw new TypeError("End time must be set to a number.");S=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},h,{get:function(){return E},set:function(U){E=""+U,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},h,{get:function(){return x},set:function(U){x=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},h,{get:function(){return R},set:function(U){const ce=i(U);if(ce===!1)throw new SyntaxError("An invalid or illegal string was specified.");R=ce,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},h,{get:function(){return L},set:function(U){L=!!U,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},h,{get:function(){return P},set:function(U){if(typeof U!="number"&&U!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");P=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},h,{get:function(){return V},set:function(U){const ce=s(U);if(!ce)throw new SyntaxError("An invalid or illegal string was specified.");V=ce,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},h,{get:function(){return re},set:function(U){if(U<0||U>100)throw new Error("Position must be between 0 and 100.");re=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},h,{get:function(){return N},set:function(U){const ce=s(U);if(!ce)throw new SyntaxError("An invalid or illegal string was specified.");N=ce,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},h,{get:function(){return j},set:function(U){if(U<0||U>100)throw new Error("Size must be between 0 and 100.");j=U,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},h,{get:function(){return Y},set:function(U){const ce=s(U);if(!ce)throw new SyntaxError("An invalid or illegal string was specified.");Y=ce,this.hasBeenReset=!0}})),c.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class $c{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Vo(a){function e(i,s,n,r){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(r||0)}const t=a.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Gc{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Ko(a,e,t,i){const s=i?a.split(i):[a];for(const n in s){if(typeof s[n]!="string")continue;const r=s[n].split(t);if(r.length!==2)continue;const o=r[0],u=r[1];e(o,u)}}const ba=new Aa(0,0,""),Ur=ba.align==="middle"?"middle":"center";function Vc(a,e,t){const i=a;function s(){const o=Vo(a);if(o===null)throw new Error("Malformed timestamp: "+i);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,u){const l=new Gc;Ko(o,function(m,v){let y;switch(m){case"region":for(let S=t.length-1;S>=0;S--)if(t[S].id===v){l.set(m,t[S].region);break}break;case"vertical":l.alt(m,v,["rl","lr"]);break;case"line":y=v.split(","),l.integer(m,y[0]),l.percent(m,y[0])&&l.set("snapToLines",!1),l.alt(m,y[0],["auto"]),y.length===2&&l.alt("lineAlign",y[1],["start",Ur,"end"]);break;case"position":y=v.split(","),l.percent(m,y[0]),y.length===2&&l.alt("positionAlign",y[1],["start",Ur,"end","line-left","line-right","auto"]);break;case"size":l.percent(m,v);break;case"align":l.alt(m,v,["start",Ur,"end","left","right"]);break}},/:/,/\s/),u.region=l.get("region",null),u.vertical=l.get("vertical","");let c=l.get("line","auto");c==="auto"&&ba.line===-1&&(c=-1),u.line=c,u.lineAlign=l.get("lineAlign","start"),u.snapToLines=l.get("snapToLines",!0),u.size=l.get("size",100),u.align=l.get("align",Ur);let h=l.get("position","auto");h==="auto"&&ba.position===50&&(h=u.align==="start"||u.align==="left"?0:u.align==="end"||u.align==="right"?100:50),u.position=h}function r(){a=a.replace(/^\s+/,"")}if(r(),e.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(),e.endTime=s(),r(),n(a,e)}function Ho(a){return a.replace(/<br(?: \/)?>/gi,`
`)}class Kc{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new $c,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,r=0;for(n=Ho(n);r<n.length&&n[r]!=="\r"&&n[r]!==`
`;)++r;const o=n.slice(0,r);return n[r]==="\r"&&++r,n[r]===`
`&&++r,t.buffer=n.slice(r),o}function s(n){Ko(n,function(r,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:n=i(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new Aa(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Vc(n,t.cue,t.regionList)}catch(o){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
`),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch(n){t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Hc=/\r\n|\n\r|\n|\r/g,La=function(e,t,i=0){return e.slice(i,i+t.length)===t},Wc=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!b(t)||!b(i)||!b(s)||!b(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t};function Ra(a,e,t){return lr(a.toString())+lr(e.toString())+lr(t)}const jc=function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(r=n)!=null&&r.new;){var r;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i};function zc(a,e,t,i,s,n,r){const o=new Kc,u=_t(new Uint8Array(a)).trim().replace(Hc,`
`).split(`
`),l=[],c=e?su(e.baseTime,e.timescale):0;let h="00:00.000",m=0,v=0,y,S=!0;o.oncue=function(E){const x=t[i];let R=t.ccOffset;const L=(m-c)/9e4;if(x!=null&&x.new&&(v!==void 0?R=t.ccOffset=x.start:jc(t,i,L)),L){if(!e){y=new Error("Missing initPTS for VTT MPEGTS");return}R=L-t.presentationOffset}const P=E.endTime-E.startTime,V=Ws((E.startTime+R-v)*9e4,s*9e4)/9e4;E.startTime=Math.max(V,0),E.endTime=Math.max(V+P,0);const re=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(re)),E.id||(E.id=Ra(E.startTime,E.endTime,re)),E.endTime>0&&l.push(E)},o.onparsingerror=function(E){y=E},o.onflush=function(){if(y){r(y);return}n(l)},u.forEach(E=>{if(S)if(La(E,"X-TIMESTAMP-MAP=")){S=!1,E.slice(16).split(",").forEach(x=>{La(x,"LOCAL:")?h=x.slice(6):La(x,"MPEGTS:")&&(m=parseInt(x.slice(7)))});try{v=Wc(h)/1e3}catch(x){y=x}return}else E===""&&(S=!1);o.parse(E+`
`)}),o.flush()}const Ia="stpp.ttml.im1t",Wo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,jo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Yc={left:"start",center:"center",right:"end",start:"start",end:"end"};function zo(a,e,t,i){const s=B(new Uint8Array(a),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>_t(o)),r=iu(e.baseTime,1,e.timescale);try{n.forEach(o=>t(Zc(o,r)))}catch(o){i(o)}}function Zc(a,e){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((h,m)=>(h[m]=s.getAttribute(`ttp:${m}`)||n[m],h),{}),o=s.getAttribute("xml:space")!=="preserve",u=Yo(Ca(s,"styling","style")),l=Yo(Ca(s,"layout","region")),c=Ca(s,"body","[begin]");return[].map.call(c,h=>{const m=Zo(h,o);if(!m||!h.hasAttribute("begin"))return null;const v=wa(h.getAttribute("begin"),r),y=wa(h.getAttribute("dur"),r);let S=wa(h.getAttribute("end"),r);if(v===null)throw qo(h);if(S===null){if(y===null)throw qo(h);S=v+y}const E=new Aa(v-e,S-e,m);E.id=Ra(E.startTime,E.endTime,E.text);const x=l[h.getAttribute("region")],R=u[h.getAttribute("style")],L=qc(x,R,u),{textAlign:P}=L;if(P){const V=Yc[P];V&&(E.lineAlign=V),E.align=P}return Re(E,L),E}).filter(h=>h!==null)}function Ca(a,e,t){const i=a.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Yo(a){return a.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Zo(a,e){return[].slice.call(a.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
`:(n=i.childNodes)!=null&&n.length?Zo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function qc(a,e,t){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&&t.hasOwnProperty(r)&&(s=t[r]),n.reduce((o,u)=>{const l=Da(e,i,u)||Da(a,i,u)||Da(s,i,u);return l&&(o[u]=l),o},{})}function Da(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function qo(a){return new Error(`Could not parse ttml timestamp ${a}`)}function wa(a,e){if(!a)return null;let t=Vo(a);return t===null&&(Wo.test(a)?t=Xc(a,e):jo.test(a)&&(t=Qc(a,e))),t}function Xc(a,e){const t=Wo.exec(a),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Qc(a,e){const t=jo.exec(a),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class $r{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Jc{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Jo(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new $r(this,"textTrack1"),t=new $r(this,"textTrack2"),i=new $r(this,"textTrack3"),s=new $r(this,"textTrack4");this.cea608Parser1=new Go(1,e,t),this.cea608Parser2=new Go(3,i,s)}addCues(e,t,i,s,n){let r=!1;for(let o=n.length;o--;){const u=n[o],l=ed(u[0],u[1],t,i);if(l>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],i),r=!0,l/(i-t)>.5))return}if(r||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(g.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:r}){const{unparsedVttFrags:o}=this;i===ae.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:r}),o.length&&(this.unparsedVttFrags=[],o.forEach(u=>{this.initPTS[u.frag.cc]?this.onFragLoaded(g.FRAG_LOADED,u):this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:u.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const n=i.textTracks[s];if(Qo(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:r}=t[e],o=this.getExistingTrack(n,r);if(o)i[e]=o,Wn(i[e]),ko(i[e],s);else{const u=this.createTextTrack("captions",n,r);u&&(u[e]=!0,i[e]=u)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(n=>{Wn(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Jo(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Wn(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===Ia);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(ho(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const r=this.media,o=r?Fr(r.textTracks):null;if(this.tracks.forEach((u,l)=>{let c;if(o){let h=null;for(let m=0;m<o.length;m++)if(o[m]&&Qo(o[m],u)){h=o[m],o[m]=null;break}h&&(c=h)}if(c)Wn(c);else{const h=Xo(u);c=this.createTextTrack(h,u.name,u.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){const u=o.filter(l=>l!==null).map(l=>l.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.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(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.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(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ae.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:r,lastSn:o}=this,{cc:u,sn:l}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&r&&(l!==o+1||l===o&&c!==this.lastPartIndex+1||u!==this.lastCc)&&(n.reset(),r.reset()),this.lastCc=u,this.lastSn=l,this.lastPartIndex=c}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===ae.SUBTITLE)if(s.byteLength){const n=i.decryptdata,r="stats"in t;if(n==null||!n.encrypted||r){const o=this.tracks[i.level],u=this.vttCCs;u[i.cc]||(u[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Ia?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;zo(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:r}=this,o=n.length-1;if(!n[i.cc]&&o===-1){r.push(e);return}const u=this.hls,l=(t=i.initSegment)!=null&&t.data?Bt(i.initSegment.data,new Uint8Array(s)).buffer:s;zc(l,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),u.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{const h=c.message==="Missing initPTS for VTT MPEGTS";h?r.push(e):this._fallbackToIMSC1(i,s),u.logger.log(`Failed to parse VTT cue: ${c}`),!(h&&o>i.cc)&&u.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||zo(t,this.initPTS[e.cc],()=>{i.textCodec=Ia,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>Po(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(g.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===ae.SUBTITLE&&this.onFragLoaded(g.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===ae.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(e,{startOffset:t,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(u=>_a(o[u],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(u=>_a(o[u],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const r=e[s++],o=127&e[s++],u=127&e[s++];if(o===0&&u===0)continue;if((4&r)!==0){const c=3&r;(c===0||c===1)&&(t[c].push(o),t[c].push(u))}}return t}}function Xo(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Qo(a,e){return!!a&&a.kind===Xo(e)&&ha(e,a)}function ed(a,e,t,i){return Math.min(e,i)-Math.max(a,t)}function Jo(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const td=/\s/,id={newCue(a,e,t,i){const s=[];let n,r,o,u,l;const c=self.VTTCue||self.TextTrackCue;for(let m=0;m<i.rows.length;m++)if(n=i.rows[m],o=!0,u=0,l="",!n.isEmpty()){var h;for(let S=0;S<n.chars.length;S++)td.test(n.chars[S].uchar)&&o?u++:(l+=n.chars[S].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;const v=Ho(l.trim()),y=Ra(e,t,v);a!=null&&(h=a.cues)!=null&&h.getCueById(y)||(r=new c(e,t,v),r.id=y,r.line=m+1,r.align="left",r.position=10+Math.min(80,Math.floor(u*8/32)*10),s.push(r))}return a&&s.length&&(s.sort((m,v)=>m.line==="auto"||v.line==="auto"?0:m.line>8&&v.line>8?v.line-m.line:m.line-v.line),s.forEach(m=>Po(a,m))),s}};function sd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(a){}return!1}const nd=/(\d+)-(\d+)\/(\d+)/;class el{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||ld,this.controller=new self.AbortController,this.stats=new Ye}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,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=rd(e,this.controller.signal),r=e.responseType==="arraybuffer",o=r?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&b(u)?u:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(ar(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var m;this.response=this.loader=h;const v=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(v-s.loading.start)),!h.ok){const{status:S,statusText:E}=h;throw new ud(E||"fetch, bad network response",S,h)}s.loading.first=v,s.total=od(h.headers)||s.total;const y=(m=this.callbacks)==null?void 0:m.onProgress;return y&&b(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,y):r?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var m,v;const y=this.response;if(!y)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const S=h[o];S&&(s.loaded=s.total=S);const E={url:y.url,data:h,code:y.status},x=(m=this.callbacks)==null?void 0:m.onProgress;x&&!b(t.highWaterMark)&&x(s,e,h,y),(v=this.callbacks)==null||v.onSuccess(E,s,e,y)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const v=h&&h.code||0,y=h?h.message:null;(m=this.callbacks)==null||m.onError({code:v,text:y},e,h?h.details:null,s)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){const r=new Ar,o=e.body.getReader(),u=()=>o.read().then(l=>{if(l.done)return r.dataLength&&n(t,i,r.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const c=l.value,h=c.length;return t.loaded+=h,h<s||r.dataLength?(r.push(c),r.dataLength>=s&&n(t,i,r.flush().buffer,e)):n(t,i,c.buffer,e),u()}).catch(()=>Promise.reject());return u()}}function rd(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Re({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function ad(a){const e=nd.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function od(a){const e=a.get("Content-Range");if(e){const i=ad(e);if(b(i))return i}const t=a.get("Content-Length");if(t)return parseInt(t)}function ld(a,e){return new self.Request(a.url,e)}class ud extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const cd=/^age:\s*[\d.]+\s*$/im;class tl{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ye,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)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,t.url)}).catch(r=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(r=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:r.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:r}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&b(n)?n:r,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.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),t.onreadystatechange=null,t.onprogress=null;const l=t.status,c=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const y=c!=null?c:t.response;if(y!=null){var r,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const S=t.responseType==="arraybuffer"?y.byteLength:y.length;i.loaded=i.total=S,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(r=this.callbacks)==null?void 0:r.onProgress;E&&E(i,e,y,t);const x={url:t.responseURL,data:y,code:l};(o=this.callbacks)==null||o.onSuccess(x,i,e,t);return}}const h=n.loadPolicy.errorRetry,m=i.retry,v={url:e.url,data:void 0,code:l};if(oi(h,m,!1,v))this.retry(h);else{var u;J.error(`${l} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(oi(e,t,!0))this.retry(e);else{var i;J.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(e){const{context:t,stats:i}=this;this.retryDelay=Ei(e,i.retry),i.retry++,J.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&cd.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const dd={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hd=z(z({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:tl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ct,bufferController:yu,capLevelController:ma,errorController:zi,fpsController:gc,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:Li,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:dd},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},fd()),{},{subtitleStreamController:Rc,subtitleTrackController:yc,timelineController:Jc,audioStreamController:mu,audioTrackController:gu,emeController:Hn,cmcdController:hc,contentSteeringController:mc,interstitialsController:Lc});function fd(){return{cueHandler:id,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 md(a,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=ka(a),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,u=e[o]===void 0,l=[];n.forEach(c=>{const h=`${r}Loading${c}`,m=e[h];if(m!==void 0&&u){l.push(h);const v=i[o].default;switch(e[o]={default:v},c){case"TimeOut":v.maxLoadTimeMs=m,v.maxTimeToFirstByteMs=m;break;case"MaxRetry":v.errorRetry.maxNumRetry=m,v.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":v.errorRetry.retryDelayMs=m,v.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=m,v.timeoutRetry.maxRetryDelayMs=m;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${Ce(e[o])}`)}),z(z({},i),e)}function ka(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(ka):Object.keys(a).reduce((e,t)=>(e[t]=ka(a[t]),e),{}):a}function gd(a,e){const t=a.loader;t!==el&&t!==tl?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):sd()&&(a.loader=el,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Gr=2,pd=.1,vd=.05,yd=100;class Ed extends Ps{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,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(g.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(yd),this.mediaSource=t.mediaSource;const i=this.media=t.media;ms(i,"playing",this.onMediaPlaying),ms(i,"waiting",this.onMediaWaiting),ms(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(xs(i,"playing",this.onMediaPlaying),xs(i,"waiting",this.onMediaWaiting),xs(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){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,u=this.seeking&&!o,l=!this.seeking&&o,c=r.paused&&!o||r.ended||r.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||u){u&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:!1}));return}if(!bt.getBuffered(r).length){this.nudgeRetry=0;return}const h=bt.bufferInfo(r,e,0),m=h.nextStart||0,v=this.fragmentTracker;if(o&&v&&this.hls){const re=il(this.hls.inFlightFragments,e),N=h.len>Gr,j=!m||re||m-e>Gr&&!v.getPartialFragment(e);if(N||j)return;this.moved=!1}const y=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(h.len>0)&&!m)return;const N=Math.max(m,h.start||0)-e,Y=!!(y!=null&&y.live)?y.targetduration*2:Gr,U=Vr(e,v);if(N>0&&(N<=Y||U)){r.paused||this._trySkipBufferHole(U);return}}const S=n.detectStallWithCurrentTimeMs,E=self.performance.now(),x=this.waiting;let R=this.stalled;if(R===null)if(x>0&&E-x<S)R=this.stalled=x;else{this.stalled=E;return}const L=E-R;if(!o&&(L>=S||x)&&this.hls){var P;if(((P=this.mediaSource)==null?void 0:P.readyState)==="ended"&&!(y!=null&&y.live)&&Math.abs(e-((y==null?void 0:y.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const V=bt.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(V,L,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(g.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){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&&e>s.end(0)){const n=bt.bufferedInfo(bt.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const r=bt.timeRangesToArray(s),o=bt.bufferedInfo(r,t,0).bufferedIndex;if(o>-1&&o<r.length-1){const u=bt.bufferedInfo(r,e,0).bufferedIndex,l=r[o].end,c=r[o+1].start;if((u===-1||u>o)&&c-l<1&&e-l<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${c} buffered index: ${u}`);this.warn(h.message),this.media.currentTime+=1e-6;let m=Vr(e,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const v=bt.bufferInfo(this.media,e,0);this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var s,n;const{fragmentTracker:r,media:o}=this,u=(s=this.hls)==null?void 0:s.config;if(!o||!r||!u)return;const l=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Vr(i,r);if((c||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;const h=e.buffered,m=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>u.maxBufferHole||e.nextStart&&(e.nextStart-i<u.maxBufferHole||m))&&(t>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const n=i.getFragAtPos(t,ae.MAIN),r=i.getFragAtPos(s,ae.MAIN);if(n&&r)return r.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ce(e)})`);this.warn(r.message),t.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;const r=s.currentTime,o=bt.bufferInfo(s,r,0),u=r<o.start?o.start:o.nextStart;if(u&&this.hls){const c=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&s.readyState<3,m=u-r;if(m>0&&(c||h)){if(m>n.maxBufferHole){let y=!1;if(r===0){const S=i.getAppendedFrag(0,ae.MAIN);S&&u<S.end&&(y=!0)}if(!y&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||il(this.hls.inFlightFragments,u))return 0;let E=!1,x=e.end;for(;x<u;){const R=Vr(x,i);if(R)x+=R.duration;else{E=!0;break}}if(E)return 0}}const v=Math.max(u+vd,r+pd);if(this.warn(`skipping hole, adjusting currentTime from ${r} to ${v}`),this.moved=!0,s.currentTime=v,!(e!=null&&e.gap)){const y=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${v}`),S={type:Z.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?S.part=e:S.frag=e),this.hls.trigger(g.ERROR,S)}return v}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,n=t==null?void 0:t.config;if(!i||!n)return 0;const r=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=r+(s+1)*n.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${r} to ${o}`);this.warn(u.message),i.currentTime=o,t.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${r} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function il(a,e){const t=sl(a.main);if(t&&t.start<=e)return t;const i=sl(a.audio);return i&&i.start<=e?i:null}function sl(a){if(!a)return null;switch(a.state){case ue.IDLE:case ue.STOPPED:case ue.ENDED:case ue.ERROR:return null}return a.frag}function Vr(a,e){return e.getAppendedFrag(a,ae.MAIN)||e.getPartialFragment(a)}const _d=.25;function Pa(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function Oa(a,e,t,i,s){let n=new a(e,t,"");try{n.value=i,s&&(n.type=s)}catch(r){n=new a(e,t,Ce(s?z({type:s},i):i))}return n}const Kr=(()=>{const a=Pa();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Sd{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(g.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Wn(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return ko(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Pa();if(r)for(let o=0;o<n.length;o++){const u=n[o].type;if(u===Ns.emsg&&!i||!s)continue;const l=ja(n[o].data),c=n[o].pts;let h=c+n[o].duration;h>Kr&&(h=Kr),h-c<=0&&(h=c+_d);for(let v=0;v<l.length;v++){const y=l[v];if(!za(y)){this.updateId3CueEnds(c,u);const S=Oa(r,c,h,y,u);S&&this.id3Track.addCue(S)}}}}updateId3CueEnds(e,t){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===t&&r.startTime<e&&r.endTime===Kr&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:u}}=r;if(n&&(o||u)){let l;s==="audio"?l=c=>c.type===Ns.audioId3&&u:s==="video"?l=c=>c.type===Ns.emsg&&o:l=c=>c.type===Ns.audioId3&&u||c.type===Ns.emsg&&o,_a(n,t,i,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:r}=this.hls.config;if(!n)return;const o=Pa();if(i&&s&&!r){const{fragmentStart:S,fragmentEnd:E}=e;let x=this.assetCue;x?(x.startTime=S,x.endTime=E):o&&(x=this.assetCue=Oa(o,S,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),x&&(x.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(x),x.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:u}=this,{dateRanges:l}=e,c=Object.keys(l);let h=this.dateRangeCuesAppended;if(u&&t){var m;if((m=u.cues)!=null&&m.length){const S=Object.keys(h).filter(E=>!c.includes(E));for(let E=S.length;E--;){var v;const x=S[E],R=(v=h[x])==null?void 0:v.cues;delete h[x],R&&Object.keys(R).forEach(L=>{const P=R[L];if(P){P.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(P)}catch(V){}}})}}else h=this.dateRangeCuesAppended={}}const y=e.fragments[e.fragments.length-1];if(!(c.length===0||!b(y==null?void 0:y.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let S=0;S<c.length;S++){const E=c[S],x=l[E],R=x.startTime,L=h[E],P=(L==null?void 0:L.cues)||{};let V=(L==null?void 0:L.durationKnown)||!1,re=Kr;const{duration:N,endDate:j}=x;if(j&&N!==null)re=R+N,V=!0;else if(x.endOnNext&&!V){const U=c.reduce((ce,He)=>{if(He!==x.id){const ut=l[He];if(ut.class===x.class&&ut.startDate>x.startDate&&(!ce||x.startDate<ce.startDate))return ut}return ce},null);U&&(re=U.startTime,V=!0)}const Y=Object.keys(x.attr);for(let U=0;U<Y.length;U++){const ce=Y[U];if(!gn(ce))continue;const He=P[ce];if(He)V&&!(L!=null&&L.durationKnown)?He.endTime=re:Math.abs(He.startTime-R)>.01&&(He.startTime=R,He.endTime=re);else if(o){let ut=x.attr[ce];Ys(ce)&&(ut=X(ut));const ct=Oa(o,R,re,{key:ce,data:ut},Ns.dateRange);ct&&(ct.id=E,this.id3Track.addCue(ct),P[ce]=ct,r&&(ce==="X-ASSET-LIST"||ce==="X-ASSET-URL")&&ct.addEventListener("enter",this.onEventCueEnter))}}h[E]={cues:P,dateRange:x,durationKnown:V}}}}}class Td{constructor(e){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:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.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 u=s-o,l=Math.min(this.maxLatency,o+i.targetduration);if(u<l&&u>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),m=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,v=Math.min(h,Math.max(1,m));this.changeMediaPlaybackRate(t,v)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:r,lowLatencyMode:o}=this.config,u=this.hls.userConfig;let l=o&&i||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.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(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=e-t-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 e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.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(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===A.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(e,t){var i,s;e.playbackRate!==t&&((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 ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class xd extends da{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],n={},r={};let o=!1,u=!1,l=!1;t.levels.forEach(c=>{const h=c.attrs;let{audioCodec:m,videoCodec:v}=c;m&&(c.audioCodec=m=gi(m,i)||void 0),v&&(v=c.videoCodec=Bi(v));const{width:y,height:S,unknownCodecs:E}=c;let x=E?E.length:0;if(E)for(let U=x;U--;){const ce=E[U];this.isAudioSupported(ce)?(c.audioCodec=m=m?`${m},${ce}`:ce,x--,Mi.audio[m.substring(0,4)]=2):this.isVideoSupported(ce)&&(c.videoCodec=v=v?`${v},${ce}`:ce,x--,Mi.video[v.substring(0,4)]=2)}if(o||(o=!!(y&&S)),u||(u=!!v),l||(l=!!m),x||m&&!this.isAudioSupported(m)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:R,"FRAME-RATE":L,"HDCP-LEVEL":P,"PATHWAY-ID":V,RESOLUTION:re,"VIDEO-RANGE":N}=h,Y=`${`${V||"."}-`}${c.bitrate}-${re}-${L}-${R}-${N}-${P}`;if(n[Y])if(n[Y].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const U=r[Y]+=1;c.attrs["PATHWAY-ID"]=new Array(U+1).join(".");const ce=this.createLevel(c);n[Y]=ce,s.push(ce)}else n[Y].addGroupId("audio",h.AUDIO),n[Y].addGroupId("text",h.SUBTITLES);else{const U=this.createLevel(c);n[Y]=U,r[Y]=1,s.push(U)}}),this.filterAndSortMediaOptions(s,t,o,u,l)}createLevel(e){const t=new et(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=p(s,[])}return t}isAudioSupported(e){return cs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return cs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){let r=[],o=[],u=e;if((i||s)&&n&&(u=u.filter(({videoCodec:E,videoRange:x,width:R,height:L})=>(!!E||!!(R&&L))&&gt(x))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",x=E;t.levels.length&&(x=`one or more CODECS in variant not supported: ${Ce(t.levels.map(L=>L.attrs.CODECS).filter((L,P,V)=>V.indexOf(L)===P))}`,this.warn(x),E+=` (${x})`);const R=new Error(E);this.hls.trigger(g.ERROR,{type:Z.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:R,reason:x})}});return}t.audioTracks&&(r=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),nl(r)),t.subtitles&&(o=t.subtitles,nl(o));const l=u.slice(0);u.sort((E,x)=>{if(E.attrs["HDCP-LEVEL"]!==x.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(x.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&E.height!==x.height)return E.height-x.height;if(E.frameRate!==x.frameRate)return E.frameRate-x.frameRate;if(E.videoRange!==x.videoRange)return we.indexOf(E.videoRange)-we.indexOf(x.videoRange);if(E.videoCodec!==x.videoCodec){const R=Ji(E.videoCodec),L=Ji(x.videoCodec);if(R!==L)return L-R}if(E.uri===x.uri&&E.codecSet!==x.codecSet){const R=Wi(E.codecSet),L=Wi(x.codecSet);if(R!==L)return L-R}return E.averageBitrate!==x.averageBitrate?E.averageBitrate-x.averageBitrate:0});let c=l[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==l.length)){for(let E=0;E<l.length;E++)if(l[E].pathwayId===u[0].pathwayId){c=l[E];break}}this._levels=u;for(let E=0;E<u.length;E++)if(u[E]===c){var h;this._firstLevel=E;const x=c.bitrate,R=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${x}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const L=Math.min(x,this.hls.config.abrEwmaDefaultEstimateMax);L>R&&R===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const m=n&&!s,v=this.hls.config,y=!!(v.audioStreamController&&v.audioTrackController),S={levels:u,audioTracks:r,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:y&&!m&&r.some(E=>!!E.url)};this.hls.trigger(g.MANIFEST_PARSED,S)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const c=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:c,reason:c.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,r=t[e],o=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=r,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${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 u={level:e,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(g.LEVEL_SWITCHING,u);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(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===xe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===ae.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,r=t.levelInfo;if(!r){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(r===this.currentLevel||t.withoutMultiVariant){r.fragmentError===0&&(r.loadError=0);let u=r.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(s,t,u)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],r=e.details,o=r==null?void 0:r.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||0:""):""} ${i}`),this.hls.trigger(g.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((n,r)=>r!==e?!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));Sr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.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(g.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(g.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function nl(a){const e={};a.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function rl(){return self.SourceBuffer||self.WebKitSourceBuffer}function al(){if(!dt())return!1;const e=rl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ad(){if(!al())return!1;const a=dt();return typeof(a==null?void 0:a.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Ti(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Ti(e,"audio"))))}function bd(){var a;const e=rl();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const Ld=100;class Rd extends _n{constructor(e,t,i){super(e,t,i,"stream-controller",ae.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||!b(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const r=this.getFwdBufferInfoAtPos(s,n,ae.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:e}=this;e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(Ld),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=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=ue.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ue.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ue.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=ue.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=ue.IDLE;break}break}case ue.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===ue.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;const r=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(o,u)){const S={};this.altAudio===2&&(S.type="video"),this.hls.trigger(g.BUFFER_EOS,S),this.state=ue.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=r.details;if(!l||this.state===ue.WAITING_LEVEL||this.waitForLive(r)){this.level=n,this.state=ue.WAITING_LEVEL,this.startFragRequested=!1;return}const c=o.len,h=this.getMaxBufferLength(r.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const m=this.backtrackFragment?this.backtrackFragment.start:o.end;let v=this.getNextFragment(m,l);if(this.couldBacktrack&&!this.fragPrevious&&v&&Ie(v)&&this.fragmentTracker.getState(v)!==Jt.OK){var y;const E=((y=this.backtrackFragment)!=null?y:v).sn-l.startSN,x=l.fragments[E-1];x&&v.cc===x.cc&&(v=x,this.fragmentTracker.removeFragment(x))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,m)){if(!v.gap){const E=this.audioOnly&&!this.altAudio?Fe.AUDIO:Fe.VIDEO,x=(E===Fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;x&&this.afterBufferFlushed(x,E,ae.MAIN)}v=this.getNextFragmentLoopLoading(v,l,o,ae.MAIN,h)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,r,m))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Jt.NOT_LOADED||s===Jt.PARTIAL?Ie(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ae.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.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(!t.paused&&e){const o=this.hls.nextLoadLevel,u=e[o],l=this.fragLastKbps;l&&this.fragCurrent?i=this.fragCurrent.duration*u.maxBitrate/(1e3*l)+1:i=0}else i=0;const r=this.getBufferedFrag(t.currentTime+i);if(r){const o=this.followingBufferedFrag(r);if(o){this.abortCurrentFrag();const u=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,c=Math.max(r.end,u+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 e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ue.KEY_LOADING:case ue.FRAG_LOADING:case ue.FRAG_LOADING_WAITING_RETRY:case ue.PARSING:case ue.PARSED:this.state=ue.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;ms(i,"playing",this.onMediaPlaying),ms(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(xs(i,"playing",this.onMediaPlaying),xs(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(g.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){const r=t.levels[n].audioCodec;r&&(i=i||r.indexOf("mp4a.40.2")!==-1,s=s||r.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!bd(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==ue.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=ue.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,r=t.level,o=t.details,u=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:${u}`);const l=t.levelInfo,c=this.fragCurrent;c&&(this.state===ue.FRAG_LOADING||this.state===ue.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=l.details)!=null&&i.live){var m;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(m=this.levelLastLoaded)==null?void 0:m.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,h),this.hls.trigger(g.LEVEL_UPDATED,{details:o,level:r}),this.state===ue.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=ue.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),r=e.fragmentStart,o=e.edge,u=n>=r-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!u)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!u&&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 h=bt.bufferInfo(i,s,0);if(!((l=h.buffered)!=null&&l.length)){i.currentTime=s;return}if(h.start<=n){i.currentTime=s;return}const{nextStart:v}=bt.bufferedInfo(h.buffered,n,0);v&&(i.currentTime=v)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{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 u=o.details;if(!u){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=u.PTSKnown||!u.live,h=(t=i.initSegment)==null?void 0:t.data,m=this._getAudioCodec(o),v=this.transmuxer=this.transmuxer||new uo(this.hls,ae.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),y=s?s.index:-1,S=y!==-1,E=new ts(i.level,i.sn,i.stats.chunkCount,n.byteLength,y,S),x=this.initPTS[i.cc];v.push(n,h,m,l,i,s,u.totalduration,c,E,x)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio===2;if(Pt(t.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(g.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(g.AUDIO_TRACK_SWITCHED,t)}),i.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(g.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Pt(t.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(e,t){const i=t.tracks;let s,n,r=!1;for(const o in i){const u=i[o];if(u.id==="main"){if(n=o,s=u,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(e,t){const{frag:i,part:s}=t,n=i.type===ae.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===ue.PARSED&&(this.state=ue.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Ie(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const r=this.media;r&&(!this._hasEnoughToStart&&bt.getBuffered(r).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=ue.ERROR;return}switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae.MAIN,t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ue.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===xe.LEVEL&&(this.state=ue.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=ue.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Fe.AUDIO||!this.altAudio){const i=(t===Fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,ae.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const n=this.getLevelDetails(),r=bt.getBuffered(e),o=r.length?r.start(0):0,u=o-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<l||this.loadingParts&&u<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),i+=u,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=ue.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(g.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===ue.STOPPED||this.state===ue.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,r=this.getCurrentContext(n);if(!r){this.resetWhenMissingContext(n);return}const{frag:o,part:u,level:l}=r,{video:c,text:h,id3:m,initSegment:v}=s,{details:y}=l,S=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=ue.PARSING,v){const E=v.tracks;if(E){const P=o.initSegment||o;if(this.unhandledEncryptionError(v,o))return;this._bufferInitSegment(l,E,P,n),i.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:P,id:t,tracks:E})}const x=v.initPTS,R=v.timescale,L=this.initPTS[o.cc];if(b(x)&&(!L||L.baseTime!==x||L.timescale!==R)){const P=v.trackId;this.initPTS[o.cc]={baseTime:x,timescale:R,trackId:P},i.trigger(g.INIT_PTS_FOUND,{frag:o,id:t,initPTS:x,timescale:R,trackId:P})}}if(c&&y){S&&c.type==="audiovideo"&&this.logMuxedErr(o);const E=y.fragments[o.sn-1-y.startSN],x=o.sn===y.startSN,R=!E||o.cc>E.cc;if(s.independent!==!1){const{startPTS:L,endPTS:P,startDTS:V,endDTS:re}=c;if(u)u.elementaryStreams[c.type]={startPTS:L,endPTS:P,startDTS:V,endDTS:re};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!R&&(this.couldBacktrack=!0),c.dropped&&c.independent){const N=this.getMainFwdBufferInfo(),j=(N?N.end:this.getLoadPosition())+this.config.maxBufferHole,Y=c.firstKeyFramePTS?c.firstKeyFramePTS:L;if(!x&&j<Y-this.config.maxBufferHole&&!R){this.backtrack(o);return}else R&&(o.gap=!0);o.setElementaryStreamInfo(c.type,o.start,P,o.start,re,!0)}else x&&L-(y.appliedTimelineOffset||0)>Gr&&(o.gap=!0);o.setElementaryStreamInfo(c.type,L,P,V,re),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,u,n,x||R)}else if(x||R)o.gap=!0;else{this.backtrack(o);return}}if(S){const{startPTS:E,endPTS:x,startDTS:R,endDTS:L}=S;u&&(u.elementaryStreams[Fe.AUDIO]={startPTS:E,endPTS:x,startDTS:R,endDTS:L}),o.setElementaryStreamInfo(Fe.AUDIO,E,x,R,L),this.bufferFragmentData(S,o,u,n)}if(y&&m!=null&&m.samples.length){const E={id:t,frag:o,details:y,samples:m.samples};i.trigger(g.FRAG_PARSING_METADATA,E)}if(y&&h){const E={id:t,frag:o,details:y,samples:h.samples};i.trigger(g.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${Ie(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==ue.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:r,audiovideo:o}=t;if(n){const l=e.audioCodec;let c=yi(n.codec,l);c==="mp4a"&&(c="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");const m=n.metadata;m&&"channelCount"in m&&(m.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),l&&l!==c&&this.log(`Swapping manifest audio codec "${l}" for "${c}"`),n.levelCodec=c,n.id=ae.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(r){r.levelCodec=e.videoCodec,r.id=ae.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]=[${e.videoCodec||""}/${l}]${r.codec!==l?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const u=Object.keys(t);if(u.length){if(this.hls.trigger(g.BUFFER_CODECS,t),!this.hls)return;u.forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(g.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ae.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=ue.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(bt.isBuffered(e,i)?t=this.getAppendedFrag(i):bt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(g.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(g.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return b(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(b(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?zt(null,i.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const r=n+(t-s.start)*1e3;return new Date(r)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Id extends De{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=A.KEY_LOAD_ERROR,i,s,n){return new Vi({type:Z.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){const r=t[s];if(e.cc<=r.cc&&(!Ie(e)||!Ie(r)||e.sn<r.sn)||!i&&s==n-1)return this.emeController.selectKeySystemFormat(r).then(o=>{if(!this.emeController)return;r.setKeyFormat(o);const u=on(o);if(u)return this.emeController.getKeySystemAccess([u])})}if(this.config.requireKeySystemAccessOnStart){const s=Tt(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,c))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));const o=Fa(n);let u=this.keyIdToKeyInfo[o];if((i=u)!=null&&i.decryptdata.key)return n.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if((s=u)!=null&&s.keyLoadPromise){var l;switch((l=u.mediaKeySessionContext)==null?void 0:l.keyStatus){case"usable":case"usable-in-future":return u.keyLoadPromise.then(h=>{const{keyInfo:m}=h;return n.key=m.decryptdata.key,{frag:e,keyInfo:m}})}}switch(this.log(`Loading key ${te(n.keyId||[])} from ${e.type} ${e.level}`),u=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n.data&&(n.data.frag=t),n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((r,o)=>{const u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,v,y,S)=>{const{frag:E,keyInfo:x,url:R}=y,L=Fa(x.decryptdata)||R;if(!E.decryptdata||x!==this.keyIdToKeyInfo[L])return o(this.createKeyLoadError(E,A.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),S));x.decryptdata.key=E.decryptdata.key=new Uint8Array(m.data),E.keyLoader=null,x.loader=null,r({frag:E,keyInfo:x})},onError:(m,v,y,S)=>{this.resetLoader(v),o(this.createKeyLoadError(t,A.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),y,z({url:u.url,data:void 0},m)))},onTimeout:(m,v,y)=>{this.resetLoader(v),o(this.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(m,v,y)=>{this.resetLoader(v),o(this.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};n.load(u,c,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);const r=Fa(i.decryptdata)||s;delete this.keyIdToKeyInfo[r],n&&n.destroy()}}function Fa(a){const e=a.keyId;return e?te(e):a.uri}function ol(a){const{type:e}=a;switch(e){case xe.AUDIO_TRACK:return ae.AUDIO;case xe.SUBTITLE_TRACK:return ae.SUBTITLE;default:return ae.MAIN}}function Ma(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Cd{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,r=new n(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:xe.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:r,deliveryDirectives:o,levelInfo:u}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:xe.LEVEL,url:r,deliveryDirectives:o,levelOrTrack:u})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:xe.AUDIO_TRACK,url:n,deliveryDirectives:r,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:xe.SUBTITLE_TRACK,url:n,deliveryDirectives:r,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[xe.LEVEL];if(i){const s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[xe.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const l=this.hls.logger,c=s.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===xe.MANIFEST?n=i.manifestLoadPolicy.default:n=Re({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),b((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===xe.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===xe.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===xe.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const c=l.partTarget,h=l.targetduration;if(c&&h){const m=Math.max(c*3,h*.8)*1e3;n=Re({},n,{maxTimeToFirstByteMs:Math.min(m,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,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},u={onSuccess:(l,c,h,m)=>{const v=this.getInternalLoader(h);this.resetInternalLoader(h.type);const y=l.data;if(y.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,h,new Error("no EXTM3U delimiter"),m||null,c);return}c.parsing.start=performance.now(),Hs.isMediaPlaylist(y)||h.type!==xe.MANIFEST?this.handleTrackOrLevelPlaylist(l,c,h,m||null,v):this.handleMasterPlaylist(l,c,h,m)},onError:(l,c,h,m)=>{this.handleNetworkError(c,h,!1,l,m)},onTimeout:(l,c,h)=>{this.handleNetworkError(c,h,!0,void 0,l)}};s.load(e,o,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const n=this.hls,r=e.data,o=Ma(e,i),u=Hs.parseMasterPlaylist(r,o);if(u.playlistParsingError){this.handleManifestParsingError(e,i,u.playlistParsingError,s,t);return}const{contentSteering:l,levels:c,sessionData:h,sessionKeys:m,startTimeOffset:v,variableList:y}=u;this.variableList=y;const{AUDIO:S=[],SUBTITLES:E,"CLOSED-CAPTIONS":x}=Hs.parseMasterPlaylistMedia(r,o,u);S.length&&!S.some(L=>!L.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"),S.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ai({}),bitrate:0,url:""})),n.trigger(g.MANIFEST_LOADED,{levels:c,audioTracks:S,subtitles:E,captions:x,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:h,sessionKeys:m,startTimeOffset:v,variableList:y})}handleTrackOrLevelPlaylist(e,t,i,s,n){const r=this.hls,{id:o,level:u,type:l}=i,c=Ma(e,i),h=b(u)?u:b(o)?o:0,m=ol(i),v=Hs.parseLevelPlaylist(e.data,c,h,m,0,this.variableList);if(l===xe.MANIFEST){const y={attrs:new ai({}),bitrate:0,details:v,name:"",url:c};v.requestScheduled=t.loading.start+yr(v,0),r.trigger(g.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=v,this.handlePlaylistLoaded(v,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(g.ERROR,{type:Z.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:t.type===xe.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let r=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===xe.LEVEL?r+=`: ${e.level} id: ${e.id}`:(e.type===xe.AUDIO_TRACK||e.type===xe.SUBTITLE_TRACK)&&(r+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let u=A.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case xe.MANIFEST:u=i?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,l=!0;break;case xe.LEVEL:u=i?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,l=!1;break;case xe.AUDIO_TRACK:u=i?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case xe.SUBTITLE_TRACK:u=i?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,l=!1;break}c&&this.resetInternalLoader(e.type);const h={type:Z.NETWORK_ERROR,details:u,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){const m=(t==null?void 0:t.url)||e.url;h.response=z({url:m,data:void 0},s)}this.hls.trigger(g.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,r){const o=this.hls,{type:u,level:l,id:c,groupId:h,deliveryDirectives:m}=s,v=Ma(t,s),y=ol(s),S=typeof s.level=="number"&&y===ae.MAIN?l:void 0;if(!e.fragments.length){const x=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(g.ERROR,{type:Z.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:x,reason:x.message,response:t,context:s,level:S,parent:y,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(g.ERROR,{type:Z.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:E,reason:E.message,response:t,context:s,level:S,parent:y,networkDetails:n,stats:i});return}e.playlistParsingError=null}switch(e.live&&r&&(r.getCacheAge&&(e.ageHeader=r.getCacheAge()||0),(!r.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case xe.MANIFEST:case xe.LEVEL:o.trigger(g.LEVEL_LOADED,{details:e,levelInfo:s.levelOrTrack||o.levels[0],level:S||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:m,withoutMultiVariant:u===xe.MANIFEST});break;case xe.AUDIO_TRACK:o.trigger(g.AUDIO_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:m});break;case xe.SUBTITLE_TRACK:o.trigger(g.SUBTITLE_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:m});break}}}class Rn{static get version(){return ir}static isMSESupported(){return al()}static isSupported(){return Ad()}static getMediaSource(){return dt()}static get Events(){return g}static get MetadataSchema(){return Ns}static get ErrorTypes(){return Z}static get ErrorDetails(){return A}static get DefaultConfig(){return Rn.defaultConfig?Rn.defaultConfig:hd}static set DefaultConfig(e){Rn.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Qr,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 t=this.logger=Xe(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=md(Rn.DefaultConfig,e,t);this.userConfig=e,i.progressive&&gd(i,t);const{abrController:s,bufferController:n,capLevelController:r,errorController:o,fpsController:u}=i,l=new o(this),c=this.abrController=new s(this),h=new es(this),m=i.interstitialsController,v=m?this.interstitialsController=new m(this,Rn):null,y=this.bufferController=new n(this,h),S=this.capLevelController=new r(this),E=new u(this),x=new Cd(this),R=i.contentSteeringController,L=R?new R(this):null,P=this.levelController=new xd(this,L),V=new Sd(this),re=new Id(this.config,this.logger),N=this.streamController=new Rd(this,h,re),j=this.gapController=new Ed(this,h);S.setStreamController(N),E.setStreamController(N);const Y=[x,P,N];v&&Y.splice(1,0,v),L&&Y.splice(1,0,L),this.networkControllers=Y;const U=[c,y,j,S,E,V,h];this.audioTrackController=this.createController(i.audioTrackController,Y);const ce=i.audioStreamController;ce&&Y.push(this.audioStreamController=new ce(this,h,re)),this.subtitleTrackController=this.createController(i.subtitleTrackController,Y);const He=i.subtitleStreamController;He&&Y.push(this.subtititleStreamController=new He(this,h,re)),this.createController(i.timelineController,U),re.emeController=this.emeController=this.createController(i.emeController,U),this.cmcdController=this.createController(i.cmcdController,U),this.latencyController=this.createController(Td,U),this.coreComponents=U,Y.push(l);const ut=l.onErrorOut;typeof ut=="function"&&this.on(g.ERROR,ut,l),this.on(g.MANIFEST_LOADED,x.onManifestLoaded,x)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===g.ERROR;this.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(g.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(g.ERROR,{type:Z.OTHER_ERROR,details:A.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 t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(g.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(g.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(g.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=me.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(g.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ae.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ae.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ae.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Ec()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ht(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const r=e[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(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}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(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=k(t);return T(e,i,navigator.mediaCapabilities)}}Rn.defaultConfig=void 0}}]);
}());