@vkontakte/videoplayer-core 2.0.84 → 2.0.86-dev.f2e1ec4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.84
3
- * Mon, 24 Apr 2023 14:02:41 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-84/doc/
2
+ * @vkontakte/videoplayer-core v2.0.86-dev.f2e1ec4.0
3
+ * Wed, 10 May 2023 11:32:26 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-86/doc/
5
5
  */
6
- import{ValueSubject as y,Subject as C,Subscription as ie,isNonNullable as _,ErrorCategory as L,isNullable as J,fromEvent as M,assertNever as O,merge as x,tap as Nr,map as $,observableFrom as ke,filterChanged as pe,assertNonNullable as P,debounce as xe,timeout as xo,combine as Ze,once as ge,mapTo as At,filter as q,now as he,Observable as li,abortable as Be,getExponentialDelay as Br,interval as Oo,Logger as No}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as rv,Subject as av,Subscription as nv,ValueSubject as ov}from"@vkontakte/videoplayer-shared/es2018.esm.js";import Bo from"lodash/debounce.js";const Mo="2.0.84",Uo="es2018.esm.js";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var b;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var _e;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Ee;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ee||(Ee={}));var di;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(di||(di={}));var V;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(V||(V={}));var Fo=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vo{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(Ee.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new y(Ee.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Fo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(M(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return O(r.sessionState)}})).add(x(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nr(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),ke([i.getCastState()])).pipe(pe(),$(Ho),Nr(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ee.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(J(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ee.CONNECTED?_(this.connection$.getValue())?Ee.CONNECTED:Ee.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Ho=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ee.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ee.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ee.CONNECTING;case cast.framework.CastState.CONNECTED:return Ee.CONNECTED;default:return O(s)}};var Mr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},it=function(s){try{return!!s()}catch(e){return!0}},Go=it,Zi=!Go(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),dn=Zi,un=Function.prototype,Xs=un.call,Yo=dn&&un.bind.bind(Xs,Xs),st=dn?Yo:function(s){return function(){return Xs.apply(s,arguments)}},ln=st,qo=ln({}.toString),zo=ln("".slice),es=function(s){return zo(qo(s),8,-1)},jo=st,Wo=it,Qo=es,fs=Object,Jo=jo("".split),Ko=Wo(function(){return!fs("z").propertyIsEnumerable(0)})?function(s){return Qo(s)=="String"?Jo(s,""):fs(s)}:fs,ts=function(s){return s==null},Xo=ts,Zo=TypeError,lr=function(s){if(Xo(s))throw Zo("Can't call method on "+s);return s},ed=Ko,td=lr,ci=function(s){return ed(td(s))},id=function(){},Gt={},Ti=function(s){return s&&s.Math==Math&&s},ze=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof Mr=="object"&&Mr)||function(){return this}()||Function("return this")(),Zs=typeof document=="object"&&document.all,sd=typeof Zs=="undefined"&&Zs!==void 0,cn={all:Zs,IS_HTMLDDA:sd},hn=cn,rd=hn.all,Oe=hn.IS_HTMLDDA?function(s){return typeof s=="function"||s===rd}:function(s){return typeof s=="function"},ad=ze,nd=Oe,Ur=ad.WeakMap,od=nd(Ur)&&/native code/.test(String(Ur)),Fr=Oe,fn=cn,dd=fn.all,wt=fn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Fr(s)||s===dd}:function(s){return typeof s=="object"?s!==null:Fr(s)},ud=it,ft=!ud(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Yt={},ld=ze,Vr=wt,er=ld.document,cd=Vr(er)&&Vr(er.createElement),pn=function(s){return cd?er.createElement(s):{}},hd=ft,fd=it,pd=pn,mn=!hd&&!fd(function(){return Object.defineProperty(pd("div"),"a",{get:function(){return 7}}).a!=7}),md=ft,vd=it,vn=md&&vd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Sd=wt,gd=String,bd=TypeError,_t=function(s){if(Sd(s))return s;throw bd(gd(s)+" is not an object")},yd=Zi,Ei=Function.prototype.call,rt=yd?Ei.bind(Ei):function(){return Ei.apply(Ei,arguments)},cr={},ps=cr,ms=ze,Td=Oe,Hr=function(s){return Td(s)?s:void 0},hr=function(s,e){return arguments.length<2?Hr(ps[s])||Hr(ms[s]):ps[s]&&ps[s][e]||ms[s]&&ms[s][e]},Ed=st,fr=Ed({}.isPrototypeOf),$d=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Sn=ze,vs=$d,Gr=Sn.process,Yr=Sn.Deno,qr=Gr&&Gr.versions||Yr&&Yr.version,zr=qr&&qr.v8,Ne,Gi;zr&&(Ne=zr.split("."),Gi=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!Gi&&vs&&(Ne=vs.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=vs.match(/Chrome\/(\d+)/),Ne&&(Gi=+Ne[1])));var Ad=Gi,jr=Ad,wd=it,gn=!!Object.getOwnPropertySymbols&&!wd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&jr&&jr<41}),_d=gn,bn=_d&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kd=hr,Pd=Oe,Rd=fr,Id=bn,Dd=Object,yn=Id?function(s){return typeof s=="symbol"}:function(s){var e=kd("Symbol");return Pd(e)&&Rd(e.prototype,Dd(s))},Ld=String,pr=function(s){try{return Ld(s)}catch(e){return"Object"}},Cd=Oe,xd=pr,Od=TypeError,mr=function(s){if(Cd(s))return s;throw Od(xd(s)+" is not a function")},Nd=mr,Bd=ts,is=function(s,e){var t=s[e];return Bd(t)?void 0:Nd(t)},Ss=rt,gs=Oe,bs=wt,Md=TypeError,Ud=function(s,e){var t,i;if(e==="string"&&gs(t=s.toString)&&!bs(i=Ss(t,s))||gs(t=s.valueOf)&&!bs(i=Ss(t,s))||e!=="string"&&gs(t=s.toString)&&!bs(i=Ss(t,s)))return i;throw Md("Can't convert object to primitive value")},Yi={},Fd={get exports(){return Yi},set exports(s){Yi=s}},Vd=!0,Wr=ze,Hd=Object.defineProperty,Gd=function(s,e){try{Hd(Wr,s,{value:e,configurable:!0,writable:!0})}catch(t){Wr[s]=e}return e},Yd=ze,qd=Gd,Qr="__core-js_shared__",zd=Yd[Qr]||qd(Qr,{}),Tn=zd,Jr=Tn;(Fd.exports=function(s,e){return Jr[s]||(Jr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var jd=lr,Wd=Object,ss=function(s){return Wd(jd(s))},Qd=st,Jd=ss,Kd=Qd({}.hasOwnProperty),at=Object.hasOwn||function(e,t){return Kd(Jd(e),t)},Xd=st,Zd=0,eu=Math.random(),tu=Xd(1 .toString),En=function(s){return"Symbol("+(s===void 0?"":s)+")_"+tu(++Zd+eu,36)},iu=ze,su=Yi,Kr=at,ru=En,au=gn,nu=bn,Nt=iu.Symbol,ys=su("wks"),ou=nu?Nt.for||Nt:Nt&&Nt.withoutSetter||ru,Ue=function(s){return Kr(ys,s)||(ys[s]=au&&Kr(Nt,s)?Nt[s]:ou("Symbol."+s)),ys[s]},du=rt,Xr=wt,Zr=yn,uu=is,lu=Ud,cu=Ue,hu=TypeError,fu=cu("toPrimitive"),pu=function(s,e){if(!Xr(s)||Zr(s))return s;var t=uu(s,fu),i;if(t){if(e===void 0&&(e="default"),i=du(t,s,e),!Xr(i)||Zr(i))return i;throw hu("Can't convert object to primitive value")}return e===void 0&&(e="number"),lu(s,e)},mu=pu,vu=yn,vr=function(s){var e=mu(s,"string");return vu(e)?e:e+""},Su=ft,gu=mn,bu=vn,$i=_t,ea=vr,yu=TypeError,Ts=Object.defineProperty,Tu=Object.getOwnPropertyDescriptor,Es="enumerable",$s="configurable",As="writable";Yt.f=Su?bu?function(e,t,i){if($i(e),t=ea(t),$i(i),typeof e=="function"&&t==="prototype"&&"value"in i&&As in i&&!i[As]){var r=Tu(e,t);r&&r[As]&&(e[t]=i.value,i={configurable:$s in i?i[$s]:r[$s],enumerable:Es in i?i[Es]:r[Es],writable:!1})}return Ts(e,t,i)}:Ts:function(e,t,i){if($i(e),t=ea(t),$i(i),gu)try{return Ts(e,t,i)}catch(r){}if("get"in i||"set"in i)throw yu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var rs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Eu=ft,$u=Yt,Au=rs,hi=Eu?function(s,e,t){return $u.f(s,e,Au(1,t))}:function(s,e,t){return s[e]=t,s},wu=Yi,_u=En,ta=wu("keys"),Sr=function(s){return ta[s]||(ta[s]=_u(s))},gr={},ku=od,$n=ze,Pu=wt,Ru=hi,ws=at,_s=Tn,Iu=Sr,Du=gr,ia="Object already initialized",tr=$n.TypeError,Lu=$n.WeakMap,qi,ui,zi,Cu=function(s){return zi(s)?ui(s):qi(s,{})},xu=function(s){return function(e){var t;if(!Pu(e)||(t=ui(e)).type!==s)throw tr("Incompatible receiver, "+s+" required");return t}};if(ku||_s.state){var Ge=_s.state||(_s.state=new Lu);Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,qi=function(s,e){if(Ge.has(s))throw tr(ia);return e.facade=s,Ge.set(s,e),e},ui=function(s){return Ge.get(s)||{}},zi=function(s){return Ge.has(s)}}else{var Dt=Iu("state");Du[Dt]=!0,qi=function(s,e){if(ws(s,Dt))throw tr(ia);return e.facade=s,Ru(s,Dt,e),e},ui=function(s){return ws(s,Dt)?s[Dt]:{}},zi=function(s){return ws(s,Dt)}}var Ou={set:qi,get:ui,has:zi,enforce:Cu,getterFor:xu},Nu=Zi,An=Function.prototype,sa=An.apply,ra=An.call,Bu=typeof Reflect=="object"&&Reflect.apply||(Nu?ra.bind(sa):function(){return ra.apply(sa,arguments)}),Mu=es,Uu=st,wn=function(s){if(Mu(s)==="Function")return Uu(s)},_n={},kn={},Pn={}.propertyIsEnumerable,Rn=Object.getOwnPropertyDescriptor,Fu=Rn&&!Pn.call({1:2},1);kn.f=Fu?function(e){var t=Rn(this,e);return!!t&&t.enumerable}:Pn;var Vu=ft,Hu=rt,Gu=kn,Yu=rs,qu=ci,zu=vr,ju=at,Wu=mn,aa=Object.getOwnPropertyDescriptor;_n.f=Vu?aa:function(e,t){if(e=qu(e),t=zu(t),Wu)try{return aa(e,t)}catch(i){}if(ju(e,t))return Yu(!Hu(Gu.f,e,t),e[t])};var Qu=it,Ju=Oe,Ku=/#|\.prototype\./,fi=function(s,e){var t=Zu[Xu(s)];return t==tl?!0:t==el?!1:Ju(e)?Qu(e):!!e},Xu=fi.normalize=function(s){return String(s).replace(Ku,".").toLowerCase()},Zu=fi.data={},el=fi.NATIVE="N",tl=fi.POLYFILL="P",il=fi,na=wn,sl=mr,rl=Zi,al=na(na.bind),In=function(s,e){return sl(s),e===void 0?s:rl?al(s,e):function(){return s.apply(e,arguments)}},Ai=ze,nl=Bu,ol=wn,dl=Oe,ul=_n.f,ll=il,Lt=cr,cl=In,Ct=hi,oa=at,hl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return nl(s,this,arguments)};return e.prototype=s.prototype,e},as=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Ai:r?Ai[t]:(Ai[t]||{}).prototype,o=i?Lt:Lt[t]||Ct(Lt,t,{})[t],u=o.prototype,d,l,c,h,p,v,f,S,g;for(h in e)d=ll(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&oa(n,h),v=o[h],l&&(s.dontCallGetSet?(g=ul(n,h),f=g&&g.value):f=n[h]),p=l&&f?f:e[h],!(l&&typeof v==typeof p)&&(s.bind&&l?S=cl(p,Ai):s.wrap&&l?S=hl(p):a&&dl(p)?S=ol(p):S=p,(s.sham||p&&p.sham||v&&v.sham)&&Ct(S,"sham",!0),Ct(o,h,S),a&&(c=t+"Prototype",oa(Lt,c)||Ct(Lt,c,{}),Ct(Lt[c],h,p),s.real&&u&&(d||!u[h])&&Ct(u,h,p)))},ir=ft,fl=at,Dn=Function.prototype,pl=ir&&Object.getOwnPropertyDescriptor,br=fl(Dn,"name"),ml=br&&function(){}.name==="something",vl=br&&(!ir||ir&&pl(Dn,"name").configurable),Sl={EXISTS:br,PROPER:ml,CONFIGURABLE:vl},Ln={},gl=Math.ceil,bl=Math.floor,yl=Math.trunc||function(e){var t=+e;return(t>0?bl:gl)(t)},Tl=yl,yr=function(s){var e=+s;return e!==e||e===0?0:Tl(e)},El=yr,$l=Math.max,Al=Math.min,wl=function(s,e){var t=El(s);return t<0?$l(t+e,0):Al(t,e)},_l=yr,kl=Math.min,Pl=function(s){return s>0?kl(_l(s),9007199254740991):0},Rl=Pl,Tr=function(s){return Rl(s.length)},Il=ci,Dl=wl,Ll=Tr,da=function(s){return function(e,t,i){var r=Il(e),a=Ll(r),n=Dl(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},Cl={includes:da(!0),indexOf:da(!1)},xl=st,ks=at,Ol=ci,Nl=Cl.indexOf,Bl=gr,ua=xl([].push),Ml=function(s,e){var t=Ol(s),i=0,r=[],a;for(a in t)!ks(Bl,a)&&ks(t,a)&&ua(r,a);for(;e.length>i;)ks(t,a=e[i++])&&(~Nl(r,a)||ua(r,a));return r},Cn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ul=Ml,Fl=Cn,Vl=Object.keys||function(e){return Ul(e,Fl)},Hl=ft,Gl=vn,Yl=Yt,ql=_t,zl=ci,jl=Vl;Ln.f=Hl&&!Gl?Object.defineProperties:function(e,t){ql(e);for(var i=zl(t),r=jl(t),a=r.length,n=0,o;a>n;)Yl.f(e,o=r[n++],i[o]);return e};var Wl=hr,Ql=Wl("document","documentElement"),Jl=_t,Kl=Ln,la=Cn,Xl=gr,Zl=Ql,ec=pn,tc=Sr,ca=">",ha="<",sr="prototype",rr="script",xn=tc("IE_PROTO"),Ps=function(){},On=function(s){return ha+rr+ca+s+ha+"/"+rr+ca},fa=function(s){s.write(On("")),s.close();var e=s.parentWindow.Object;return s=null,e},ic=function(){var s=ec("iframe"),e="java"+rr+":",t;return s.style.display="none",Zl.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(On("document.F=Object")),t.close(),t.F},wi,Mi=function(){try{wi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&wi?fa(wi):ic():fa(wi);for(var s=la.length;s--;)delete Mi[sr][la[s]];return Mi()};Xl[xn]=!0;var Nn=Object.create||function(e,t){var i;return e!==null?(Ps[sr]=Jl(e),i=new Ps,Ps[sr]=null,i[xn]=e):i=Mi(),t===void 0?i:Kl.f(i,t)},sc=it,rc=!sc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),ac=at,nc=Oe,oc=ss,dc=Sr,uc=rc,pa=dc("IE_PROTO"),ar=Object,lc=ar.prototype,Bn=uc?ar.getPrototypeOf:function(s){var e=oc(s);if(ac(e,pa))return e[pa];var t=e.constructor;return nc(t)&&e instanceof t?t.prototype:e instanceof ar?lc:null},cc=hi,Mn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:cc(s,e,t),s},hc=it,fc=Oe,pc=wt,mc=Nn,ma=Bn,vc=Mn,Sc=Ue,nr=Sc("iterator"),Un=!1,et,Rs,Is;[].keys&&(Is=[].keys(),"next"in Is?(Rs=ma(ma(Is)),Rs!==Object.prototype&&(et=Rs)):Un=!0);var gc=!pc(et)||hc(function(){var s={};return et[nr].call(s)!==s});gc?et={}:et=mc(et);fc(et[nr])||vc(et,nr,function(){return this});var Fn={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Un},bc=Ue,yc=bc("toStringTag"),Vn={};Vn[yc]="z";var Er=String(Vn)==="[object z]",Tc=Er,Ec=Oe,Ui=es,$c=Ue,Ac=$c("toStringTag"),wc=Object,_c=Ui(function(){return arguments}())=="Arguments",kc=function(s,e){try{return s[e]}catch(t){}},ns=Tc?Ui:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kc(e=wc(s),Ac))=="string"?t:_c?Ui(e):(i=Ui(e))=="Object"&&Ec(e.callee)?"Arguments":i},Pc=Er,Rc=ns,Ic=Pc?{}.toString:function(){return"[object "+Rc(this)+"]"},Dc=Er,Lc=Yt.f,Cc=hi,xc=at,Oc=Ic,Nc=Ue,va=Nc("toStringTag"),Hn=function(s,e,t,i){if(s){var r=t?s:s.prototype;xc(r,va)||Lc(r,va,{configurable:!0,value:e}),i&&!Dc&&Cc(r,"toString",Oc)}},Bc=Fn.IteratorPrototype,Mc=Nn,Uc=rs,Fc=Hn,Vc=Gt,Hc=function(){return this},Gc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Mc(Bc,{next:Uc(+!i,t)}),Fc(s,r,!1,!0),Vc[r]=Hc,s},Yc=as,qc=rt,Gn=Sl,zc=Gc,jc=Bn,Wc=Hn,Sa=Mn,Qc=Ue,ga=Gt,Yn=Fn,Jc=Gn.PROPER;Gn.CONFIGURABLE;Yn.IteratorPrototype;var _i=Yn.BUGGY_SAFARI_ITERATORS,Ds=Qc("iterator"),ba="keys",ki="values",ya="entries",Kc=function(){return this},Xc=function(s,e,t,i,r,a,n){zc(t,e,i);var o=function(g){if(g===r&&h)return h;if(!_i&&g in l)return l[g];switch(g){case ba:return function(){return new t(this,g)};case ki:return function(){return new t(this,g)};case ya:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ds]||l["@@iterator"]||r&&l[r],h=!_i&&c||o(r),p=e=="Array"&&l.entries||c,v,f,S;if(p&&(v=jc(p.call(new s)),v!==Object.prototype&&v.next&&(Wc(v,u,!0,!0),ga[u]=Kc)),Jc&&r==ki&&c&&c.name!==ki&&(d=!0,h=function(){return qc(c,this)}),r)if(f={values:o(ki),keys:a?h:o(ba),entries:o(ya)},n)for(S in f)(_i||d||!(S in l))&&Sa(l,S,f[S]);else Yc({target:e,proto:!0,forced:_i||d},f);return n&&l[Ds]!==h&&Sa(l,Ds,h,{name:r}),ga[e]=h,f},Zc=function(s,e){return{value:s,done:e}},eh=ci,$r=id,Ta=Gt,qn=Ou,th=Yt.f,ih=Xc,Pi=Zc,sh=Vd,rh=ft,zn="Array Iterator",ah=qn.set,nh=qn.getterFor(zn);ih(Array,"Array",function(s,e){ah(this,{type:zn,target:eh(s),index:0,kind:e})},function(){var s=nh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Pi(void 0,!0)):t=="keys"?Pi(i,!1):t=="values"?Pi(e[i],!1):Pi([i,e[i]],!1)},"values");var Ea=Ta.Arguments=Ta.Array;$r();$r();$r();if(!sh&&rh&&Ea.name!=="values")try{th(Ea,"name",{value:"values"})}catch(s){}var oh=Ue,dh=Gt,uh=oh("iterator"),lh=Array.prototype,ch=function(s){return s!==void 0&&(dh.Array===s||lh[uh]===s)},hh=ns,$a=is,fh=ts,ph=Gt,mh=Ue,vh=mh("iterator"),jn=function(s){if(!fh(s))return $a(s,vh)||$a(s,"@@iterator")||ph[hh(s)]},Sh=rt,gh=mr,bh=_t,yh=pr,Th=jn,Eh=TypeError,$h=function(s,e){var t=arguments.length<2?Th(s):e;if(gh(t))return bh(Sh(t,s));throw Eh(yh(s)+" is not iterable")},Ah=rt,Aa=_t,wh=is,_h=function(s,e,t){var i,r;Aa(s);try{if(i=wh(s,"return"),!i){if(e==="throw")throw t;return t}i=Ah(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Aa(i),t},kh=In,Ph=rt,Rh=_t,Ih=pr,Dh=ch,Lh=Tr,wa=fr,Ch=$h,xh=jn,_a=_h,Oh=TypeError,Fi=function(s,e){this.stopped=s,this.result=e},ka=Fi.prototype,Nh=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=kh(e,i),d,l,c,h,p,v,f,S=function(T){return d&&_a(d,"normal",T),new Fi(!0,T)},g=function(T){return r?(Rh(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=s.iterator;else if(n)d=s;else{if(l=xh(s),!l)throw Oh(Ih(s)+" is not iterable");if(Dh(l)){for(c=0,h=Lh(s);h>c;c++)if(p=g(s[c]),p&&wa(ka,p))return p;return new Fi(!1)}d=Ch(s,l)}for(v=a?s.next:d.next;!(f=Ph(v,d)).done;){try{p=g(f.value)}catch(T){_a(d,"throw",T)}if(typeof p=="object"&&p&&wa(ka,p))return p}return new Fi(!1)},Bh=vr,Mh=Yt,Uh=rs,Fh=function(s,e,t){var i=Bh(e);i in s?Mh.f(s,i,Uh(0,t)):s[i]=t},Vh=as,Hh=Nh,Gh=Fh;Vh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Hh(e,function(i,r){Gh(t,i,r)},{AS_ENTRIES:!0}),t}});var Yh=cr,qh=Yh.Object.fromEntries,zh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},jh=zh,Wh=ze,Qh=ns,Jh=hi,Pa=Gt,Kh=Ue,Ra=Kh("toStringTag");for(var Ls in jh){var Ia=Wh[Ls],Cs=Ia&&Ia.prototype;Cs&&Qh(Cs)!==Ra&&Jh(Cs,Ra,Ls),Pa[Ls]=Pa.Array}var Xh=qh,Zh=Xh,ef=Zh,tf=ef,pi=tf,Mt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Mt||(Mt={}));var Ut=(s,e=0,t=Mt.OFFSET_P)=>{switch(t){case Mt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Mt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:O(t)}return s},R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},ae;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(ae||(ae={}));const Me={[ae.Q_144P]:{width:256,height:144},[ae.Q_240P]:{width:428,height:240},[ae.Q_360P]:{width:640,height:360},[ae.Q_480P]:{width:856,height:480},[ae.Q_720P]:{width:1280,height:720},[ae.Q_1080P]:{width:1920,height:1080},[ae.Q_1440P]:{width:2560,height:1440},[ae.Q_2160P]:{width:3840,height:2160},[ae.Q_4320P]:{width:7680,height:4320}},Vi=(s,e)=>Me[s].height>Me[e].height,sf=(s,e)=>Me[s].height>=Me[e].height,ai=(s,e)=>Me[s].height<Me[e].height,rf=(s,e)=>Me[s].height<=Me[e].height,af=s=>s.sort((e,t)=>e===t?0:e===ae.INVARIANT?1:t===ae.INVARIANT?-1:ai(e,t)?1:-1)[0],nf=Object.keys(Me).sort((s,e)=>ai(s,e)?-1:1),kt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return nf.find(r=>{const a=Me[r];return a.width>=i&&a.height>=t})},of=s=>Me[s].height,ji=s=>s===ae.INVARIANT;class de{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=x(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=x(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const df=s=>{switch(s){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return O(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const uf=5,lf=5,cf=500,Da=7e3;class hf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new de(Y.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===m.STOPPED){i!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===V.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case Y.PLAYING:case Y.PAUSED:case Y.READY:break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PLAYING:{switch(i){case Y.PLAYING:break;case Y.PAUSED:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.READY:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PAUSED:{switch(i){case Y.PLAYING:this.videoState.startTransitionTo(Y.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Y.PAUSED:break;case Y.READY:this.videoState.startTransitionTo(Y.PAUSED),this.videoState.setState(Y.PAUSED);break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}default:O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(df(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ie;this.subscription.add(e),this.subscription.add(x(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(xe(cf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===V.Applying||Math.abs(o-a)>uf)&&r.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<lf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,m.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:O(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=x(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(Y.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(Y.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:V.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PLAYING||e===Y.PAUSED)&&(this.videoState.setState(Y.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===Y.READY&&this.videoState.setState(Y.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&R(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==Y.STOPPED&&this.videoState.setState(Y.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case b.MPEG:{const l=i[e];P(l);const c=af(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=i[e];P(l),r=Ut(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(xo(Da).subscribe(()=>a(`timeout(${Da})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class La{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Wn extends La{constructor(){super(),this.listeners||La.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Qn=class{constructor(){Object.defineProperty(this,"signal",{value:new Wn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Qn.prototype[Symbol.toStringTag]="AbortController",Wn.prototype[Symbol.toStringTag]="AbortSignal");function Jn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function ff(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Jn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((p,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const os=Jn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Kn=os?ff({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ft=os?Kn.fetch:window.fetch;os?Kn.Request:window.Request;const Et=os?Qn:window.AbortController,ii=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ni{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=ii(r.request);if(a>=i.from&&n<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(i.url);r&&a&&a.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(ii),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const p=i[h][1];p-r<=2*this.params.minDataSize&&(a=Math.max(a,p))}r===0?a=Math.max(a,r+this.params.minInitSize):a=Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${r}-${a}`);const o=n.toString(),u=new Et,d=u.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:L.PARSER,message:"Error parsing response data",thrown:h}),h};return Ft(o,{signal:d}).then(h=>{var p,v,f;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,g);const T=S.getReader(),I=parseInt((f=h.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||a-r+1;l.data=new ArrayBuffer(I);const w=new Uint8Array(l.data),A=async({done:N,value:K})=>{N?this.onBigRequestProgress(l):K&&(w.set(K,l.loaded),l.loaded+=K.byteLength,this.onBigRequestProgress(l),await(T==null?void 0:T.read().then(A,ni.suppressStreamErrors).catch(c)))};T==null||T.read().then(A,ni.suppressStreamErrors).catch(c)},ni.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:a,response:n}){var o,u,d,l,c,h,p,v;if(!this.activeRequests.has(e)||!a)return;const f=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of f){const{request:g}=S,[T,I]=ii(g),w=T>=t&&I<=t+r,A=t>=T&&t+r<I,N=a.slice(T-t,Math.min(I-t+1,r));if((w||A)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=N.byteLength,g.bytesTotal=i-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(G=>G!==S)),(c=S.success)===null||c===void 0||c.call(S,N,"",e);const K=n?Array.from(n.headers.entries()).map(([G,U])=>`${G}: ${U}`).join(`\r
7
- `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(p=n==null?void 0:n.status)!==null&&p!==void 0?p:200,K,[])}else A&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:L.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=ii(l.request);(c>=t&&c<i||h>t&&h<=i)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,a;if(!this.activeRequests.has(e))return;const n=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const o of n){const[u,d]=ii(o.request);(u>=t&&u<i||d>t&&d<=i)&&((a=o==null?void 0:o.abort)===null||a===void 0||a.call(o,o.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Wi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Wi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Wi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const pf=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Wi(r,e,i)}}),mf=(s,e)=>{const t=new ni(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return pf(n,t)}}},!0),()=>t.destroy()};var vf=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Sf=s=>{const e=new y(1/0),t=new C,i=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,p,v,f;const S=pi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),w=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(p=w!=null?w:I*1e3)!==null&&p!==void 0?p:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(v=S["x-delivery-type"])!==null&&v!==void 0?v:di.HTTP1,T=(f={1:!0,0:!1}[S["x-reused"]])!==null&&f!==void 0?f:void 0;i.next(g),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const p=h.onload,v=h.progress;h.onload=function(...f){return u(this),p(...f)},h.progress=function(...f){return d(this),v(...f)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Vt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},gf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Vt}),!0),bf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const qe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=J(r),d=new ie;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Pt=(s,e,t)=>qe(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),nt=(s,e,t,i)=>qe(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),pt=(s,e,t,i)=>qe(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),yf=s=>["__",s.language,s.label].join("|"),Tf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class je{constructor(){this.available$=new C,this.current$=new y(void 0),this.error$=new C,this.subscription=new ie,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(qe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(qe(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(x(M(e,"addtrack"),M(e,"removetrack"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(x(M(e,"change"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),$(i=>i&&this.htmlTextTrackToITextTrack(i).id),pe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(M(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const p=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;p&&p.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(M(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(je.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:yf(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))_(e)&&Tf(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ot=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class Ar{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Xn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const or=3;class Ef{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<or&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||or))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Zn=(s,e,t=or)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const $f=50,Af=s=>s.webkitAudioDecodedByteCount!=="undefined"?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!=="undefined"?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,dt=s=>{const e=v=>M(s,v).pipe(At(void 0)),i=x(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>M(s,v))).pipe($(v=>v.type==="ended"?s.readyState<2:s.readyState<3),pe()),r=x(M(s,"progress"),M(s,"timeupdate")).pipe($(()=>Zn(s.buffered,s.currentTime))),a=Xn()?Ze({play:e("play").pipe(ge()),playing:e("playing")}).pipe(At(void 0)):e("playing"),n=M(s,"playing").pipe(xe($f),$(()=>Af(s))),o=M(s,"volumechange").pipe($(()=>({muted:s.muted,volume:s.volume}))),u=M(s,"ratechange").pipe($(()=>s.playbackRate)),d=M(s,"error").pipe(q(()=>Boolean(s.error||s.played.length)),$(()=>{var v;const f=s.error;return{id:f?`MediaError#${f.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:f?f.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=M(s,"timeupdate").pipe($(()=>s.currentTime)),c=new C,h=.3;let p;return l.subscribe(v=>{s.loop&&_(p)&&_(v)&&p>=s.duration-h&&v<=h&&c.next(p),p=v}),{playing$:a,pause$:e("pause").pipe(q(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:M(s,"durationchange").pipe($(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},wr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var wf=as,_f=ss,kf=Tr,Pf=yr;wf({target:"Array",proto:!0},{at:function(e){var t=_f(this),i=kf(t),r=Pf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Rf=hr,eo=Rf,If=eo,Df=If("Array","at"),Lf=Df,Cf=Lf,xf=Cf,Of=xf,Je=Of;let _r=!1,Ke={};const Nf=s=>{_r=s},Bf=()=>{Ke={}},Mf=s=>{s(Ke)},Ri=(s,e)=>{var t;_r&&(Ke.meta=(t=Ke.meta)!==null&&t!==void 0?t:{},Ke.meta[s]=e)};class Ye{constructor(e){this.name=e}next(e){var t,i;if(!_r)return;Ke.series=(t=Ke.series)!==null&&t!==void 0?t:{};const r=(i=Ke.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ke.series[this.name]=r}}const Uf=new Ye("best_bitrate"),Ff=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Vf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const mi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,p;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},S=f&&kt(f),g=i.considerPlaybackRate&&_(o)?o:1,T=s.filter(F=>!ji(F.quality)).sort((F,B)=>Vi(F.quality,B.quality)?-1:1),I=(c=Je(T,-1))===null||c===void 0?void 0:c.quality,w=(h=Je(T,0))===null||h===void 0?void 0:h.quality,A=J(r)||_(r.min)&&_(r.max)&&ai(r.max,r.min)||_(r.min)&&w&&Vi(r.min,w)||_(r.max)&&I&&ai(r.max,I),N=g*Ff(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G=T.filter(F=>{const B=S?ai(F.quality,S):!0,te=_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0,ue=i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!ji(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Vi(F.quality,u.quality),me=A||(J(r.max)||rf(F.quality,r.max))&&(J(r.min)||sf(F.quality,r.min));return B&&te&&!ue&&me})[0];G&&G.bitrate&&Uf.next(G.bitrate);const U=(p=G!=null?G:T[Math.ceil((T.length-1)/2)])!==null&&p!==void 0?p:s[0],X=U&&d&&d.history[U.id]&&he()-d.history[U.id]<=i.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!X&&d.recordSelection(U),X&&(d!=null&&d.last)){const F=d.last;return d==null||d.recordSwitch(F),F}return d==null||d.recordSwitch(U),U};var Ae=s=>new URL(s).hostname;const Hf=300,Qi=(s,e=Hf)=>new li(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Bo(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),_(u)&&_(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()}),ut=s=>{try{s.pause(),s.playbackRate=0,s.removeAttribute("src"),s.load(),s.remove()}catch(e){console.error(e)}},Gf=5e3,si={};var z;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const Se=(s,e)=>new li(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Ca{constructor(e){this.subscription=new ie,this.videoState=new de(z.DOWNLOADING_LIB),this.textTracksManager=new je,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new Ar,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===z.DOWNLOADING_LIB||t===z.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&t!==z.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:O(t)}break}case m.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:O(t)}break}case m.PLAYING:{switch(t){case z.PLAYING:break;case z.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case z.READY:this.play();break;case z.STOPPED:this.prepare();break;default:O(t)}break}case m.PAUSED:{switch(t){case z.PLAYING:this.pause(),this.liveOffset.pause();break;case z.PAUSED:break;case z.READY:this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case z.STOPPED:this.prepare();break;default:O(t)}break}default:O(i)}},this.video=ot(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:L.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),Gf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(si.MediaPlayer=r.MediaPlayer,si.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(si.MediaPlayer,"dashjs not loaded"),P(si.Debug,"dashjs not loaded"),this.player=si.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?wr(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=mf(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&bf(this.player),vf(this.player),this.params.tuning.requestQuick&&gf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=f=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:f})},r=(f,S)=>this.subscription.add(f.subscribe(S,i));r(Qi(this.video),this.elementSize$),r(Se(this.player,"error").pipe($(f=>{const S=typeof f.error=="object"?f.error.code:f.error,g=typeof f.error=="object"?f.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(Se(this.player,"playbackError").pipe($(f=>({id:"DashJSPlayback",message:f.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(q(({mediaType:f})=>f==="video"),$(({newQuality:f})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===f))===null||S===void 0?void 0:S.track}));a.pipe(q(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(q(({to:f})=>f===z.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(qe(t.videoTrack,()=>{var f,S;const g=this.player.getQualityFor("video");return(S=(f=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===g))===null||f===void 0?void 0:f.track)===null||S===void 0?void 0:S.id},f=>{var S;if(J(f))return;const g=(S=this.videoTracks.find(({track:T})=>T.id===f))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(f=>f==null?void 0:f.id)),onError:i}))},i)),this.subscription.add(qe(t.autoVideoTrackSwitching,()=>{var f,S,g;return(g=(S=(f=this.player.getSettings().streaming)===null||f===void 0?void 0:f.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},f=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:f}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(q(({mediaType:f})=>f==="video"),$(({state:f})=>f==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:f,request:{url:S}})=>{var g,T;const I=this.player.getDashMetrics(),w=I.getLatestFragmentRequestHeaderValueByID(f,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(f,"X-Delivery-Type"))!==null&&g!==void 0?g:di.HTTP1,N=(T={1:!0,0:!1}[w])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Ae(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:f,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(f),this.videoTracks=[];const T=this.player.getQualityFor("video");let I;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),N=kt(w),K=w.bitrate/1e3,G={width:w.width,height:w.height},U=this.frameRatesByFrameHeight[w.height];if(N){const X={id:A,quality:N,bitrate:K,size:G,fps:U};this.videoTracks.push({track:X,bitrateInfo:w}),w.qualityIndex===T&&(I=X)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:w})=>w)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(z.STREAM_INITIALIZED),this.videoState.startTransitionTo(z.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:f})=>{if(!f.requestEndDate||!f.firstByteDate||!f.bytesLoaded)return;const S=f.requestEndDate.getTime()-f.firstByteDate.getTime(),g=f.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(x(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const f=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=mi(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:f,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(Ze({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(q(_))}).pipe(q(({isLive:f})=>f),$(({maxSeekBackTime:f})=>-f/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe($(({time:f})=>f!=null?f:0));r(Ze({availableFrom:this.availableFrom$.pipe(q(_)),currentTime:n}),({availableFrom:f,currentTime:S})=>this.params.output.liveTime$.next(f+S*1e3)),r(n.pipe(q(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe($(()=>Zn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),R(t.playbackState,m.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),R(t.playbackState,m.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var f;((f=this.videoState.getTransition())===null||f===void 0?void 0:f.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(Qi(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Sf(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ze({isLive:this.isLive$,isShort:e.duration$.pipe($(f=>f<60))}),({isLive:f,isShort:S})=>{const g=!f&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(q(f=>f>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ge(),At(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(Pt(this.video,t.isLooped,i));const{volumeState$:h,looped$:p,playbackRateState$:v}=dt(this.video);this.subscription.add(nt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(pt(this.video,t.playbackRate,v,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(z.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(z.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=Ut(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Mt.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(z.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}ut(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var vi=s=>{switch(s){case"mobile":return ae.Q_144P;case"lowest":return ae.Q_240P;case"low":return ae.Q_360P;case"sd":case"medium":return ae.Q_480P;case"hd":case"high":return ae.Q_720P;case"fullhd":case"full":return ae.Q_1080P;case"quadhd":case"quad":return ae.Q_1440P;case"ultrahd":case"ultra":return ae.Q_2160P}},mt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function Te(){return he()}function to(s){return Te()-s}function xa(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Yf(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Hi(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,p="arraybuffer",v=7e3,f=2e3,S=()=>{if(u)return;P(l);const B=to(l);let te;if(B<f){te=f-B,setTimeout(S,te);return}f*=2,f>v&&(f=v),n&&n.abort(),n=new r,N()};const g=B=>(a=B,F),T=B=>(c=B,F),I=()=>(p="json",F),w=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},A=B=>(h=B,F),N=()=>{l=Te(),n=new r,n.open("get",s);let B=0,te,ue=0;const me=()=>(P(l),Math.max(l,Math.max(te||0,ue||0)));if(a&&n.addEventListener("progress",k=>{const H=Te();a.updateChunk&&k.loaded>B&&(a.updateChunk(me(),k.loaded-B),B=k.loaded,te=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const H=n.response.byteLength-B;H&&a.updateChunk&&a.updateChunk(me(),H)}c&&c(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Te(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),F},F={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,F),withRetryInterval:(B,te)=>(_(B)&&(f=B),_(te)&&(v=te),F),withTimeout:B=>(o=B,F),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}const qf=100,zf=2e3,jf=500;let Wf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-jf;if(t-e>zf){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>qf&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class Qf{constructor(e,t,i,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Hi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Di=3,Jf=300,Kf=2e3,Xf=6e4,Zf=10,ep=1,tp=500;class ip{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new Wf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=xa(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=xa(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||_(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Yf(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qf(Di,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=Hi(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Di).withFinally(()=>{u=null}).send()},p=(w,A,N)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=w=>{const A=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),i.playbackRate=w)},f=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const N=Te()-1e4;let K=0;for(let U=0;U<this.bufferStates.length;U++){const X=this.bufferStates[U];w=Math.min(w,X.buf),X.ts<N&&K++}this.bufferStates.splice(0,K),t(`update playback rate; minBuffer=${w} drop=${K} jitter=${this.sourceJitter}`);let G=w-ep;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?v(1.15):G>1?v(1.1):G>.3?v(1.05):v(1)}},g=w=>{let A;const N=()=>A&&A.start?A.start.length:0,K=k=>A.start[k]/1e3,G=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,X=(k,H)=>({chunkIdx:U(k),startTS:K(k),dur:G(k),discontinuity:H}),F=()=>{let k=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=H;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=A.dur.length-1;for(;ve>=0&&(fe-=A.dur[ve],!(fe<=0));--ve);k=Math.min(ve,A.dur.length-1-ne),k=Math.max(k,0)}return X(k,!0)},B=k=>{const H=N();if(!(H<=0)){if(_(k)){for(let ne=0;ne<H;ne++)if(K(ne)>k)return X(ne)}return F()}},te=k=>{const H=N(),ne=k?k.chunkIdx+1:0,fe=ne-A.fragIndex;if(!(H<=0)){if(!k||fe<0||fe-H>Zf)return t(`Resync: offset=${fe} bChunks=${H} chunk=`+JSON.stringify(k)),F();if(!(fe>=H))return X(ne-A.fragIndex,!1)}},ue=(k,H,ne)=>{d&&d.abort(),d=Hi(this.urlResolver.resolve(k,!0,this.lowLatency),H,ne,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Di).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{ue(w,ne=>{if(!c())return;A=ne;const fe=Boolean(A.lowLatency);fe!==this.lowLatency&&f(fe);let ve=0;for(let we=0;we<A.dur.length;++we)ve+=A.dur[we];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(B(H))},()=>this._handleNetworkError())},nextChunk:te}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:A,logger:N}=this.params;let K=g(e.jidxUrl),G,U,X,F,B=0,te,ue,me;const k=()=>{te&&(clearTimeout(te),te=void 0);const Z=Math.max(tp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=B+Z,$e=Te(),Pe=Math.min(1e4,be-$e);B=$e;const vt=()=>{d||c()&&K.seek(()=>{c()&&(B=Te(),H(),k())})};Pe>0?te=window.setTimeout(()=>{this.paused?k():vt()},Pe):vt()},H=()=>{let Z;for(;Z=K.nextChunk(F);)F=Z,Fe(Z);const be=K.nextChunk(X);if(be){if(X&&be.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}we(be)}else k()},ne=(Z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,Pe,vt;const Ve=lt=>{window.setTimeout(()=>{c()&&ne(Z,be)},lt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Ve(100);else{const lt=Te(),St=A.currentTime;!this.paused&&A.buffered.length>1&&ue===St&&lt-me>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),ue!==St&&(ue=St,me=lt);const zt=this._getBufferSizeSec();if(zt>30)N(`Buffered ${zt} seconds; delaying appendBuffer`),Ve(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Rt){if(Rt.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&($e=this.sourceBuffer.buffered.start(0),Pe=St,Pe-$e>4&&this.sourceBuffer.remove($e,Pe-3)),Ve(1e3);else throw Rt}}},fe=()=>{U&&G&&(N([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(X)]),ne(U,function(){U=null,H()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),we=Z=>{c()&&p(ve(Z),(be,$e)=>{if(c()){if($e/=1e3,U=be,X=Z,n=Z.startTS,$e){const Pe=Math.min(10,Z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}fe()}},()=>this._handleNetworkError())},Fe=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},qt=Z=>{c()&&(e.cachedHeader=Z,ne(Z,()=>{G=!0,fe()}))};a=!0,K.seek(Z=>{if(c()){if(B=Te(),!Z){k();return}F=Z,!J(w)||Z.startTS>w?we(Z):(X=Z,H())}},w),e.cachedHeader?qt(e.cachedHeader):h(e.headerUrl,qt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),v=c/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,p)=>{const v=Te();if(this.chunkRateEstimator.addInterval(h,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-h,speed:S}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&to(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const p=a.updateChunk(c,h);return p&&d(),p},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Hi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Di).withRetryInterval(Jf,Kf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;mt(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Xf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const sp=[j.PAUSED,j.PLAYING,j.READY],rp=[j.PAUSED,j.PLAYING,j.READY];class ap{constructor(e){this.subscription=new ie,this.videoState=new de(j.STOPPED),this.representations$=new y([]),this.textTracksManager=new je,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Ar,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),p=(n=vi(c.name))!==null&&n!==void 0?n:kt(c.video),v=c.bitrate/1e3,f={...c.video};if(!p)continue;const S={id:h,quality:p,bitrate:v,size:f};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===m.STOPPED){a!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(!n){if(rp.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;_(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==m.PAUSED&&d.state===V.Requested&&sp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(Ut(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(o===m.PAUSED)this.videoState.setState(j.PAUSED);else if(o===m.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const l=u==null?void 0:u.from;l&&l===m.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:o===m.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:o===m.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:r})};x(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ot(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=dt(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ze({zeroTime:this.zeroTime$.pipe(q(_)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Pt(this.video,this.params.desiredState.isLooped,t)).add(nt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&of(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case j.MANIFEST_READY:case j.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===m.READY&&this.params.desiredState.playbackState.setState(m.READY);break;case j.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return O(r.to)}},t)).add(x(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(this.video)}createLiveDashPlayer(){const e=new ip({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&_(u)?u:(a=mi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(Ut(this.params.source.url,i))}}var io=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?di.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Tt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const np=s=>{const e=document.createElement("a");return e.href=s,e.origin},op=s=>{const e=document.createElement("a");return e.href=s,e.host};class so{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=pi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(op(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ji{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const p=f=>{r(Ji._str2ua(f.substr(u))),u=f.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Vt(v)),this._lastXhr=new so(v,e.failoverHosts,f=>{this._lastXhr=void 0,p(f);const S=Date.now()-d;this._params.onBandwidthChange({size:f.length,duration:S,speed:8*f.length/(S/1e3)}),this._onDashCallback("loading",{size:f.length,done:!0}),a==null||a()},f=>{if(f.length-u>o&&p(f),c===0){c=Date.now();return}h=f.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=f.length,c=Date.now()),this._onDashCallback("loading",{size:f.length,done:!1})},n,(f,S,g)=>this._params.onError(f,S,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ji._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class dp{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Vt(i)),new so(i,t,r=>{this.attachManifest(r,t,np(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,p,v,f,S,g,T,I,w,A,N,K,G,U,X,F,B;const te=d.getElementsByTagName("SegmentBase")[0],ue=te&&n(te,"indexRange").split("-"),me=te&&te.getElementsByTagName("Initialization")[0],k=me&&n(me,"range").split("-");if(!k||!ue){const Fe=d.parentElement;if((Fe==null?void 0:Fe.getAttribute("contentType"))==="text"){const qt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((v=(p=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),be=(f=Fe.getAttribute("lang"))!==null&&f!==void 0?f:void 0;Z&&u.push({id:qt,url:Z,language:be})}return}const H=.1,ne=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const we=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ve=we?wr(we):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((w=d.attributes.getNamedItem("height"))===null||w===void 0?void 0:w.value),bandwidth:ne,baseURL:fe,failoverHosts:t,indexFrom:Number(ue[0]),indexTo:Number(ue[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(N=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&N!==void 0?N:void 0,mimeType:(G=(K=d.attributes.getNamedItem("mimeType"))===null||K===void 0?void 0:K.value)!==null&&G!==void 0?G:void 0,fps:ve,bufferSize:H*ne/8,bufferLength:H,name:(X=(U=d.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&X!==void 0?X:void 0,id:(B=(F=d.attributes.getNamedItem("id"))===null||F===void 0?void 0:F.value)!==null&&B!==void 0?B:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const p=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:p-1}),d=p,u=v}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}c=p.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ji({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||J(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const up=[W.PAUSED,W.PLAYING];class lp{constructor(e){this.videoState=new de(W.STOPPED),this.subscription=new ie,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new je,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var i,r,a;const n=[];for(const o of t){const u=(r=(i=o.name)!==null&&i!==void 0?i:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&vi(o.name))!==null&&a!==void 0?a:kt(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const p={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:p,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===m.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===V.Requested&&up.includes(t)&&this.seek(n.position,n.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===m.READY?R(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case W.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),x(this.videoState.stateChangeStarted$.pipe($(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=ot(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ef(this.video),this.dash=new dp({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:L.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=dt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==V.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(nt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(Qi(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(x(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe($(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(p))g=p;else{const T=Tt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(T/I,1);g=(u=mi(c.map(({track:A})=>A),{container:f,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),pe()).subscribe(this.currentRepresentation$,i)).add(Ze({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(q(o=>o.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(q(_))}).pipe(ge()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(q(_),pe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Tt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ae(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=io(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),At(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(q(_)).subscribe(this.handleRepresentationPlay,i)).add(x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return O(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}var De;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(De||(De={}));var Ki;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Ki||(Ki={}));var Le;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Le||(Le={}));var ee;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ee||(ee={}));var Ht;(function(s){s.MP4="mp4",s.WEBM="webm"})(Ht||(Ht={}));var dr=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const cp=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},hp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Oa=hp?cp:window.requestIdleCallback;var xs,Os;let ro=!1;try{ro=Xn()&&parseInt((Os=(xs=navigator.userAgent.match(/Version\/(\d+)/))===null||xs===void 0?void 0:xs[1])!==null&&Os!==void 0?Os:"",10)<16}catch(s){console.error(s)}class fp{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;ro&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:L.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:O(t)}}}var Na=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const ao=new TextDecoder("ascii"),no=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=ao.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,s.byteLength)-e,n=new DataView(s.buffer,s.byteOffset+e,a);return{id:r,size:t,contents:n}},pp=s=>ao.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",mp=(s,e,t)=>{const i=no(s),r=[];let a=0;const n=()=>{const f=i.contents.getUint32(a);return a+=4,f};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),l=n(),c=n(),h=n()&4294967295;let p=l/d*1e3,v=(t?t.to+1:s.byteOffset+s.byteLength)+c;for(let f=0;f<h;f++){const S=n(),g=S>>>31,T=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const w=I/d*1e3;r.push({status:ee.NONE,time:{from:p,to:p+w},byte:{from:v,to:v+T-1}}),p+=w,v+=T}return r},vp=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const a=no(r);if(i||(i=a.id==="mdat"),e+a.size<=s.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Sp={validateData:pp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:mp,parseFeedableSegmentChunk:vp};var E;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(D||(D={}));const Ba={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},oo=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Xi(s,t),r=i in Ba,a=r?Ba[i].type:D.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=Xi(u),c=d*2**((o-1)*8)+l,h=t+o;let p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Xi=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Xe=(s,e)=>{switch(e){case D.SignedInteger:return s.getInt8(0);case D.UnsignedInteger:return Xi(s);case D.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(s);case D.UTF8:return new TextDecoder("utf-8").decode(s);case D.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case D.Master:return s;case D.Binary:return s;default:O(e)}},Si=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=oo(i);if(!e(r))return;r.type===D.Master&&Si(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},gp=s=>{if(s.getUint32(0)!==E.EBML)return!1;let e,t,i;const r=oo(s);return Si(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=Xe(o,n):a===E.DocType?t=Xe(o,n):a===E.DocTypeReadVersion&&(i=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},uo=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],bp=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],yp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d;return Si(s,({tag:l,type:c,value:h,valueSize:p})=>{if(l===E.SeekID){const v=Xe(h,c);d=Xi(v)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+p):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?i=Xe(h,c):l===E.Duration?r=Xe(h,c):l===E.SeekPosition&&d===E.Cues?u=Xe(h,c):a&&n&&uo.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u}},Tp=s=>{if(J(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ep=(s,e)=>{let t=!1,i=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Si(s,({tag:o,type:u,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&r(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=Xe(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=Xe(d,u));break;default:t&&uo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:ee.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},$p=s=>{let e=0,t=!1;try{Si(s,i=>i.tag===E.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):bp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Ap={validateData:gp,parseInit:yp,getIndexRange:Tp,parseSegments:Ep,parseFeedableSegmentChunk:$p};class Ma{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new C,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Et,this.destroyAbortController=new Et,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Be(this.destroyAbortController.signal,async function*(d){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new fp(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const f=Math.min(this.bufferLimit,Na(this.sourceBuffer.buffered)*.8);this.bufferLimit=f,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(l,"high",!0);const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let p=0;for(const v of h)v.time.from-p>0&&this.gaps.push({representation:l.id,from:p,to:v.time.from}),p=v.time.to;_(l.duration)&&l.duration-p>0&&this.gaps.push({representation:l.id,from:p,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=Be(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(J(c)?yield this.loadInit(l,"high",!1):c instanceof Promise&&(yield c),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal);const h=this.getCurrentPosition();_(h)&&this.maintain(h)}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case Ht.MP4:this.containerParser=Sp;break;case Ht.WEBM:this.containerParser=Ap;break;default:O(i)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Tt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Na(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Tt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Je(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===ee.FED&&!o.length&&Tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Je(i,-1);u&&u.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&(this.mediaSource.readyState==="open"&&this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:p}},v)=>{const f=h<=i&&p>=i,S=h>i||f||v===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+g||p<=i+g;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&S&&T&&this.sourceBuffer&&!dr(this.sourceBuffer.buffered,i))&&S&&T});if(r===-1)return[];if(t!==Le.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===ee.NONE||h.status===ee.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Le.BYTE_RANGE:{r=t.segmentReference.url,a={from:Je(e,0).byte.from,to:Je(e,-1).byte.to};break}case Le.TEMPLATE:{const d=Je(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:O(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Be(u,async function*(){const d=Br(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(i=Tt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),c.segment.status=ee.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(h=this.segments.get(p.id))!==null&&h!==void 0?h:[])v.status===ee.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,p=d===Le.BYTE_RANGE,v=p?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=p?h.byte.from-i:0,g=p?h.byte.to-i:e.byteLength,T=S<r,I=g<=r;if(h.status===ee.DOWNLOADING&&T&&I){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const w=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(v,r-S),c.loadedBytes>c.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===v?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)c.fedBytes+=A.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Oa(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Be(this.destroyAbortController.signal,async function*(){const o=Br(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||J(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===ee.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const p of h)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===ee.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>=1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Oa(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(J(this.sourceBuffer)||J(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var Bt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Bt||(Bt={}));class wp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Et,this.subscription=new ie,this.fetchManifest=Be(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Vt(a));const n=yield Ft(a,{signal:this.abortAllController.signal}).catch(ri);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Be(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Bt.HEADER:Bt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,p,v;let f=r;const S=new Headers;if(n)switch(a){case Bt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Bt.PARAM:{const k=new URL(f,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),f=k.toString();break}default:O(a)}this.requestQuic&&(f=Vt(f));let g=this.abortAllController.signal;if(d){const k=new Et;if(this.subscription.add(x(M(this.abortAllController.signal,"abort"),M(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){ri(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){ri(H)}g=k.signal}const T=he(),I=yield Ft(f,{priority:u,headers:S,signal:g}).catch(ri),w=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(w-T),!I)return null;if(!I.ok||!I.body)return Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`));this.onHeadersReceived(I.headers);const A=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield I.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(k.byteLength,he()-w),o==null||o(new DataView(k),k.byteLength),k}if(!o&&!l)return I.arrayBuffer();const[N,K]=I.body.tee(),G=N.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(K));let U=0;const X=new ArrayBuffer(A),F=new Uint8Array(X),B=new DataView(X);let te=!1;const ue=k=>{te=!0,ri(k)},me=Be(g,async function*({done:k,value:H}){U===0&&this.lastRequestFirstBytes$.next(he()-T),!g.aborted&&(k?o==null||o(B,U):H&&(F.set(H,U),U+=H.byteLength,o==null||o(B,U),yield G==null?void 0:G.read().then(me,ue)))}.bind(this));return yield G==null?void 0:G.read().then(me,ue),te?null:X}.bind(this)),this.fetchByteRangeRepresentation=Be(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Le.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,p,v;r.indexRange&&(p=r.indexRange.from,v=r.indexRange.to,h=d+1===p,h&&(l=Math.min(p,u),c=Math.max(v,d))),l=Math.min(l,0);const f=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!f)return null;const S=new DataView(f,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!T)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(f,T.from-l,T.to-T.from+1);else{const A=yield this.fetch(r.url,{range:T,priority:n,measureThroughput:!1});if(!A)return null;I=new DataView(A)}const w=a.parseSegments(I,g,T);return{dataView:new DataView(f),segments:w}}.bind(this)),this.fetchTemplateRepresentation=Be(this.abortAllController.signal,async function*(r,a){if(r.type!==Le.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{segments:r.segments.map(d=>({...d,status:ee.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=io(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case Le.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Le.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:O(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ri=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var _p=wt,kp=es,Pp=Ue,Rp=Pp("match"),Ip=function(s){var e;return _p(s)&&((e=s[Rp])!==void 0?!!e:kp(s)=="RegExp")},Dp=ns,Lp=String,Cp=function(s){if(Dp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Lp(s)},xp=_t,Op=function(){var s=xp(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Np=rt,Bp=at,Mp=fr,Up=Op,Ua=RegExp.prototype,Fp=function(s){var e=s.flags;return e===void 0&&!("flags"in Ua)&&!Bp(s,"flags")&&Mp(Ua,s)?Np(Up,s):e},kr=st,Vp=ss,Hp=Math.floor,Ns=kr("".charAt),Gp=kr("".replace),Bs=kr("".slice),Yp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,zp=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=qp;return r!==void 0&&(r=Vp(r),u=Yp),Gp(a,u,function(d,l){var c;switch(Ns(l,0)){case"$":return"$";case"&":return s;case"`":return Bs(e,0,t);case"'":return Bs(e,n);case"<":c=r[Bs(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var p=Hp(h/10);return p===0?d:p<=o?i[p-1]===void 0?Ns(l,1):i[p-1]+Ns(l,1):d}c=i[h-1]}return c===void 0?"":c})},jp=as,Wp=rt,Pr=st,Fa=lr,Qp=Oe,Jp=ts,Kp=Ip,xt=Cp,Xp=is,Zp=Fp,em=zp,tm=Ue,im=tm("replace"),sm=TypeError,lo=Pr("".indexOf),rm=Pr("".replace),Va=Pr("".slice),am=Math.max,Ha=function(s,e,t){return t>s.length?-1:e===""?t:lo(s,e,t)};jp({target:"String",proto:!0},{replaceAll:function(e,t){var i=Fa(this),r,a,n,o,u,d,l,c,h,p=0,v=0,f="";if(!Jp(e)){if(r=Kp(e),r&&(a=xt(Fa(Zp(e))),!~lo(a,"g")))throw sm("`.replaceAll` does not allow non-global regexes");if(n=Xp(e,im),n)return Wp(n,e,i,t);if(r)return rm(xt(i),e,t)}for(o=xt(i),u=xt(e),d=Qp(t),d||(t=xt(t)),l=u.length,c=am(1,l),p=Ha(o,u,0);p!==-1;)h=d?xt(t(u,p,o)):em(u,o,p,[],void 0,t),f+=Va(o,v,p)+h,v=p+l,p=Ha(o,u,p+c);return v<o.length&&(f+=Va(o,v)),f}});var nm=eo,om=nm("String","replaceAll"),dm=om,um=dm,lm=um,cm=lm,Ga=cm;const Ya=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ms=(s,e)=>{let t=s;t=Ga(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Ga(t,n,(o,u)=>J(a)?o:J(u)?a:a.padStart(parseInt(u,10),"0"))}return t},hm=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,p,v,f,S,g,T,I,w,A,N,K,G,U,X,F,B,te,ue,me,k,H,ne,fe,ve,we,Fe;const Z=new DOMParser().parseFromString(s,"application/xml"),be={video:[],audio:[],text:[]},$e=Z.children[0],Pe=$e.getElementsByTagName("Period")[0],vt=Pe.children;let Ve;const lt=$e.getAttribute("mediaPresentationDuration"),St=Pe.getAttribute("duration");if(lt)Ve=Ya(lt);else if(St){const He=Ya(St);_(He)&&(Ve=He)}let zt=0;const Rt=(i=(t=$e.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],vo=Rt.includes(Ki.WEBM_AS_IN_FFMPEG)||Rt.includes(Ki.WEBM_AS_IN_SPEC)?Ht.WEBM:Ht.MP4;for(const He of vt){const gi=He.getAttribute("mimeType"),So=He.getAttribute("codecs"),Rr=(r=He.getAttribute("contentType"))!==null&&r!==void 0?r:gi==null?void 0:gi.split("/")[0],go=(n=(a=He.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],bo=He.querySelectorAll("Representation"),yo=He.querySelector("SegmentTemplate");if(Rr!=="text")for(const ye of bo){const jt=(o=ye.getAttribute("mimeType"))!==null&&o!==void 0?o:gi,Ir=(d=(u=ye.getAttribute("codecs"))!==null&&u!==void 0?u:So)!==null&&d!==void 0?d:"",bi=(c=(l=ye.getAttribute("contentType"))!==null&&l!==void 0?l:jt==null?void 0:jt.split("/")[0])!==null&&c!==void 0?c:Rr,To=(p=(h=He.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&p!==void 0?p:[],Eo=parseInt((v=ye.getAttribute("width"))!==null&&v!==void 0?v:"",10),Dr=parseInt((f=ye.getAttribute("height"))!==null&&f!==void 0?f:"",10),Lr=parseInt((S=ye.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Cr=(g=ye.getAttribute("frameRate"))!==null&&g!==void 0?g:"",$o=(T=ye.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Ao=Cr?wr(Cr):void 0,wo=(I=ye.getAttribute("id"))!==null&&I!==void 0?I:(zt++).toString(10),_o=bi==="video"?`${Dr}p`:bi==="audio"?`${Lr}Kbps`:Ir,ko=`${wo}@${_o}`,Po=(N=(A=(w=ye.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",xr=new URL(Po,e).toString(),Ro=[...Rt,...go,...To];let us;const Io=ye.querySelector("SegmentBase"),gt=(K=ye.querySelector("SegmentTemplate"))!==null&&K!==void 0?K:yo;if(Io){const Wt=(U=(G=ye.querySelector("SegmentBase Initialization"))===null||G===void 0?void 0:G.getAttribute("range"))!==null&&U!==void 0?U:"",[Qt,cs]=Wt.split("-").map(bt=>parseInt(bt,10)),Jt={from:Qt,to:cs},Kt=(X=ye.querySelector("SegmentBase"))===null||X===void 0?void 0:X.getAttribute("indexRange"),[hs,yi]=Kt?Kt.split("-").map(bt=>parseInt(bt,10)):[],Xt=Kt?{from:hs,to:yi}:void 0;us={type:Le.BYTE_RANGE,url:xr,initRange:Jt,indexRange:Xt}}else if(gt){const Wt={representationId:(F=ye.getAttribute("id"))!==null&&F!==void 0?F:void 0,bandwidth:(B=ye.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},Qt=parseInt((te=gt.getAttribute("timescale"))!==null&&te!==void 0?te:"",10),cs=(ue=gt.getAttribute("initialization"))!==null&&ue!==void 0?ue:"",Jt=gt.getAttribute("media"),Kt=(k=parseInt((me=gt.getAttribute("startNumber"))!==null&&me!==void 0?me:"",10))!==null&&k!==void 0?k:1,hs=Ms(cs,Wt);if(!Jt)throw new ReferenceError("No media attribute in SegmentTemplate");const yi=(H=gt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],Xt=[];if(yi.length){let bt=Kt,yt=0;for(const Zt of yi){const It=parseInt((ne=Zt.getAttribute("d"))!==null&&ne!==void 0?ne:"",10)*1e3,ei=parseInt((fe=Zt.getAttribute("r"))!==null&&fe!==void 0?fe:"",10)||0,ti=(we=parseInt((ve=Zt.getAttribute("t"))!==null&&ve!==void 0?ve:"",10))!==null&&we!==void 0?we:void 0;for(let Or=0;Or<ei+1;Or++){const Do=Ms(Jt,{...Wt,segmentNumber:bt.toString(10),segmentTime:ti.toString(10)}),Lo=ti?ti/Qt:yt;yt+=It/Qt;const Co=yt;bt++,Xt.push({time:{from:Lo,to:Co},url:Do})}}}else if(_(Ve)){const yt=parseInt((Fe=gt.getAttribute("duration"))!==null&&Fe!==void 0?Fe:"",10)/Qt*1e3,Zt=Math.ceil(Ve/yt);let It=0;for(let ei=1;ei<Zt;ei++){const ti=Ms(Jt,{...Wt,segmentNumber:ei.toString(10),segmentTime:It.toString(10)});Xt.push({time:{from:It,to:It+yt},url:ti}),It+=yt}}us={type:Le.TEMPLATE,baseUrl:xr,initUrl:hs,segments:Xt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!bi||!jt)continue;const ls={video:De.VIDEO,audio:De.AUDIO,text:De.TEXT}[bi];ls&&be[ls].push({id:ko,kind:ls,segmentReference:us,profiles:Ro,duration:Ve,bitrate:Lr,mime:jt,codecs:Ir,width:Eo,height:Dr,fps:Ao,quality:$o})}}return{duration:Ve,container:vo,representations:be}},fm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ie;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ie||(Ie={}));let pm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ie,this.state$=new de(Ie.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new C,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new Et,this.initManifest=Be(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(Ie.MANIFEST_READY);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=hm(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest={...a,representations:pi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(Ie.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=Be(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.state$.startTransitionTo(Ie.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Ma(De.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(i)&&(this.audioBufferManager=new Ma(De.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=x(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=x(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(x(this.forceEnded$,Ze({allBuffersFull:a,someBufferEnded:n}).pipe(q(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(x(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),_(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&_(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ie.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Oo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new wp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Ie.RUNNING),this.subscription.add(x(...fm.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[De.VIDEO]:this.videoBufferManager,[De.AUDIO]:this.audioBufferManager,[De.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),dr(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ie.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const mm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?vi(a):void 0)!==null&&n!==void 0?n:kt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},vm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Je(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Je(s,-1)};class gm{constructor(e){this.subscription=new ie,this.videoState=new de(le.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new je,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Vf,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===V.Requested&&(r==null?void 0:r.to)!==m.PAUSED&&t!==le.STOPPED&&i!==m.STOPPED&&this.seek(a.position,a.forcePrecise),i===m.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(t){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:i===m.PAUSED?(this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.READY&&R(this.params.desiredState.playbackState,m.READY);return;case le.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case le.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}}},this.params=e,this.video=ot(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new pm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:L.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,r));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(q(_),ge(),At(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),a(Qi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),R(t.playbackState,m.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),R(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Ie.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((f,S)=>S.bitrate-f.bitrate),p=Array.from(c.video).sort((f,S)=>S.bitrate-f.bitrate);if(!this.params.tuning.isAudioDisabled)for(const f of h){const S=vm(f);S&&this.audioTracks.push({track:S,representation:f})}for(const f of p){const S=mm(f);if(S){this.videoTracks.push({track:S,representation:f});const g=!this.params.tuning.isAudioDisabled&&Sm(h,p,f);g&&this.audioRepresentations.set(f.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();P(v),this.player.initRepresentations(v.id,(l=this.audioRepresentations.get(v.id))===null||l===void 0?void 0:l.id)}else d===Ie.REPRESENTATIOS_READY&&(this.videoState.setState(le.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(x(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Ie.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(De.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(De.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),$(d=>{var l;return d&&((l=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===m.READY),pe());this.subscription.add(x(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(x(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=Tt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),f=mi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?f!=null?f:d:d!=null?d:f;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ut(this.video)}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}const bm=5e3,We={};var Q;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const Li=(s,e)=>new li(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class ym{constructor(e){this.subscription=new ie,this.videoState=new de(Q.INITIALIZING),this.textTracksManager=new je,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==Q.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case Q.STOPPED:break;case Q.READY:case Q.PLAYING:case Q.PAUSED:this.stop();break;default:O(t)}break;case m.READY:switch(t){case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PLAYING:case Q.PAUSED:break;default:O(t)}break;case m.PLAYING:switch(t){case Q.PLAYING:break;case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PAUSED:this.playIfAllowed();break;default:O(t)}break;case m.PAUSED:switch(t){case Q.PAUSED:break;case Q.STOPPED:this.prepare();break;case Q.READY:this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case Q.PLAYING:this.pause();break;default:O(t)}break;default:O(i)}},this.video=ot(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),bm);import("hls.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){P(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=dt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Pt(this.video,e.isLooped,i)),this.subscription.add(nt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Li(this.hls,We.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),R(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i)),a(Li(this.hls,We.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,p;const v=c.name||c.height.toString(10),{width:f,height:S}=c,g=(p=vi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&p!==void 0?p:kt({width:f,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:v.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:f,height:S},fps:T};return this.trackLevels.set(v,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(Li(this.hls,We.Events.LEVEL_LOADING).pipe($(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Li(this.hls,We.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(q(_)).subscribe(t.currentVideoTrack$,i),this.subscription.add(qe(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(J(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),p=this.hls.currentLevel,v=this.hls.levels[p];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=x(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Q.PLAYING),await mt(this.video)||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Q.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}}const qa="X-Playback-Duration";var za=async s=>{const e=await Ft(s,{method:"HEAD"});return e.headers.has(qa)?parseInt(e.headers.get(qa),10):void 0};const Tm=s=>{let e=null;if(s.QUALITY&&(e=vi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kt({width:t,height:i})}return e!=null?e:null},co=async(s,e=s)=>{var t;const a=(await(await Ft(s)).text()).split(`
8
- `),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=pi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Tm(l);let p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let f;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(f={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:p,size:f,fps:v})}return n};var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(se||(se={}));class Em{constructor(e){var t;this.subscription=new ie,this.videoState=new de(se.STOPPED),this.textTracksManager=new je,this.manifests$=new y([]),this.liveOffset=new Ar,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===m.STOPPED){r!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&l.state===V.Requested){this.videoState.startTransitionTo(se.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case se.READY:a===m.READY?R(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case se.PAUSED:a===m.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===m.PAUSED&&(R(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return O(r)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),co(Ut(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=dt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===se.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===V.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ze({startTime:this.manifestStartTime$.pipe(q(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.selectManifest();if(J(e))return;const t=Ut(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),za(t).then(i=>{var r;if(!J(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(J(a)||!isFinite(a))try{Ft(t).then(n=>n.text()).then(n=>{var o;const u=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(u){const d=new URL(u,t).toString();za(d).then(l=>{J(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class $m{constructor(e){this.subscription=new ie,this.videoState=new de(oe.STOPPED),this.textTracksManager=new je,this.manifests$=new y([]),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===m.STOPPED){i!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&d.state===V.Requested&&this.seek(d.position),i){case oe.READY:r===m.READY?R(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case oe.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return O(i)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),co(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},r=dt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===V.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.selectManifest();J(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class Am{constructor(e){this.subscription=new ie,this.videoState=new de(ce.STOPPED),this.trackUrls={},this.textTracksManager=new je,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==m.PAUSED&&o.state===V.Requested&&this.seek(o.position),t){case ce.READY:i===m.READY?R(this.params.desiredState.playbackState,m.READY):i===m.PAUSED?(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ce.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},r=dt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&_(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();P(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];P(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=Vt(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ae(r))}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const ja=["stun:videostun.mycdn.me:80"],wm=1e3,_m=3,Us=()=>null;class km{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Us,this.externalStopCallback=Us,this.externalErrorCallback=Us,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:ja}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),wm)}normalizeOptions(e={}){const t={stunServerList:ja,maxRetryNumber:_m,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var re;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(re||(re={}));class Pm{constructor(e){this.videoState=new de(re.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case re.READY:i===m.PAUSED?(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case re.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ot(e.container),this.liveStreamClient=new km(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};x(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=dt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===re.READY&&this.videoState.setState(re.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(nt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case re.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case re.READY:break;case re.PAUSED:t.playbackState.setState(m.PAUSED);break;case re.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return O(n.to)}},i)).add(x(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ae.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(re.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class Wa{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var Rm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Fs,Vs,Hs,Gs,Ys,qs,Ci,zs,xi,js,Oi,Ws,Ni,Qs,Bi,Js;const ho=Rm(),ct=document.createElement("video"),Qe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Vs=(Fs=window.SourceBuffer)===null||Fs===void 0?void 0:Fs.prototype)===null||Vs===void 0?void 0:Vs.appendBuffer)),hls:Boolean(((Hs=ct.canPlayType)===null||Hs===void 0?void 0:Hs.call(ct,"application/x-mpegurl"))||((Gs=ct.canPlayType)===null||Gs===void 0?void 0:Gs.call(ct,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((Ys=ct.canPlayType)===null||Ys===void 0?void 0:Ys.call(ct,"video/mp4")),webm:Boolean((qs=ct.canPlayType)===null||qs===void 0?void 0:qs.call(ct,"video/webm")),cmaf:!0},ht={h264:Boolean((zs=(Ci=window.MediaSource)===null||Ci===void 0?void 0:Ci.isTypeSupported)===null||zs===void 0?void 0:zs.call(Ci,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((js=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||js===void 0?void 0:js.call(xi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Ws=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||Ws===void 0?void 0:Ws.call(Oi,'video/webm; codecs="vp9"')),aac:Boolean((Qs=(Ni=window.MediaSource)===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||Qs===void 0?void 0:Qs.call(Ni,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Js=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||Js===void 0?void 0:Js.call(Bi,'audio/webm; codecs="opus"'))},Ot=(ht.h264||ht.h265)&&ht.aac,ds=Qe.hls&&Re.mp4,Im=Boolean(window.WebSocket),Dm=()=>Object.keys(ht).filter(s=>ht[s]),Lm=(s,e=!1)=>s.filter(t=>{switch(t){case b.DASH:return Qe.mse&&Re.mp4&&Ot;case b.DASH_SEP:return Qe.mse&&Re.mp4&&Ot;case b.DASH_WEBM:return Qe.mse&&Re.webm&&ht.vp9&&ht.opus;case b.DASH_LIVE:return Qe.mse&&Re.mp4&&Ot;case b.DASH_LIVE_CMAF:return Qe.mse&&Re.mp4&&Ot&&Re.cmaf;case b.DASH_ONDEMAND:return Qe.mse&&Re.mp4&&Ot;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return ds||e&&Qe.mse&&Re.mp4&&Ot;case b.MPEG:return Re.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Qe.webrtc&&Im&&ht.h264&&(Re.mp4||Re.webm);default:return O(t)}}),Cm=()=>ho?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:ds?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],xm=()=>ho?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:ds?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],Qa=s=>s?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Om=s=>new li(e=>{const t=new ie,i=s.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$,n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ja={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Nm={cacheDuration:12e4},Bm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Mm={maxPausedTime:3e4},Ka={maxPausedTime:3e4};class Um{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),element$:new y(void 0)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Lm([...xm(),...Cm()],this.params.tuning.useHlsJs).filter(n=>_(e.sources[n])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(n=>!i.includes(n)),...t.filter(n=>i.includes(n))]:t;this.screenFormatsIterator=new Wa(r);const a=[...Qa(!0),...Qa(!1)];this.chromecastFormatsIterator=new Wa(a.filter(n=>_(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(J(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;P(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==V.None;this.params.desiredState.seekState.setState({state:V.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return O(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new lp({...n,source:o,config:Nm})}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new Ca({...n,source:o,format:e,config:Ka}):new gm({...n,source:o})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Ca({...n,source:o,format:e,config:Ka})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),ds||!this.params.tuning.useHlsJs?new $m({...n,source:o}):new ym({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Em({...n,source:o,config:Mm})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new Am({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new ap({...n,source:o,config:Bm})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Pm({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new hf({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return O(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return O(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return O(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return pi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,i=0;return e.add(x(this.providerOutput.error$,Om({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ja.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(q(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:L.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(q(({to:a})=>a===m.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===L.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=i<Ja.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Ce;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(Ce||(Ce={}));const fo=new Map;let $t=Ce.RUNTIME;const Ks=`vk-videoplayer-dummy-key-${Math.random()}`,Fm=()=>{try{localStorage.setItem(Ks,"test"),localStorage.removeItem(Ks),$t=Ce.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Ks),$t=Ce.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)$t=Ce.RUNTIME;else throw e}else throw s}};Fm();const Vm=s=>{var e,t;switch($t){case Ce.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case Ce.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case Ce.RUNTIME:return fo.get(s);default:O($t)}},Xa=(s,e)=>{switch($t){case Ce.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.RUNTIME:return void fo.set(s,e);default:O($t)}},ur=(s,e,t)=>t*e+(1-t)*s,po=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Hm=(s,e,t,i)=>{let r=0,a=t;const n=po(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class mo{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${i}`),this.smoothedSeries$=new Ye(`smoothed_${i}`),this.reportedSeries$=new Ye(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(J(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Gm extends mo{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ur(this.slow,e,this.params.emaAlphaSlow),this.fast=ur(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ym extends mo{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=po(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ur(this.emaSmoothed,e,this.params.emaAlpha);const i=Hm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Za{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Gm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ym({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const qm=5e3,en="one_video_throughput",tn="one_video_rtt",tt=window.navigator.connection,sn=()=>{const s=tt==null?void 0:tt.downlink;if(_(s)&&s!==10)return s*1e3},rn=()=>{const s=tt==null?void 0:tt.rtt;if(_(s)&&s!==3e3)return s},an=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class oi{constructor(e){var t,i;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=oi.load(en)||(e.useBrowserEstimation?sn():void 0)||qm,a=(i=(t=oi.load(tn))!==null&&t!==void 0?t:e.useBrowserEstimation?rn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(an(r,a,e.rttPenaltyRequestSize)),this.throughput=Za.getSmoothedValue(r,-1,e),this.rtt=Za.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=sn();u&&this.throughput.next(u);const d=rn();_(d)&&this.rtt.next(d)};tt&&"onchange"in tt&&this.subscription.add(M(tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Xa(en,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Xa(tn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ze({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>an(n,o,e.rttPenaltyRequestSize)),q(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=he();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(M(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(M(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=he();let a=0,n=he();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,he()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&he()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,he()-n,this.concurrentDownloads.size),a=0,n=he()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(oi.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Vm(e);if(_(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const nn={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},zm=s=>{const e={};for(const t of Object.keys(nn)){const i=nn[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var jm=({seekState:s,position$:e})=>x(s.stateChangeEnded$.pipe($(({to:t})=>{var i;return t.state===V.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),q(_)),e.pipe(q(()=>s.getState().state===V.None))),Wm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const on=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new li(a=>{let n;const o=s.transitionEnded$.pipe(q(p=>(p.from===m.PAUSED||p.from===m.STOPPED)&&p.to===m.PLAYING)),u=s.stateChangeEnded$.pipe(q(p=>p.from===m.PLAYING&&p.to===m.PAUSED)),d=e.stateChangeEnded$.pipe(q(({to:p})=>{var v,f;return p.state===V.Requested&&((f=(v=s.getTransition())===null||v===void 0?void 0:v.from)!==null&&f!==void 0?f:s.getState())===m.PLAYING})),l=e.stateChangeEnded$.pipe(q(({from:p,to:v})=>{var f,S;return p.state===V.Applying&&v.state===V.None&&((S=(f=s.getTransition())===null||f===void 0?void 0:f.from)!==null&&S!==void 0?S:s.getState())===m.PLAYING})),c=x(o,l).pipe($(()=>r.getValue()),q(_)),h=x(x(u,d,t),i).pipe($(()=>r.getValue()),q(_));return new ie().add(c.subscribe(p=>{n=p})).add(h.subscribe(p=>{if(J(n)||n===p)return;const v={from:n,to:p};n=void 0,a.next(v)}))});class ev{constructor(e={}){if(this.subscription=new ie,this.logger=new No,this.isPlaybackStarted=!1,this.desiredState={playbackState:new de(m.STOPPED),seekState:new de({state:V.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({})},this.info={playbackState$:new y(m.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),chromecastState$:new y(Ee.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new C,started$:new C,willPause$:new C,willResume$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:Mf},this.initLogs(),this.tuning=zm(e),this.chromecastInitializer=new Vo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new oi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Wm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Um({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===m.STOPPED&&e.startTransitionTo(m.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==m.PLAYING&&e.startTransitionTo(m.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===Ee.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===Ee.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(J(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return _(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(x(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(q(({from:e})=>e===m.STOPPED),ge()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(()=>!this.isPlaybackStarted),q(e=>e.to===m.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===V.Requested?this.desiredState.seekState.setState({...u,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,l)=>ji(d)?1:ji(l)?-1:Vi(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe($(u=>u?{start:u.from,end:u.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe($(u=>u.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),pe()).subscribe(this.info.volume$)).add(jm({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(x(e.providerOutput.endedEvent$.pipe(At(!0)),e.providerOutput.seekedEvent$.pipe(At(!1))).pipe(pe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe($(u=>({id:"NoProviders",category:L.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new y(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:u})=>u===m.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=x(e.providerOutput.isBuffering$,t,i).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||i.getValue();return u&&!d}),pe());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new ie;this.subscription.add(n);const o=x(M(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(q(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(pe()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new y(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(on({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(on({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(x(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=mi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(x(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),Bf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Nf(i)),this.providerContainer.current$.subscribe(({type:i})=>Ri("provider",i)),t.duration$.subscribe(i=>Ri("duration",i)),t.availableVideoTracks$.pipe(q(i=>!!i.length),ge()).subscribe(i=>Ri("tracks",i)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe($(i=>i==null?void 0:i.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(i=>this.subscription.add(i)),Ri("codecs",Dm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(r)})})};this.subscription.add(x(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const tv=`${Uo}@${Mo}`;export{Ee as ChromecastState,di as HttpConnectionType,rv as Observable,m as PlaybackState,ev as Player,tv as SDK_VERSION,av as Subject,nv as Subscription,ov as ValueSubject,b as VideoFormat,ae as VideoQuality};
6
+ import{ValueSubject as y,Subject as C,Subscription as ae,isNonNullable as k,ErrorCategory as D,isNullable as X,fromEvent as N,assertNever as M,merge as V,tap as Or,map as _,observableFrom as ke,filterChanged as pe,assertNonNullable as R,debounce as Ce,timeout as Co,combine as qe,once as ge,mapTo as Bt,filter as te,now as he,Observable as Ki,abortable as Ne,getExponentialDelay as Nr,interval as xo,safeStorage as hs,Logger as Oo,ACTIVE_LIVE_VALID_DELAY as No}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as sv,Subject as rv,Subscription as av,ValueSubject as nv}from"@vkontakte/videoplayer-shared/es2018.esm.js";import Bo from"lodash/debounce.js";const Mo="2.0.86-dev.f2e1ec4.0",Fo="es2018.esm.js";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var T;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(T||(T={}));var _e;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Te;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Te||(Te={}));var oi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(oi||(oi={}));var q;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(q||(q={}));var lt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(lt||(lt={}));var Uo=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vo{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(Te.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new y(Te.NOT_AVAILABLE),this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=k((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Uo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();X(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();X(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(N(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return M(r.sessionState)}})).add(V(N(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Or(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),ke([i.getCastState()])).pipe(pe(),_(Ho),Or(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Te.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const l=i.getCurrentSession();R(l);const d=l.getCastDevice(),u=(a=l.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(X(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Te.CONNECTED?k(this.connection$.getValue())?Te.CONNECTED:Te.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Ho=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Te.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Te.AVAILABLE;case cast.framework.CastState.CONNECTING:return Te.CONNECTING;case cast.framework.CastState.CONNECTED:return Te.CONNECTED;default:return M(s)}};var Br=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},tt=function(s){try{return!!s()}catch(e){return!0}},Yo=tt,Xi=!Yo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),on=Xi,dn=Function.prototype,Ks=dn.call,qo=on&&dn.bind.bind(Ks,Ks),it=on?qo:function(s){return function(){return Ks.apply(s,arguments)}},un=it,Go=un({}.toString),zo=un("".slice),Zi=function(s){return zo(Go(s),8,-1)},jo=it,Wo=tt,Qo=Zi,fs=Object,Jo=jo("".split),Ko=Wo(function(){return!fs("z").propertyIsEnumerable(0)})?function(s){return Qo(s)=="String"?Jo(s,""):fs(s)}:fs,es=function(s){return s==null},Xo=es,Zo=TypeError,ur=function(s){if(Xo(s))throw Zo("Can't call method on "+s);return s},ed=Ko,td=ur,ui=function(s){return ed(td(s))},id=function(){},Ht={},bi=function(s){return s&&s.Math==Math&&s},ze=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof Br=="object"&&Br)||function(){return this}()||Function("return this")(),Xs=typeof document=="object"&&document.all,sd=typeof Xs=="undefined"&&Xs!==void 0,ln={all:Xs,IS_HTMLDDA:sd},cn=ln,rd=cn.all,xe=cn.IS_HTMLDDA?function(s){return typeof s=="function"||s===rd}:function(s){return typeof s=="function"},ad=ze,nd=xe,Mr=ad.WeakMap,od=nd(Mr)&&/native code/.test(String(Mr)),Fr=xe,hn=ln,dd=hn.all,$t=hn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Fr(s)||s===dd}:function(s){return typeof s=="object"?s!==null:Fr(s)},ud=tt,ft=!ud(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Yt={},ld=ze,Ur=$t,Zs=ld.document,cd=Ur(Zs)&&Ur(Zs.createElement),fn=function(s){return cd?Zs.createElement(s):{}},hd=ft,fd=tt,pd=fn,pn=!hd&&!fd(function(){return Object.defineProperty(pd("div"),"a",{get:function(){return 7}}).a!=7}),md=ft,vd=tt,mn=md&&vd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Sd=$t,gd=String,bd=TypeError,At=function(s){if(Sd(s))return s;throw bd(gd(s)+" is not an object")},yd=Xi,yi=Function.prototype.call,st=yd?yi.bind(yi):function(){return yi.apply(yi,arguments)},lr={},ps=lr,ms=ze,Td=xe,Vr=function(s){return Td(s)?s:void 0},cr=function(s,e){return arguments.length<2?Vr(ps[s])||Vr(ms[s]):ps[s]&&ps[s][e]||ms[s]&&ms[s][e]},Ed=it,hr=Ed({}.isPrototypeOf),$d=typeof navigator!="undefined"&&String(navigator.userAgent)||"",vn=ze,vs=$d,Hr=vn.process,Yr=vn.Deno,qr=Hr&&Hr.versions||Yr&&Yr.version,Gr=qr&&qr.v8,Oe,Vi;Gr&&(Oe=Gr.split("."),Vi=Oe[0]>0&&Oe[0]<4?1:+(Oe[0]+Oe[1]));!Vi&&vs&&(Oe=vs.match(/Edge\/(\d+)/),(!Oe||Oe[1]>=74)&&(Oe=vs.match(/Chrome\/(\d+)/),Oe&&(Vi=+Oe[1])));var Ad=Vi,zr=Ad,wd=tt,Sn=!!Object.getOwnPropertySymbols&&!wd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&zr&&zr<41}),_d=Sn,gn=_d&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kd=cr,Pd=xe,Rd=hr,Id=gn,Dd=Object,bn=Id?function(s){return typeof s=="symbol"}:function(s){var e=kd("Symbol");return Pd(e)&&Rd(e.prototype,Dd(s))},Ld=String,fr=function(s){try{return Ld(s)}catch(e){return"Object"}},Cd=xe,xd=fr,Od=TypeError,pr=function(s){if(Cd(s))return s;throw Od(xd(s)+" is not a function")},Nd=pr,Bd=es,ts=function(s,e){var t=s[e];return Bd(t)?void 0:Nd(t)},Ss=st,gs=xe,bs=$t,Md=TypeError,Fd=function(s,e){var t,i;if(e==="string"&&gs(t=s.toString)&&!bs(i=Ss(t,s))||gs(t=s.valueOf)&&!bs(i=Ss(t,s))||e!=="string"&&gs(t=s.toString)&&!bs(i=Ss(t,s)))return i;throw Md("Can't convert object to primitive value")},Hi={},Ud={get exports(){return Hi},set exports(s){Hi=s}},Vd=!0,jr=ze,Hd=Object.defineProperty,Yd=function(s,e){try{Hd(jr,s,{value:e,configurable:!0,writable:!0})}catch(t){jr[s]=e}return e},qd=ze,Gd=Yd,Wr="__core-js_shared__",zd=qd[Wr]||Gd(Wr,{}),yn=zd,Qr=yn;(Ud.exports=function(s,e){return Qr[s]||(Qr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var jd=ur,Wd=Object,is=function(s){return Wd(jd(s))},Qd=it,Jd=is,Kd=Qd({}.hasOwnProperty),rt=Object.hasOwn||function(e,t){return Kd(Jd(e),t)},Xd=it,Zd=0,eu=Math.random(),tu=Xd(1 .toString),Tn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+tu(++Zd+eu,36)},iu=ze,su=Hi,Jr=rt,ru=Tn,au=Sn,nu=gn,xt=iu.Symbol,ys=su("wks"),ou=nu?xt.for||xt:xt&&xt.withoutSetter||ru,Me=function(s){return Jr(ys,s)||(ys[s]=au&&Jr(xt,s)?xt[s]:ou("Symbol."+s)),ys[s]},du=st,Kr=$t,Xr=bn,uu=ts,lu=Fd,cu=Me,hu=TypeError,fu=cu("toPrimitive"),pu=function(s,e){if(!Kr(s)||Xr(s))return s;var t=uu(s,fu),i;if(t){if(e===void 0&&(e="default"),i=du(t,s,e),!Kr(i)||Xr(i))return i;throw hu("Can't convert object to primitive value")}return e===void 0&&(e="number"),lu(s,e)},mu=pu,vu=bn,mr=function(s){var e=mu(s,"string");return vu(e)?e:e+""},Su=ft,gu=pn,bu=mn,Ti=At,Zr=mr,yu=TypeError,Ts=Object.defineProperty,Tu=Object.getOwnPropertyDescriptor,Es="enumerable",$s="configurable",As="writable";Yt.f=Su?bu?function(e,t,i){if(Ti(e),t=Zr(t),Ti(i),typeof e=="function"&&t==="prototype"&&"value"in i&&As in i&&!i[As]){var r=Tu(e,t);r&&r[As]&&(e[t]=i.value,i={configurable:$s in i?i[$s]:r[$s],enumerable:Es in i?i[Es]:r[Es],writable:!1})}return Ts(e,t,i)}:Ts:function(e,t,i){if(Ti(e),t=Zr(t),Ti(i),gu)try{return Ts(e,t,i)}catch(r){}if("get"in i||"set"in i)throw yu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ss=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Eu=ft,$u=Yt,Au=ss,li=Eu?function(s,e,t){return $u.f(s,e,Au(1,t))}:function(s,e,t){return s[e]=t,s},wu=Hi,_u=Tn,ea=wu("keys"),vr=function(s){return ea[s]||(ea[s]=_u(s))},Sr={},ku=od,En=ze,Pu=$t,Ru=li,ws=rt,_s=yn,Iu=vr,Du=Sr,ta="Object already initialized",er=En.TypeError,Lu=En.WeakMap,Yi,di,qi,Cu=function(s){return qi(s)?di(s):Yi(s,{})},xu=function(s){return function(e){var t;if(!Pu(e)||(t=di(e)).type!==s)throw er("Incompatible receiver, "+s+" required");return t}};if(ku||_s.state){var He=_s.state||(_s.state=new Lu);He.get=He.get,He.has=He.has,He.set=He.set,Yi=function(s,e){if(He.has(s))throw er(ta);return e.facade=s,He.set(s,e),e},di=function(s){return He.get(s)||{}},qi=function(s){return He.has(s)}}else{var Rt=Iu("state");Du[Rt]=!0,Yi=function(s,e){if(ws(s,Rt))throw er(ta);return e.facade=s,Ru(s,Rt,e),e},di=function(s){return ws(s,Rt)?s[Rt]:{}},qi=function(s){return ws(s,Rt)}}var Ou={set:Yi,get:di,has:qi,enforce:Cu,getterFor:xu},Nu=Xi,$n=Function.prototype,ia=$n.apply,sa=$n.call,Bu=typeof Reflect=="object"&&Reflect.apply||(Nu?sa.bind(ia):function(){return sa.apply(ia,arguments)}),Mu=Zi,Fu=it,An=function(s){if(Mu(s)==="Function")return Fu(s)},wn={},_n={},kn={}.propertyIsEnumerable,Pn=Object.getOwnPropertyDescriptor,Uu=Pn&&!kn.call({1:2},1);_n.f=Uu?function(e){var t=Pn(this,e);return!!t&&t.enumerable}:kn;var Vu=ft,Hu=st,Yu=_n,qu=ss,Gu=ui,zu=mr,ju=rt,Wu=pn,ra=Object.getOwnPropertyDescriptor;wn.f=Vu?ra:function(e,t){if(e=Gu(e),t=zu(t),Wu)try{return ra(e,t)}catch(i){}if(ju(e,t))return qu(!Hu(Yu.f,e,t),e[t])};var Qu=tt,Ju=xe,Ku=/#|\.prototype\./,ci=function(s,e){var t=Zu[Xu(s)];return t==tl?!0:t==el?!1:Ju(e)?Qu(e):!!e},Xu=ci.normalize=function(s){return String(s).replace(Ku,".").toLowerCase()},Zu=ci.data={},el=ci.NATIVE="N",tl=ci.POLYFILL="P",il=ci,aa=An,sl=pr,rl=Xi,al=aa(aa.bind),Rn=function(s,e){return sl(s),e===void 0?s:rl?al(s,e):function(){return s.apply(e,arguments)}},Ei=ze,nl=Bu,ol=An,dl=xe,ul=wn.f,ll=il,It=lr,cl=Rn,Dt=li,na=rt,hl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return nl(s,this,arguments)};return e.prototype=s.prototype,e},rs=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Ei:r?Ei[t]:(Ei[t]||{}).prototype,o=i?It:It[t]||Dt(It,t,{})[t],l=o.prototype,d,u,c,h,f,v,S,b,m;for(h in e)d=ll(i?h:t+(r?".":"#")+h,s.forced),u=!d&&n&&na(n,h),v=o[h],u&&(s.dontCallGetSet?(m=ul(n,h),S=m&&m.value):S=n[h]),f=u&&S?S:e[h],!(u&&typeof v==typeof f)&&(s.bind&&u?b=cl(f,Ei):s.wrap&&u?b=hl(f):a&&dl(f)?b=ol(f):b=f,(s.sham||f&&f.sham||v&&v.sham)&&Dt(b,"sham",!0),Dt(o,h,b),a&&(c=t+"Prototype",na(It,c)||Dt(It,c,{}),Dt(It[c],h,f),s.real&&l&&(d||!l[h])&&Dt(l,h,f)))},tr=ft,fl=rt,In=Function.prototype,pl=tr&&Object.getOwnPropertyDescriptor,gr=fl(In,"name"),ml=gr&&function(){}.name==="something",vl=gr&&(!tr||tr&&pl(In,"name").configurable),Sl={EXISTS:gr,PROPER:ml,CONFIGURABLE:vl},Dn={},gl=Math.ceil,bl=Math.floor,yl=Math.trunc||function(e){var t=+e;return(t>0?bl:gl)(t)},Tl=yl,br=function(s){var e=+s;return e!==e||e===0?0:Tl(e)},El=br,$l=Math.max,Al=Math.min,wl=function(s,e){var t=El(s);return t<0?$l(t+e,0):Al(t,e)},_l=br,kl=Math.min,Pl=function(s){return s>0?kl(_l(s),9007199254740991):0},Rl=Pl,yr=function(s){return Rl(s.length)},Il=ui,Dl=wl,Ll=yr,oa=function(s){return function(e,t,i){var r=Il(e),a=Ll(r),n=Dl(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},Cl={includes:oa(!0),indexOf:oa(!1)},xl=it,ks=rt,Ol=ui,Nl=Cl.indexOf,Bl=Sr,da=xl([].push),Ml=function(s,e){var t=Ol(s),i=0,r=[],a;for(a in t)!ks(Bl,a)&&ks(t,a)&&da(r,a);for(;e.length>i;)ks(t,a=e[i++])&&(~Nl(r,a)||da(r,a));return r},Ln=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Fl=Ml,Ul=Ln,Vl=Object.keys||function(e){return Fl(e,Ul)},Hl=ft,Yl=mn,ql=Yt,Gl=At,zl=ui,jl=Vl;Dn.f=Hl&&!Yl?Object.defineProperties:function(e,t){Gl(e);for(var i=zl(t),r=jl(t),a=r.length,n=0,o;a>n;)ql.f(e,o=r[n++],i[o]);return e};var Wl=cr,Ql=Wl("document","documentElement"),Jl=At,Kl=Dn,ua=Ln,Xl=Sr,Zl=Ql,ec=fn,tc=vr,la=">",ca="<",ir="prototype",sr="script",Cn=tc("IE_PROTO"),Ps=function(){},xn=function(s){return ca+sr+la+s+ca+"/"+sr+la},ha=function(s){s.write(xn("")),s.close();var e=s.parentWindow.Object;return s=null,e},ic=function(){var s=ec("iframe"),e="java"+sr+":",t;return s.style.display="none",Zl.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xn("document.F=Object")),t.close(),t.F},$i,Ni=function(){try{$i=new ActiveXObject("htmlfile")}catch(e){}Ni=typeof document!="undefined"?document.domain&&$i?ha($i):ic():ha($i);for(var s=ua.length;s--;)delete Ni[ir][ua[s]];return Ni()};Xl[Cn]=!0;var On=Object.create||function(e,t){var i;return e!==null?(Ps[ir]=Jl(e),i=new Ps,Ps[ir]=null,i[Cn]=e):i=Ni(),t===void 0?i:Kl.f(i,t)},sc=tt,rc=!sc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),ac=rt,nc=xe,oc=is,dc=vr,uc=rc,fa=dc("IE_PROTO"),rr=Object,lc=rr.prototype,Nn=uc?rr.getPrototypeOf:function(s){var e=oc(s);if(ac(e,fa))return e[fa];var t=e.constructor;return nc(t)&&e instanceof t?t.prototype:e instanceof rr?lc:null},cc=li,Bn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:cc(s,e,t),s},hc=tt,fc=xe,pc=$t,mc=On,pa=Nn,vc=Bn,Sc=Me,ar=Sc("iterator"),Mn=!1,Ze,Rs,Is;[].keys&&(Is=[].keys(),"next"in Is?(Rs=pa(pa(Is)),Rs!==Object.prototype&&(Ze=Rs)):Mn=!0);var gc=!pc(Ze)||hc(function(){var s={};return Ze[ar].call(s)!==s});gc?Ze={}:Ze=mc(Ze);fc(Ze[ar])||vc(Ze,ar,function(){return this});var Fn={IteratorPrototype:Ze,BUGGY_SAFARI_ITERATORS:Mn},bc=Me,yc=bc("toStringTag"),Un={};Un[yc]="z";var Tr=String(Un)==="[object z]",Tc=Tr,Ec=xe,Bi=Zi,$c=Me,Ac=$c("toStringTag"),wc=Object,_c=Bi(function(){return arguments}())=="Arguments",kc=function(s,e){try{return s[e]}catch(t){}},as=Tc?Bi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kc(e=wc(s),Ac))=="string"?t:_c?Bi(e):(i=Bi(e))=="Object"&&Ec(e.callee)?"Arguments":i},Pc=Tr,Rc=as,Ic=Pc?{}.toString:function(){return"[object "+Rc(this)+"]"},Dc=Tr,Lc=Yt.f,Cc=li,xc=rt,Oc=Ic,Nc=Me,ma=Nc("toStringTag"),Vn=function(s,e,t,i){if(s){var r=t?s:s.prototype;xc(r,ma)||Lc(r,ma,{configurable:!0,value:e}),i&&!Dc&&Cc(r,"toString",Oc)}},Bc=Fn.IteratorPrototype,Mc=On,Fc=ss,Uc=Vn,Vc=Ht,Hc=function(){return this},Yc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Mc(Bc,{next:Fc(+!i,t)}),Uc(s,r,!1,!0),Vc[r]=Hc,s},qc=rs,Gc=st,Hn=Sl,zc=Yc,jc=Nn,Wc=Vn,va=Bn,Qc=Me,Sa=Ht,Yn=Fn,Jc=Hn.PROPER;Hn.CONFIGURABLE;Yn.IteratorPrototype;var Ai=Yn.BUGGY_SAFARI_ITERATORS,Ds=Qc("iterator"),ga="keys",wi="values",ba="entries",Kc=function(){return this},Xc=function(s,e,t,i,r,a,n){zc(t,e,i);var o=function(m){if(m===r&&h)return h;if(!Ai&&m in u)return u[m];switch(m){case ga:return function(){return new t(this,m)};case wi:return function(){return new t(this,m)};case ba:return function(){return new t(this,m)}}return function(){return new t(this)}},l=e+" Iterator",d=!1,u=s.prototype,c=u[Ds]||u["@@iterator"]||r&&u[r],h=!Ai&&c||o(r),f=e=="Array"&&u.entries||c,v,S,b;if(f&&(v=jc(f.call(new s)),v!==Object.prototype&&v.next&&(Wc(v,l,!0,!0),Sa[l]=Kc)),Jc&&r==wi&&c&&c.name!==wi&&(d=!0,h=function(){return Gc(c,this)}),r)if(S={values:o(wi),keys:a?h:o(ga),entries:o(ba)},n)for(b in S)(Ai||d||!(b in u))&&va(u,b,S[b]);else qc({target:e,proto:!0,forced:Ai||d},S);return n&&u[Ds]!==h&&va(u,Ds,h,{name:r}),Sa[e]=h,S},Zc=function(s,e){return{value:s,done:e}},eh=ui,Er=id,ya=Ht,qn=Ou,th=Yt.f,ih=Xc,_i=Zc,sh=Vd,rh=ft,Gn="Array Iterator",ah=qn.set,nh=qn.getterFor(Gn);ih(Array,"Array",function(s,e){ah(this,{type:Gn,target:eh(s),index:0,kind:e})},function(){var s=nh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,_i(void 0,!0)):t=="keys"?_i(i,!1):t=="values"?_i(e[i],!1):_i([i,e[i]],!1)},"values");var Ta=ya.Arguments=ya.Array;Er();Er();Er();if(!sh&&rh&&Ta.name!=="values")try{th(Ta,"name",{value:"values"})}catch(s){}var oh=Me,dh=Ht,uh=oh("iterator"),lh=Array.prototype,ch=function(s){return s!==void 0&&(dh.Array===s||lh[uh]===s)},hh=as,Ea=ts,fh=es,ph=Ht,mh=Me,vh=mh("iterator"),zn=function(s){if(!fh(s))return Ea(s,vh)||Ea(s,"@@iterator")||ph[hh(s)]},Sh=st,gh=pr,bh=At,yh=fr,Th=zn,Eh=TypeError,$h=function(s,e){var t=arguments.length<2?Th(s):e;if(gh(t))return bh(Sh(t,s));throw Eh(yh(s)+" is not iterable")},Ah=st,$a=At,wh=ts,_h=function(s,e,t){var i,r;$a(s);try{if(i=wh(s,"return"),!i){if(e==="throw")throw t;return t}i=Ah(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return $a(i),t},kh=Rn,Ph=st,Rh=At,Ih=fr,Dh=ch,Lh=yr,Aa=hr,Ch=$h,xh=zn,wa=_h,Oh=TypeError,Mi=function(s,e){this.stopped=s,this.result=e},_a=Mi.prototype,Nh=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=kh(e,i),d,u,c,h,f,v,S,b=function(g){return d&&wa(d,"normal",g),new Mi(!0,g)},m=function(g){return r?(Rh(g),o?l(g[0],g[1],b):l(g[0],g[1])):o?l(g,b):l(g)};if(a)d=s.iterator;else if(n)d=s;else{if(u=xh(s),!u)throw Oh(Ih(s)+" is not iterable");if(Dh(u)){for(c=0,h=Lh(s);h>c;c++)if(f=m(s[c]),f&&Aa(_a,f))return f;return new Mi(!1)}d=Ch(s,u)}for(v=a?s.next:d.next;!(S=Ph(v,d)).done;){try{f=m(S.value)}catch(g){wa(d,"throw",g)}if(typeof f=="object"&&f&&Aa(_a,f))return f}return new Mi(!1)},Bh=mr,Mh=Yt,Fh=ss,Uh=function(s,e,t){var i=Bh(e);i in s?Mh.f(s,i,Fh(0,t)):s[i]=t},Vh=rs,Hh=Nh,Yh=Uh;Vh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Hh(e,function(i,r){Yh(t,i,r)},{AS_ENTRIES:!0}),t}});var qh=lr,Gh=qh.Object.fromEntries,zh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},jh=zh,Wh=ze,Qh=as,Jh=li,ka=Ht,Kh=Me,Pa=Kh("toStringTag");for(var Ls in jh){var Ra=Wh[Ls],Cs=Ra&&Ra.prototype;Cs&&Qh(Cs)!==Pa&&Jh(Cs,Pa,Ls),ka[Ls]=ka.Array}var Xh=Gh,Zh=Xh,ef=Zh,tf=ef,hi=tf,Nt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Nt||(Nt={}));var Mt=(s,e=0,t=Nt.OFFSET_P)=>{switch(t){case Nt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Nt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:M(t)}return s},I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},re;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(re||(re={}));const Be={[re.Q_144P]:{width:256,height:144},[re.Q_240P]:{width:428,height:240},[re.Q_360P]:{width:640,height:360},[re.Q_480P]:{width:856,height:480},[re.Q_720P]:{width:1280,height:720},[re.Q_1080P]:{width:1920,height:1080},[re.Q_1440P]:{width:2560,height:1440},[re.Q_2160P]:{width:3840,height:2160},[re.Q_4320P]:{width:7680,height:4320}},Fi=(s,e)=>Be[s].height>Be[e].height,sf=(s,e)=>Be[s].height>=Be[e].height,ri=(s,e)=>Be[s].height<Be[e].height,rf=(s,e)=>Be[s].height<=Be[e].height,af=s=>s.sort((e,t)=>e===t?0:e===re.INVARIANT?1:t===re.INVARIANT?-1:ri(e,t)?1:-1)[0],nf=Object.keys(Be).sort((s,e)=>ri(s,e)?-1:1),wt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return nf.find(r=>{const a=Be[r];return a.width>=i&&a.height>=t})},of=s=>Be[s].height,Gi=s=>s===re.INVARIANT;class de{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||k(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const df=s=>{switch(s){case T.MPEG:case T.DASH:case T.DASH_SEP:case T.DASH_ONDEMAND:case T.DASH_WEBM:case T.HLS:case T.HLS_ONDEMAND:return!1;case T.DASH_LIVE:case T.DASH_LIVE_CMAF:case T.HLS_LIVE:case T.HLS_LIVE_CMAF:case T.DASH_LIVE_WEBM:case T.WEB_RTC_LIVE:return!0;default:return M(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const uf=5,lf=5,cf=500,Ia=7e3;class hf{constructor(e){this.subscription=new ae,this.loadMediaTimeoutSubscription=new ae,this.videoState=new de(Y.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===q.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case Y.PLAYING:case Y.PAUSED:case Y.READY:break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:M(i)}break}case p.PLAYING:{switch(i){case Y.PLAYING:break;case Y.PAUSED:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.READY:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:M(i)}break}case p.PAUSED:{switch(i){case Y.PLAYING:this.videoState.startTransitionTo(Y.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Y.PAUSED:break;case Y.READY:this.videoState.startTransitionTo(Y.PAUSED),this.videoState.setState(Y.PAUSED);break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:M(i)}break}default:M(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(df(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ae;this.subscription.add(e),this.subscription.add(V(this.videoState.stateChangeStarted$.pipe(_(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(_(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(Ce(cf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===q.Applying||Math.abs(o-a)>uf)&&r.next(o),a=o})),e.add(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<lf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:M(n)}}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(Y.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(Y.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:q.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PLAYING||e===Y.PAUSED)&&(this.videoState.setState(Y.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===Y.READY&&this.videoState.setState(Y.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==Y.STOPPED&&this.videoState.setState(Y.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case T.MPEG:{const u=i[e];R(u);const c=af(Object.keys(u));R(c);const h=u[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case T.HLS:case T.HLS_ONDEMAND:{const u=i[e];R(u),r=u.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case T.DASH_SEP:case T.DASH_ONDEMAND:case T.DASH_WEBM:{const u=i[e];R(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case T.DASH_LIVE_CMAF:{const u=i[e];R(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case T.HLS_LIVE:case T.HLS_LIVE_CMAF:{const u=i[e];R(u),r=Mt(u.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case T.DASH:case T.DASH_LIVE:case T.WEB_RTC_LIVE:{const u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:D.VIDEO_PIPELINE,message:u,thrown:c}),c}case T.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:l,subtitle:d}=this.params.meta;return k(l)&&(o.metadata.title=l),k(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===q.Applying||i.state===q.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Co(Ia).subscribe(()=>a(`timeout(${Ia})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===q.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Da{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class jn extends Da{constructor(){super(),this.listeners||Da.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Wn=class{constructor(){Object.defineProperty(this,"signal",{value:new jn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Wn.prototype[Symbol.toStringTag]="AbortController",jn.prototype[Symbol.toStringTag]="AbortSignal");function Qn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function ff(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Qn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,u){let c;u&&u.signal&&(c=u.signal,delete u.signal);const h=new t(d,u);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(l,d)=>{const u=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.signal:void 0;if(u){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(u.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{u.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(l,d)])}return n(l,d)},Request:a}}const ns=Qn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jn=ns?ff({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ft=ns?Jn.fetch:window.fetch;ns?Jn.Request:window.Request;const Et=ns?Wn:window.AbortController,ti=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ai{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=ti(r.request);if(a>=i.from&&n<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(i.url);r&&a&&a.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(ti),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const f=i[h][1];f-r<=2*this.params.minDataSize&&(a=Math.max(a,f))}r===0?a=Math.max(a,r+this.params.minInitSize):a=Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${r}-${a}`);const o=n.toString(),l=new Et,d=l.signal,u={url:e,from:r,to:a,loaded:0,data:null,abortController:l};d.addEventListener("abort",()=>this.onBigRequestAbort(u));const c=h=>{var f,v;throw(v=(f=this.params).onError)===null||v===void 0||v.call(f,{id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:h}),h};return Ft(o,{signal:d}).then(h=>{var f,v,S;if(u.response=h,!h.ok||!h.body){this.onBigRequestError(u);return}const[b,m]=h.body.tee();(v=(f=this.params).onDownloadStream)===null||v===void 0||v.call(f,m);const g=b.getReader(),E=parseInt((S=h.headers.get("Content-Length"))!==null&&S!==void 0?S:"",10)||a-r+1;u.data=new ArrayBuffer(E);const $=new Uint8Array(u.data),w=async({done:x,value:W})=>{x?this.onBigRequestProgress(u):W&&($.set(W,u.loaded),u.loaded+=W.byteLength,this.onBigRequestProgress(u),await(g==null?void 0:g.read().then(w,ai.suppressStreamErrors).catch(c)))};g==null||g.read().then(w,ai.suppressStreamErrors).catch(c)},ai.suppressAbort).catch(h=>this.onBigRequestError(u,h)),u}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:a,response:n}){var o,l,d,u,c,h,f,v;if(!this.activeRequests.has(e)||!a)return;const S=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const b of S){const{request:m}=b,[g,E]=ti(m),$=g>=t&&E<=t+r,w=t>=g&&t+r<E,x=a.slice(g-t,Math.min(E-t+1,r));if(($||w)&&(m.requestStartDate=(l=m.requestStartDate)!==null&&l!==void 0?l:new Date,m.firstByteDate=(d=m.firstByteDate)!==null&&d!==void 0?d:new Date,m.bytesLoaded=x.byteLength,m.bytesTotal=i-t),$){m.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((u=this.dashJsRequestQueue.get(e))!==null&&u!==void 0?u:[]).filter(F=>F!==b)),(c=b.success)===null||c===void 0||c.call(b,x,"",e);const W=n?Array.from(n.headers.entries()).map(([F,U])=>`${F}: ${U}`).join(`\r
7
+ `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(m,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,W,[])}else w&&((v=b.progress)===null||v===void 0||v.call(b,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var a,n,o,l;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:D.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const u of d){const[c,h]=ti(u.request);(c>=t&&c<i||h>t&&h<=i)&&((l=u==null?void 0:u.error)===null||l===void 0||l.call(u,u.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,a;if(!this.activeRequests.has(e))return;const n=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const o of n){const[l,d]=ti(o.request);(l>=t&&l<i||d>t&&d<=i)&&((a=o==null?void 0:o.abort)===null||a===void 0||a.call(o,o.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class zi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(zi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;zi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const pf=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new zi(r,e,i)}}),mf=(s,e)=>{const t=new ai(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return pf(n,t)}}},!0),()=>t.destroy()};var vf=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Sf=s=>{const e=new y(1/0),t=new C,i=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},l=u=>{var c,h,f,v,S;const b=hi(u.getAllResponseHeaders().trim().split(/[\n\r]+/).map(E=>E.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const E=parseInt((c=u.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),$=parseInt((h=u.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),w=(f=$!=null?$:E*1e3)!==null&&f!==void 0?f:NaN;k(w)&&!isNaN(w)&&e.next(w)}const m=(v=b["x-delivery-type"])!==null&&v!==void 0?v:oi.HTTP1,g=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(m),r.next(g)},d=u=>{u.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:u}=this,c=u.load.bind(u);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...S){return l(this),f(...S)},h.progress=function(...S){return d(this),v(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Ut=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},gf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Ut}),!0),bf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ge=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),l=X(r),d=new ae;return r&&d.add(r.subscribe(u=>{const c=s.getState();i(u,c)&&s.setState(u)},a)),i(o,n)||(t(n),l&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(u=>{t(u.to),l&&s.setState(u.to)},a)),d},_t=(s,e,t)=>Ge(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),at=(s,e,t,i)=>Ge(e,()=>({muted:s.muted,volume:s.volume}),r=>{k(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),pt=(s,e,t,i)=>Ge(e,()=>s.playbackRate,r=>{k(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),yf=s=>["__",s.language,s.label].join("|"),Tf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class je{constructor(){this.available$=new C,this.current$=new y(void 0),this.error$=new C,this.subscription=new ae,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ge(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{k(a)&&this.setExternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ge(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(N(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(V(N(e,"addtrack"),N(e,"removetrack"),ke(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(N(e,"change"),ke(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),pe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(N(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var l,d,u,c,h;const f=(d=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(N(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(je.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:yf(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))k(e)&&Tf(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){R(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var nt=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class $r{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}const Kn=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},La=s=>{const e=Kn(s);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===s)},Ef=s=>{const e=Kn(s);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var Xn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const nr=3;class $f{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<nr&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||nr))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Zn=(s,e,t=nr)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let l=a-1;l>=0;l--)s.end(l)+t>=i&&(i=s.start(l));for(let l=a+1;l<s.length;l++)s.start(l)-t<=r&&(r=s.end(l))}}return{from:i,to:r}};const Af=50,wf=s=>s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,ot=s=>{const e=E=>N(s,E).pipe(Bt(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>N(s,E))).pipe(_(E=>E.type==="ended"?s.readyState<2:s.readyState<3),pe()),r=V(N(s,"progress"),N(s,"timeupdate")).pipe(_(()=>Zn(s.buffered,s.currentTime))),a=Xn()?qe({play:e("play").pipe(ge()),playing:e("playing")}).pipe(Bt(void 0)):e("playing"),n=N(s,"playing").pipe(Ce(Af),_(()=>wf(s))),o=N(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),l=N(s,"ratechange").pipe(_(()=>s.playbackRate)),d=N(s,"error").pipe(te(()=>Boolean(s.error||s.played.length)),_(()=>{var E;const $=s.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(E=s.error)!==null&&E!==void 0?E:void 0}})),u=N(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new C,h=.3;let f;u.subscribe(E=>{s.loop&&k(f)&&k(E)&&f>=s.duration-h&&E<=h&&c.next(f),f=E});const v=N(s,"enterpictureinpicture"),S=N(s,"leavepictureinpicture"),b=new y(Ef(s));v.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const m=new y(La(s));return N(s,"fullscreenchange").pipe(_(()=>La(s))).subscribe(m),{playing$:a,pause$:e("pause").pipe(te(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:N(s,"durationchange").pipe(_(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:l,inPiP$:b,inFullscreen$:m}},Ar=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var _f=rs,kf=is,Pf=yr,Rf=br;_f({target:"Array",proto:!0},{at:function(e){var t=kf(this),i=Pf(t),r=Rf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var If=cr,eo=If,Df=eo,Lf=Df("Array","at"),Cf=Lf,xf=Cf,Of=xf,Nf=Of,Je=Nf;let wr=!1,Ke={};const Bf=s=>{wr=s},Mf=()=>{Ke={}},Ff=s=>{s(Ke)},ki=(s,e)=>{var t;wr&&(Ke.meta=(t=Ke.meta)!==null&&t!==void 0?t:{},Ke.meta[s]=e)};class Ye{constructor(e){this.name=e}next(e){var t,i;if(!wr)return;Ke.series=(t=Ke.series)!==null&&t!==void 0?t:{};const r=(i=Ke.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ke.series[this.name]=r}}const Uf=new Ye("best_bitrate"),Vf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Hf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const fi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:l,history:d})=>{var u,c,h,f;const v=i.usePixelRatio&&(u=window.devicePixelRatio)!==null&&u!==void 0?u:1,S=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},b=S&&wt(S),m=i.considerPlaybackRate&&k(o)?o:1,g=s.filter(B=>!Gi(B.quality)).sort((B,O)=>Fi(B.quality,O.quality)?-1:1),E=(c=Je(g,-1))===null||c===void 0?void 0:c.quality,$=(h=Je(g,0))===null||h===void 0?void 0:h.quality,w=X(r)||k(r.min)&&k(r.max)&&ri(r.max,r.min)||k(r.min)&&$&&Fi(r.min,$)||k(r.max)&&E&&ri(r.max,E),x=m*Vf(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F=g.filter(B=>{const O=b?ri(B.quality,b):!0,ee=k(t)&&isFinite(t)&&k(B.bitrate)?t-a>=B.bitrate*x:!0,ue=i.lazyQualitySwitch&&k(i.minBufferToSwitchUp)&&l&&!Gi(l.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Fi(B.quality,l.quality),me=w||(X(r.max)||rf(B.quality,r.max))&&(X(r.min)||sf(B.quality,r.min));return O&&ee&&!ue&&me})[0];F&&F.bitrate&&Uf.next(F.bitrate);const U=(f=F!=null?F:g[Math.ceil((g.length-1)/2)])!==null&&f!==void 0?f:s[0],Z=U&&d&&d.history[U.id]&&he()-d.history[U.id]<=i.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!Z&&d.recordSelection(U),Z&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),B}return d==null||d.recordSwitch(U),U};var Ae=s=>new URL(s).hostname;const Yf=300,ji=(s,e=Yf)=>new Ki(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Bo(n=>{const o=n[0];if(!o)return;let l,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,l=o.contentBoxSize[0].inlineSize):o.contentRect&&(l=o.contentRect.width,d=o.contentRect.height),k(l)&&k(d)&&t.next({width:l,height:d})},e));return a.observe(s),()=>a.disconnect()}),dt=s=>{try{s.pause(),s.playbackRate=0,s.removeAttribute("src"),s.load(),s.remove()}catch(e){console.error(e)}},qf=5e3,ii={};var G;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(G||(G={}));const Se=(s,e)=>new Ki(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Ca{constructor(e){this.subscription=new ae,this.videoState=new de(G.DOWNLOADING_LIB),this.textTracksManager=new je,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new $r,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===G.DOWNLOADING_LIB||t===G.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===q.Requested&&t!==G.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case G.STOPPED:break;case G.PLAYING:case G.PAUSED:case G.READY:this.stop();break;default:M(t)}break}case p.READY:{switch(t){case G.STOPPED:this.prepare();break;case G.PLAYING:case G.PAUSED:case G.READY:break;default:M(t)}break}case p.PLAYING:{switch(t){case G.PLAYING:break;case G.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case G.READY:this.play();break;case G.STOPPED:this.prepare();break;default:M(t)}break}case p.PAUSED:{switch(t){case G.PLAYING:this.pause(),this.liveOffset.pause();break;case G.PAUSED:break;case G.READY:this.videoState.setState(G.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case G.STOPPED:this.prepare();break;default:M(t)}break}default:M(i)}},this.video=nt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:D.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),qf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ii.MediaPlayer=r.MediaPlayer,ii.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(ii.MediaPlayer,"dashjs not loaded"),R(ii.Debug,"dashjs not loaded"),this.player=ii.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Ar(t.frameRate+""):void 0),!0)),(this.params.format===T.DASH_WEBM||this.params.format===T.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=mf(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&bf(this.player),vf(this.player),this.params.tuning.requestQuick&&gf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(G.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,g)=>this.subscription.add(m.subscribe(g,i));r(ji(this.video),this.elementSize$),r(Se(this.player,"error").pipe(_(m=>{const g=typeof m.error=="object"?m.error.code:m.error,E=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${g}`,message:E}})),e.error$),r(Se(this.player,"playbackError").pipe(_(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(te(({mediaType:m})=>m==="video"),_(({newQuality:m})=>{var g;return(g=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===m))===null||g===void 0?void 0:g.track}));a.pipe(te(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(te(({to:m})=>m===G.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(Ge(t.videoTrack,()=>{var m,g;const E=this.player.getQualityFor("video");return(g=(m=this.videoTracks.find(({bitrateInfo:$})=>$.qualityIndex===E))===null||m===void 0?void 0:m.track)===null||g===void 0?void 0:g.id},m=>{var g;if(X(m))return;const E=(g=this.videoTracks.find(({track:$})=>$.id===m))===null||g===void 0?void 0:g.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:a.pipe(_(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Ge(t.autoVideoTrackSwitching,()=>{var m,g,E;return(E=(g=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||g===void 0?void 0:g.autoSwitchBitrate)===null||E===void 0?void 0:E.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(te(({mediaType:m})=>m==="video"),_(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:g}})=>{var E,$;const w=this.player.getDashMetrics(),x=w.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),W=(E=w.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&E!==void 0?E:oi.HTTP1,F=($={1:!0,0:!1}[x])!==null&&$!==void 0?$:void 0;this.params.output.httpConnectionType$.next(W),this.params.output.httpConnectionReused$.next(F),e.hostname$.next(Ae(g))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:g,availableFrom:E}}})=>{this.isLive$.next(g),this.availableFrom$.next(E.getTime()),g||e.duration$.next(m),this.videoTracks=[];const $=this.player.getQualityFor("video");let w;for(const x of this.player.getBitrateInfoListFor("video")){const W=x.qualityIndex.toString(10),F=wt(x),U=x.bitrate/1e3,Z={width:x.width,height:x.height},B=this.frameRatesByFrameHeight[x.height];if(F){const O={id:W,quality:F,bitrate:U,size:Z,fps:B};this.videoTracks.push({track:O,bitrateInfo:x}),x.qualityIndex===$&&(w=O)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:x})=>x)),w&&e.currentVideoTrack$.next(w),this.videoState.setState(G.STREAM_INITIALIZED),this.videoState.startTransitionTo(G.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const g=m.requestEndDate.getTime()-m.firstByteDate.getTime(),E=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,g)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),g=fi(this.videoTracks.map(({track:$})=>$),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),E=this.videoTracks.find(({track:$})=>$===g);E!=null&&E.bitrateInfo&&this.player.setQualityFor("video",E==null?void 0:E.bitrateInfo.qualityIndex,!1)}),r(qe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(te(k))}).pipe(te(({isLive:m})=>m),_(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(_(({time:m})=>m!=null?m:0));r(qe({availableFrom:this.availableFrom$.pipe(te(k)),currentTime:n}),({availableFrom:m,currentTime:g})=>this.params.output.liveTime$.next(m+g*1e3)),r(n.pipe(te(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe(_(()=>Zn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(G.PLAYING),I(t.playbackState,p.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(G.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(G.PAUSED),I(t.playbackState,p.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===G.READY&&this.videoState.setState(G.READY)}),r(this.isLive$,e.isLive$),r(ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));r(o,this.syncPlayback);const{playbackDuration$:l,ping$:d,connectionType$:u,connectionReused$:c}=Sf(this.player);r(u,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(l,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(qe({isLive:this.isLive$,isShort:e.duration$.pipe(_(m=>m<60))}),({isLive:m,isShort:g})=>{const E=!m&&g;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(n.pipe(te(m=>m>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ge(),Bt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(_t(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:S,inFullscreen$:b}=ot(this.video);this.subscription.add(at(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(pt(this.video,t.playbackRate,v,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(G.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(G.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=Mt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Nt.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(G.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(G.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}dt(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var pi=s=>{switch(s){case"mobile":return re.Q_144P;case"lowest":return re.Q_240P;case"low":return re.Q_360P;case"sd":case"medium":return re.Q_480P;case"hd":case"high":return re.Q_720P;case"fullhd":case"full":return re.Q_1080P;case"quadhd":case"quad":return re.Q_1440P;case"ultrahd":case"ultra":return re.Q_2160P}};const xa=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var mt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!xa(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return xa(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Ee(){return he()}function to(s){return Ee()-s}function Oa(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,l=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return l&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Gf(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ui(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,l=!1,d=0,u,c,h=!1,f="arraybuffer",v=7e3,S=2e3,b=()=>{if(l)return;R(u);const O=to(u);let ee;if(O<S){ee=S-O,setTimeout(b,ee);return}S*=2,S>v&&(S=v),n&&n.abort(),n=new r,x()};const m=O=>(a=O,B),g=O=>(c=O,B),E=()=>(f="json",B),$=()=>{if(!l){if(--d>=0){b(),i&&i();return}l=!0,c&&c(),t&&t()}},w=O=>(h=O,B),x=()=>{u=Ee(),n=new r,n.open("get",s);let O=0,ee,ue=0;const me=()=>(R(u),Math.max(u,Math.max(ee||0,ue||0)));if(a&&n.addEventListener("progress",P=>{const H=Ee();a.updateChunk&&P.loaded>O&&(a.updateChunk(me(),P.loaded-O),O=P.loaded,ee=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(l)return;R(n);const P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&a){const H=n.response.byteLength-O;H&&a.updateChunk&&a.updateChunk(me(),H)}c&&c(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),h){const P=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Ee(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=f,n.send(),B},B={withBitrateReporting:m,withParallel:w,withJSONResponse:E,withRetryCount:O=>(d=O,B),withRetryInterval:(O,ee)=>(k(O)&&(S=O),k(ee)&&(v=ee),B),withTimeout:O=>(o=O,B),withFinally:g,send:x,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return B}const zf=100,jf=2e3,Wf=500;let Qf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Wf;if(t-e>jf){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const l=a.bytes*n/o;r+=l,a.start=t,a.bytes-=l}}}if(r>0&&i>0){const a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>zf&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class Jf{constructor(e,t,i,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=Ee(),r=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=l=>{e._complete=1,e._responseData=l,e._downloadTime=Ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ui(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Ee();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Pi=1e4,Ri=3,Kf=300,Xf=2e3,Zf=6e4,ep=10,tp=1,ip=500;class sp{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new Qf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Oa(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Oa(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||k(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Gf(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Jf(Ri,Pi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,l=null,d=null,u=!1;const c=()=>{const $=a&&(!u||u===this.rep);return $||t("Not running!"),$},h=($,w,x)=>{l&&l.abort(),l=Ui(this.urlResolver.resolve($,!1),w,x,()=>this._retryCallback()).withTimeout(Pi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ri).withFinally(()=>{l=null}).send()},f=($,w,x)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),w,x,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=$=>{const w=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${w}=>${$}`),i.playbackRate=$)},S=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const x=Ee()-1e4;let W=0;for(let U=0;U<this.bufferStates.length;U++){const Z=this.bufferStates[U];$=Math.min($,Z.buf),Z.ts<x&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${$} drop=${W} jitter=${this.sourceJitter}`);let F=$-tp;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?v(1.15):F>1?v(1.1):F>.3?v(1.05):v(1)}},m=$=>{let w;const x=()=>w&&w.start?w.start.length:0,W=P=>w.start[P]/1e3,F=P=>w.dur[P]/1e3,U=P=>w.fragIndex+P,Z=(P,H)=>({chunkIdx:U(P),startTS:W(P),dur:F(P),discontinuity:H}),B=()=>{let P=0;if(w&&w.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=H;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=w.dur.length-1;for(;ve>=0&&(fe-=w.dur[ve],!(fe<=0));--ve);P=Math.min(ve,w.dur.length-1-ne),P=Math.max(P,0)}return Z(P,!0)},O=P=>{const H=x();if(!(H<=0)){if(k(P)){for(let ne=0;ne<H;ne++)if(W(ne)>P)return Z(ne)}return B()}},ee=P=>{const H=x(),ne=P?P.chunkIdx+1:0,fe=ne-w.fragIndex;if(!(H<=0)){if(!P||fe<0||fe-H>ep)return t(`Resync: offset=${fe} bChunks=${H} chunk=`+JSON.stringify(P)),B();if(!(fe>=H))return Z(ne-w.fragIndex,!1)}},ue=(P,H,ne)=>{d&&d.abort(),d=Ui(this.urlResolver.resolve(P,!0,this.lowLatency),H,ne,()=>this._retryCallback()).withTimeout(Pi).withRetryCount(Ri).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(P,H)=>{ue($,ne=>{if(!c())return;w=ne;const fe=Boolean(w.lowLatency);fe!==this.lowLatency&&S(fe);let ve=0;for(let we=0;we<w.dur.length;++we)ve+=w.dur[we];ve>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,P(O(H))},()=>this._handleNetworkError())},nextChunk:ee}},g=()=>{a=!1,o&&o.abort(),l&&l.abort(),d&&d.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:$=>{const{videoElement:w,logger:x}=this.params;let W=m(e.jidxUrl),F,U,Z,B,O=0,ee,ue,me;const P=()=>{ee&&(clearTimeout(ee),ee=void 0);const J=Math.max(ip,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=O+J,$e=Ee(),Pe=Math.min(1e4,be-$e);O=$e;const vt=()=>{d||c()&&W.seek(()=>{c()&&(O=Ee(),H(),P())})};Pe>0?ee=window.setTimeout(()=>{this.paused?P():vt()},Pe):vt()},H=()=>{let J;for(;J=W.nextChunk(B);)B=J,Fe(J);const be=W.nextChunk(Z);if(be){if(Z&&be.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?P():(g(),this._initPlayerWith(e));return}we(be)}else P()},ne=(J,be)=>{if(!c()||!this.sourceBuffer)return;let $e,Pe,vt;const Ue=ut=>{window.setTimeout(()=>{c()&&ne(J,be)},ut)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const ut=Ee(),St=w.currentTime;!this.paused&&w.buffered.length>1&&ue===St&&ut-me>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),ue!==St&&(ue=St,me=ut);const Gt=this._getBufferSizeSec();if(Gt>30)x(`Buffered ${Gt} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(J),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:Gt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(kt){if(kt.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&($e=this.sourceBuffer.buffered.start(0),Pe=St,Pe-$e>4&&this.sourceBuffer.remove($e,Pe-3)),Ue(1e3);else throw kt}}},fe=()=>{U&&F&&(x([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Z)]),ne(U,function(){U=null,H()}))},ve=J=>e.fragUrlTemplate.replace("%%id%%",J.chunkIdx),we=J=>{c()&&f(ve(J),(be,$e)=>{if(c()){if($e/=1e3,U=be,Z=J,n=J.startTS,$e){const Pe=Math.min(10,J.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}fe()}},()=>this._handleNetworkError())},Fe=J=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(J),!1)))},qt=J=>{c()&&(e.cachedHeader=J,ne(J,()=>{F=!0,fe()}))};a=!0,W.seek(J=>{if(c()){if(O=Ee(),!J){P();return}B=J,!X($)||J.startTS>$?we(J):(Z=J,H())}},$),e.cachedHeader?qt(e.cachedHeader):h(e.headerUrl,qt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=Ee();if(this.chunkRateEstimator.addInterval(h,v,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:b}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,l=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(l&&c>o&&to(n)<3e4)return;i(c)}l=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Ee();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ui(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Pi).withRetryCount(Ri).withRetryInterval(Kf,Xf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;mt(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((l,d)=>{l.video&&r.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=d,o.push(l))}),o.sort(function(l,d){return l.video&&d.video?d.video.height-l.video.height:d.bitrate-l.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Zf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const rp=[z.PAUSED,z.PLAYING,z.READY],ap=[z.PAUSED,z.PLAYING,z.READY];class np{constructor(e){this.subscription=new ae,this.videoState=new de(z.STOPPED),this.representations$=new y([]),this.textTracksManager=new je,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new $r,this._dashCb=r=>{var a,n,o,l;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,u=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=pi(c.name))!==null&&n!==void 0?n:wt(c.video),v=c.bitrate/1e3,S={...c.video};if(!f)continue;const b={id:h,quality:f,bitrate:v,size:S};u.push({track:b,representation:c})}this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.MANIFEST_READY&&this.videoState.setState(z.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,u=(l=this.representations$.getValue().find(({representation:c})=>c===d))===null||l===void 0?void 0:l.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),k(u)&&this.params.output.currentVideoTrack$.next(u);break}case"bandwidth":{const{size:d,duration:u}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,u);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===p.STOPPED){a!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(!n){if(ap.includes(a)){const u=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;k(u)&&this.setVideoTrack(u);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((l==null?void 0:l.to)!==p.PAUSED&&d.state===q.Requested&&rp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(Mt(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(o===p.PAUSED)this.videoState.setState(z.PAUSED);else if(o===p.PLAYING){this.videoState.startTransitionTo(z.PLAYING);const u=l==null?void 0:l.from;u&&u===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(z.PAUSED)})}return;case z.PLAYING:o===p.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:o===p.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(z.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return M(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(this.videoState.stateChangeStarted$.pipe(_(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=nt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=ot(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===q.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(qe({zeroTime:this.zeroTime$.pipe(te(k)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(_t(this.video,this.params.desiredState.isLooped,t)).add(at(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&of(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case z.MANIFEST_READY:case z.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case z.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case z.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return M(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),dt(this.video)}createLiveDashPlayer(){const e=new sp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),l=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),u=!d&&k(l)?l:(a=fi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===u))===null||n===void 0?void 0:n.representation;R(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(u),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;R(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(Mt(this.params.source.url,i))}}var io=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?oi.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Tt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const op=s=>{const e=document.createElement("a");return e.href=s,e.origin},dp=s=>{const e=document.createElement("a");return e.href=s,e.host};class so{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,l,d;if(R(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const u=hi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(u))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((l=this._progressCb)===null||l===void 0||l.call(this,this._xhr.response))}catch(u){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(u)}`,u),u}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(dp(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Wi{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let l=0;const d=Date.now();let u=0,c=0,h=0;const f=S=>{r(Wi._str2ua(S.substr(l))),l=S.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Ut(v)),this._lastXhr=new so(v,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const b=Date.now()-d;this._params.onBandwidthChange({size:S.length,duration:b,speed:8*S.length/(b/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),a==null||a()},S=>{if(S.length-l>o&&f(S),c===0){c=Date.now();return}h=S.length-u;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,u=S.length,c=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},n,(S,b,m)=>this._params.onError(S,b,m))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Wi._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class up{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Ut(i)),new so(i,t,r=>{this.attachManifest(r,t,op(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,u)=>{const c=d.attributes.getNamedItem(u);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],l=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var u,c,h,f,v,S,b,m,g,E,$,w,x,W,F,U,Z,B,O;const ee=d.getElementsByTagName("SegmentBase")[0],ue=ee&&n(ee,"indexRange").split("-"),me=ee&&ee.getElementsByTagName("Initialization")[0],P=me&&n(me,"range").split("-");if(!P||!ue){const Fe=d.parentElement;if((Fe==null?void 0:Fe.getAttribute("contentType"))==="text"){const qt=(u=d.getAttribute("id"))!==null&&u!==void 0?u:void 0,J=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),be=(S=Fe.getAttribute("lang"))!==null&&S!==void 0?S:void 0;J&&l.push({id:qt,url:J,language:be})}return}const H=.1,ne=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const we=(g=(m=d.attributes.getNamedItem("frameRate"))===null||m===void 0?void 0:m.value)!==null&&g!==void 0?g:void 0;ve=we?Ar(we):void 0,o.push({width:Number((E=d.attributes.getNamedItem("width"))===null||E===void 0?void 0:E.value),height:Number(($=d.attributes.getNamedItem("height"))===null||$===void 0?void 0:$.value),bandwidth:ne,baseURL:fe,failoverHosts:t,indexFrom:Number(ue[0]),indexTo:Number(ue[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(x=(w=d.attributes.getNamedItem("codecs"))===null||w===void 0?void 0:w.value)!==null&&x!==void 0?x:void 0,mimeType:(F=(W=d.attributes.getNamedItem("mimeType"))===null||W===void 0?void 0:W.value)!==null&&F!==void 0?F:void 0,fps:ve,bufferSize:H*ne/8,bufferLength:H,name:(Z=(U=d.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&Z!==void 0?Z:void 0,id:(O=(B=d.attributes.getNamedItem("id"))===null||B===void 0?void 0:B.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}l.forEach(({id:d,language:u,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),u&&h.setAttribute("srclang",u),this._video.appendChild(h)}),this._representations.sort((d,u)=>u.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let l=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const u=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<u;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=l+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:l/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,l=v}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const u=this._appendVector[String(d.fromTime)];u!==r&&(r=u,this._params.onRepresentationPlay(u));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},l=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Wi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",l),i.removeEventListener("webkitsourceopen",l)};i.addEventListener("sourceopen",l,!1),i.addEventListener("webkitsourceopen",l,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),l=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=l?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,l)=>this._stream.remove(o,l)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,l)=>this._stream.remove(o,l)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||X(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var j;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const lp=[j.PAUSED,j.PLAYING];class cp{constructor(e){this.videoState=new de(j.STOPPED),this.subscription=new ae,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new je,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var i,r,a;const n=[];for(const o of t){const l=(r=(i=o.name)!==null&&i!==void 0?i:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&pi(o.name))!==null&&a!==void 0?a:wt(o),u=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:l,quality:d,bitrate:u,size:c,fps:h};n.push({track:f,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(j.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return R(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(j.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===q.Requested&&lp.includes(t)&&this.seek(n.position,n.forcePrecise),t){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_LOADED),this.prepare();return;case j.MANIFEST_LOADED:this.videoState.startTransitionTo(j.INITIAL_REPRESENTATION_SELECTED);return;case j.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(j.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case j.METADATA_LOADED:this.videoState.startTransitionTo(j.READY),this.dash.updateRefsForCurrentTime();return;case j.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed());return;case j.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(j.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case j.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return M(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(this.videoState.stateChangeStarted$.pipe(_(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=nt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new $f(this.video),this.dash=new up({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:D.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:D.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();return l?l.to:o},a=ot(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{X(this.params.desiredState.seekState.getState().state!==q.Applying)&&(this.videoState.getState()===j.PLAYING||this.videoState.getState()===j.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(at(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(ji(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.READY&&this.videoState.setState(j.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(j.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(_(({id:o,message:l,thrown:d})=>({id:`DashLite_${o}`,category:D.WTF,message:l,thrown:d}))).subscribe(this.params.output.error$)).add(V(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,N(this.video,"progress")).pipe(_(()=>{var o,l,d;const u=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),b=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let m;if(!b&&k(f))m=f;else{const g=Tt(this.video.buffered,this.video.currentTime*1e3),E=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(g/E,1);m=(l=fi(c.map(({track:w})=>w),{container:S,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:$,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:w})=>w===u))===null||o===void 0?void 0:o.track}))===null||l===void 0?void 0:l.id}return k(m)?(d=c.find(({track:g})=>g.id===m))===null||d===void 0?void 0:d.representation:void 0}),pe()).subscribe(this.currentRepresentation$,i)).add(qe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(te(o=>o.to===j.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(te(k))}).pipe(ge()).subscribe(()=>this.videoState.setState(j.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(te(k),pe((o,l)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=l.height:o===l)).subscribe(o=>{const l=Tt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(l/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ae(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:l,reused:d}=io(o);this.params.output.httpConnectionType$.next(l),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),Bt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(te(k)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),dt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return M(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var De;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(De||(De={}));var Qi;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Qi||(Qi={}));var Le;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Le||(Le={}));var K;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(K||(K={}));var Vt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Vt||(Vt={}));var or=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const hp=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},fp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Na=fp?hp:window.requestIdleCallback;var xs,Os;let ro=!1;try{ro=Xn()&&parseInt((Os=(xs=navigator.userAgent.match(/Version\/(\d+)/))===null||xs===void 0?void 0:xs[1])!==null&&Os!==void 0?Os:"",10)<16}catch(s){console.error(s)}class pp{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:D.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;ro&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:M(t)}}}var Ba=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const ao=new TextDecoder("ascii"),no=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=ao.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,s.byteLength)-e,n=new DataView(s.buffer,s.byteOffset+e,a);return{id:r,size:t,contents:n}},mp=s=>ao.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",vp=(s,e,t)=>{const i=no(s),r=[];let a=0;const n=()=>{const S=i.contents.getUint32(a);return a+=4,S};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),u=n(),c=n(),h=n()&4294967295;let f=u/d*1e3,v=(t?t.to+1:s.byteOffset+s.byteLength)+c;for(let S=0;S<h;S++){const b=n(),m=b>>>31,g=b<<1>>>1,E=n();if(n(),m!==0)throw new Error("Unsupported multilevel sidx");const $=E/d*1e3;r.push({status:K.NONE,time:{from:f,to:f+$},byte:{from:v,to:v+g-1}}),f+=$,v+=g}return r},Sp=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const a=no(r);if(i||(i=a.id==="mdat"),e+a.size<=s.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},gp={validateData:mp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:vp,parseFeedableSegmentChunk:Sp};var A;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(A||(A={}));var L;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(L||(L={}));const Ma={[A.EBML]:{type:L.Master},[A.EBMLVersion]:{type:L.UnsignedInteger},[A.EBMLReadVersion]:{type:L.UnsignedInteger},[A.EBMLMaxIDLength]:{type:L.UnsignedInteger},[A.EBMLMaxSizeLength]:{type:L.UnsignedInteger},[A.DocType]:{type:L.String},[A.DocTypeVersion]:{type:L.UnsignedInteger},[A.DocTypeReadVersion]:{type:L.UnsignedInteger},[A.Void]:{type:L.Binary},[A.Segment]:{type:L.Master},[A.SeekHead]:{type:L.Master},[A.Seek]:{type:L.Master},[A.SeekID]:{type:L.Binary},[A.SeekPosition]:{type:L.UnsignedInteger},[A.Info]:{type:L.Master},[A.TimestampScale]:{type:L.UnsignedInteger},[A.Duration]:{type:L.Float},[A.Tracks]:{type:L.Master},[A.Chapters]:{type:L.Master},[A.Cluster]:{type:L.Master},[A.Timestamp]:{type:L.UnsignedInteger},[A.SilentTracks]:{type:L.Master},[A.SilentTrackNumber]:{type:L.UnsignedInteger},[A.Position]:{type:L.UnsignedInteger},[A.PrevSize]:{type:L.UnsignedInteger},[A.SimpleBlock]:{type:L.Binary},[A.BlockGroup]:{type:L.Master},[A.EncryptedBlock]:{type:L.Binary},[A.Attachments]:{type:L.Master},[A.Tags]:{type:L.Master},[A.Cues]:{type:L.Master},[A.CuePoint]:{type:L.Master},[A.CueTime]:{type:L.UnsignedInteger},[A.CueTrackPositions]:{type:L.Master},[A.CueTrack]:{type:L.UnsignedInteger},[A.CueClusterPosition]:{type:L.UnsignedInteger},[A.CueRelativePosition]:{type:L.UnsignedInteger},[A.CueDuration]:{type:L.UnsignedInteger},[A.CueBlockNumber]:{type:L.UnsignedInteger},[A.CueCodecState]:{type:L.UnsignedInteger},[A.CueReference]:{type:L.Master},[A.CueRefTime]:{type:L.UnsignedInteger}},oo=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ji(s,t),r=i in Ma,a=r?Ma[i].type:L.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const l=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,u=Ji(l),c=d*2**((o-1)*8)+u,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ji=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Xe=(s,e)=>{switch(e){case L.SignedInteger:return s.getInt8(0);case L.UnsignedInteger:return Ji(s);case L.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case L.String:return new TextDecoder("ascii").decode(s);case L.UTF8:return new TextDecoder("utf-8").decode(s);case L.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case L.Master:return s;case L.Binary:return s;default:M(e)}},mi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=oo(i);if(!e(r))return;r.type===L.Master&&mi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},bp=s=>{if(s.getUint32(0)!==A.EBML)return!1;let e,t,i;const r=oo(s);return mi(r.value,({tag:a,type:n,value:o})=>(a===A.EBMLReadVersion?e=Xe(o,n):a===A.DocType?t=Xe(o,n):a===A.DocTypeReadVersion&&(i=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},uo=[A.Info,A.SeekHead,A.Tracks,A.Chapters,A.Cluster,A.Cues,A.Attachments,A.Tags],yp=[A.Timestamp,A.SilentTracks,A.SilentTrackNumber,A.Position,A.PrevSize,A.SimpleBlock,A.BlockGroup,A.EncryptedBlock],Tp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,l,d;return mi(s,({tag:u,type:c,value:h,valueSize:f})=>{if(u===A.SeekID){const v=Xe(h,c);d=Ji(v)}else u!==A.SeekPosition&&(d=void 0);return u===A.Segment?(e=h.byteOffset,t=h.byteOffset+f):u===A.Info?a=!0:u===A.SeekHead?n=!0:u===A.TimestampScale?i=Xe(h,c):u===A.Duration?r=Xe(h,c):u===A.SeekPosition&&d===A.Cues?l=Xe(h,c):a&&n&&uo.includes(u)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:l}},Ep=s=>{if(X(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$p=(s,e)=>{let t=!1,i=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return mi(s,({tag:o,type:l,value:d})=>{switch(o){case A.Cues:t=!0;break;case A.CuePoint:n&&r(n)&&a.push(n),n={};break;case A.CueTime:n&&(n.time=Xe(d,l));break;case A.CueTrackPositions:break;case A.CueClusterPosition:n&&(n.position=Xe(d,l));break;default:t&&uo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,l)=>{const{time:d,position:u}=o,c=a[l+1];return{status:K.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Ap=s=>{let e=0,t=!1;try{mi(s,i=>i.tag===A.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):yp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[A.SimpleBlock,A.BlockGroup,A.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wp={validateData:bp,parseInit:Tp,getIndexRange:Ep,parseSegments:$p,parseFeedableSegmentChunk:Ap};class Fa{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:l=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new C,this.gaps=[],this.subscription=new ae,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Et,this.destroyAbortController=new Et,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Ne(this.destroyAbortController.signal,async function*(d){const u=this.representations.get(d);R(u,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${u.mime}; codecs="${u.codecs}"`),this.sourceBufferTaskQueue=new pp(this.sourceBuffer),this.subscription.add(N(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(N(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Ba(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(u,"high",!0);const c=this.initData.get(u.id),h=this.segments.get(u.id);if(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let f=0;for(const v of h)v.time.from-f>0&&this.gaps.push({representation:u.id,from:f,to:v.time.from}),f=v.time.to;k(u.duration)&&u.duration-f>0&&this.gaps.push({representation:u.id,from:f,to:u.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=Ne(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const u=this.representations.get(d);R(u,`No such representation ${d}`);let c=this.initData.get(d);if(X(c)?yield this.loadInit(u,"high",!1):c instanceof Promise&&(yield c),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal);const h=this.getCurrentPosition();k(h)&&this.maintain(h)}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case Vt.MP4:this.containerParser=gp;break;case Vt.WEBM:this.containerParser=wp;break;default:M(i)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(X(e)||X(this.downloadingRepresentationId)||X(this.playingRepresentationId)||X(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(R(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=Tt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&u>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Ba(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Tt(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const u=Je(o,0);u&&u.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===K.FED&&!o.length&&Tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const l=Je(i,-1);l&&l.status===K.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===l))}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(l=>l.time.from<=e&&l.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const S=h<=i&&f>=i,b=h>i||S||v===0&&i===0,m=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=i+m||f<=i+m;return(c===K.NONE||c===K.PARTIALLY_EJECTED&&b&&g&&this.sourceBuffer&&!or(this.sourceBuffer.buffered,i))&&b&&g});if(r===-1)return[];if(t!==Le.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=u);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===K.NONE||h.status===K.PARTIALLY_EJECTED)l.push(h);else break}return l}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Le.BYTE_RANGE:{r=t.segmentReference.url,a={from:Je(e,0).byte.from,to:Je(e,-1).byte.to};break}case Le.TEMPLATE:{const d=Je(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:M(o)}for(const d of n)d.status=K.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:l}=this.downloadAbortController;if(this.failedDownloads&&(await Ne(l,async function*(){const d=Nr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,d))}.bind(this))(),l.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,u)=>{if(!l.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,u,l)}catch(c){this.error$.next({id:"SegmentFeeding",category:D.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:l,priority:i}).then(()=>this.failedDownloads=0,d=>{for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(i=Tt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:D.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),c.segment.status=K.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===K.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=K.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Le.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=f?h.byte.from-i:0,m=f?h.byte.to-i:e.byteLength,g=b<r,E=m<=r;if(h.status===K.DOWNLOADING&&g&&E){h.status=K.DOWNLOADED,this.activeSegments.delete(c);const $=new DataView(e.buffer,e.byteOffset+b,v);this.sourceBufferTaskQueue.append($,a).then(w=>w&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(c.loadedBytes=Math.min(v,r-b),c.loadedBytes>c.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),w=c.loadedBytes===v?$:this.containerParser.parseFeedableSegmentChunk($);w!=null&&w.byteLength&&(h.status=K.PARTIALLY_FED,c.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(x=>{if(a.aborted)n();else if(x)c.fedBytes+=w.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===K.PARTIALLY_FED||e.status===K.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=K.NONE),e.status=K.PARTIALLY_EJECTED):e.status=K.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Na(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ne(this.destroyAbortController.signal,async function*(){const o=Nr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:l,segments:d}=o,u=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:D.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||X(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const l=d=>{var u;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(u=d.size)!==null&&u!==void 0?u:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const u of d){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;u.status===K.FED&&l(u)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const u of d){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;u.status===K.FED&&l(u)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===K.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(c)){a=u,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const c of u)c.time.from>e+d&&c.status===K.FED&&l(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>=1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Na(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(X(this.sourceBuffer)||X(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==K.FED&&a!==K.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),l=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);l||(d.length===1?r.status=K.PARTIALLY_EJECTED:r.status=K.NONE)}}}var Ot;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ot||(Ot={}));class _p{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Et,this.subscription=new ae,this.fetchManifest=Ne(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Ut(a));const n=yield Ft(a,{signal:this.abortAllController.signal}).catch(si);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Ne(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ot.HEADER:Ot.PARAM,range:n,onProgress:o,priority:l="auto",signal:d,measureThroughput:u=!0}={}){var c,h,f,v;let S=r;const b=new Headers;if(n)switch(a){case Ot.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Ot.PARAM:{const P=new URL(S,location.href);P.searchParams.append("bytes",`${n.from}-${n.to}`),S=P.toString();break}default:M(a)}this.requestQuic&&(S=Ut(S));let m=this.abortAllController.signal;if(d){const P=new Et;if(this.subscription.add(V(N(this.abortAllController.signal,"abort"),N(d,"abort")).subscribe(()=>{try{P.abort()}catch(H){si(H)}})),this.abortAllController.signal.aborted||d.aborted)try{P.abort()}catch(H){si(H)}m=P.signal}const g=he(),E=yield Ft(S,{priority:l,headers:b,signal:m}).catch(si),$=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-g),!E)return null;if(!E.ok||!E.body)return Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));this.onHeadersReceived(E.headers);const w=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!w){const P=yield E.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(P.byteLength,he()-$),o==null||o(new DataView(P),P.byteLength),P}if(!o&&!u)return E.arrayBuffer();const[x,W]=E.body.tee(),F=x.getReader();u&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(W));let U=0;const Z=new ArrayBuffer(w),B=new Uint8Array(Z),O=new DataView(Z);let ee=!1;const ue=P=>{ee=!0,si(P)},me=Ne(m,async function*({done:P,value:H}){U===0&&this.lastRequestFirstBytes$.next(he()-g),!m.aborted&&(P?o==null||o(O,U):H&&(B.set(H,U),U+=H.byteLength,o==null||o(O,U),yield F==null?void 0:F.read().then(me,ue)))}.bind(this));return yield F==null?void 0:F.read().then(me,ue),ee?null:Z}.bind(this)),this.fetchByteRangeRepresentation=Ne(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Le.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(v,d))),u=Math.min(u,0);const S=yield this.fetch(r.url,{range:{from:u,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,l-u,d-u+1);if(!a.validateData(b))throw new Error("Invalid media file");const m=a.parseInit(b),g=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(m);if(!g)throw new ReferenceError("No way to load representation index");let E;if(h)E=new DataView(S,g.from-u,g.to-g.from+1);else{const w=yield this.fetch(r.url,{range:g,priority:n,measureThroughput:!1});if(!w)return null;E=new DataView(w)}const $=a.parseSegments(E,m,g);return{dataView:new DataView(S),segments:$}}.bind(this)),this.fetchTemplateRepresentation=Ne(this.abortAllController.signal,async function*(r,a){if(r.type!==Le.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{segments:r.segments.map(d=>({...d,status:K.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=io(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case Le.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Le.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:M(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const si=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var kp=$t,Pp=Zi,Rp=Me,Ip=Rp("match"),Dp=function(s){var e;return kp(s)&&((e=s[Ip])!==void 0?!!e:Pp(s)=="RegExp")},Lp=as,Cp=String,xp=function(s){if(Lp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Cp(s)},Op=At,Np=function(){var s=Op(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Bp=st,Mp=rt,Fp=hr,Up=Np,Ua=RegExp.prototype,Vp=function(s){var e=s.flags;return e===void 0&&!("flags"in Ua)&&!Mp(s,"flags")&&Fp(Ua,s)?Bp(Up,s):e},_r=it,Hp=is,Yp=Math.floor,Ns=_r("".charAt),qp=_r("".replace),Bs=_r("".slice),Gp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,jp=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,l=zp;return r!==void 0&&(r=Hp(r),l=Gp),qp(a,l,function(d,u){var c;switch(Ns(u,0)){case"$":return"$";case"&":return s;case"`":return Bs(e,0,t);case"'":return Bs(e,n);case"<":c=r[Bs(u,1,-1)];break;default:var h=+u;if(h===0)return d;if(h>o){var f=Yp(h/10);return f===0?d:f<=o?i[f-1]===void 0?Ns(u,1):i[f-1]+Ns(u,1):d}c=i[h-1]}return c===void 0?"":c})},Wp=rs,Qp=st,kr=it,Va=ur,Jp=xe,Kp=es,Xp=Dp,Lt=xp,Zp=ts,em=Vp,tm=jp,im=Me,sm=im("replace"),rm=TypeError,lo=kr("".indexOf),am=kr("".replace),Ha=kr("".slice),nm=Math.max,Ya=function(s,e,t){return t>s.length?-1:e===""?t:lo(s,e,t)};Wp({target:"String",proto:!0},{replaceAll:function(e,t){var i=Va(this),r,a,n,o,l,d,u,c,h,f=0,v=0,S="";if(!Kp(e)){if(r=Xp(e),r&&(a=Lt(Va(em(e))),!~lo(a,"g")))throw rm("`.replaceAll` does not allow non-global regexes");if(n=Zp(e,sm),n)return Qp(n,e,i,t);if(r)return am(Lt(i),e,t)}for(o=Lt(i),l=Lt(e),d=Jp(t),d||(t=Lt(t)),u=l.length,c=nm(1,u),f=Ya(o,l,0);f!==-1;)h=d?Lt(t(l,f,o)):tm(l,o,f,[],void 0,t),S+=Ha(o,v,f)+h,v=f+u,f=Ya(o,l,f+c);return v<o.length&&(S+=Ha(o,v)),S}});var om=eo,dm=om("String","replaceAll"),um=dm,lm=um,cm=lm,hm=cm,qa=hm;const Ga=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ms=(s,e)=>{let t=s;t=qa(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=qa(t,n,(o,l)=>X(a)?o:X(l)?a:a.padStart(parseInt(l,10),"0"))}return t},fm=(s,e)=>{var t,i,r,a,n,o,l,d,u,c,h,f,v,S,b,m,g,E,$,w,x,W,F,U,Z,B,O,ee,ue,me,P,H,ne,fe,ve,we,Fe;const J=new DOMParser().parseFromString(s,"application/xml"),be={video:[],audio:[],text:[]},$e=J.children[0],Pe=$e.getElementsByTagName("Period")[0],vt=Pe.children;let Ue;const ut=$e.getAttribute("mediaPresentationDuration"),St=Pe.getAttribute("duration");if(ut)Ue=Ga(ut);else if(St){const Ve=Ga(St);k(Ve)&&(Ue=Ve)}let Gt=0;const kt=(i=(t=$e.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],mo=kt.includes(Qi.WEBM_AS_IN_FFMPEG)||kt.includes(Qi.WEBM_AS_IN_SPEC)?Vt.WEBM:Vt.MP4;for(const Ve of vt){const vi=Ve.getAttribute("mimeType"),vo=Ve.getAttribute("codecs"),Pr=(r=Ve.getAttribute("contentType"))!==null&&r!==void 0?r:vi==null?void 0:vi.split("/")[0],So=(n=(a=Ve.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],go=Ve.querySelectorAll("Representation"),bo=Ve.querySelector("SegmentTemplate");if(Pr!=="text")for(const ye of go){const zt=(o=ye.getAttribute("mimeType"))!==null&&o!==void 0?o:vi,Rr=(d=(l=ye.getAttribute("codecs"))!==null&&l!==void 0?l:vo)!==null&&d!==void 0?d:"",Si=(c=(u=ye.getAttribute("contentType"))!==null&&u!==void 0?u:zt==null?void 0:zt.split("/")[0])!==null&&c!==void 0?c:Pr,yo=(f=(h=Ve.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],To=parseInt((v=ye.getAttribute("width"))!==null&&v!==void 0?v:"",10),Ir=parseInt((S=ye.getAttribute("height"))!==null&&S!==void 0?S:"",10),Dr=parseInt((b=ye.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Lr=(m=ye.getAttribute("frameRate"))!==null&&m!==void 0?m:"",Eo=(g=ye.getAttribute("quality"))!==null&&g!==void 0?g:void 0,$o=Lr?Ar(Lr):void 0,Ao=(E=ye.getAttribute("id"))!==null&&E!==void 0?E:(Gt++).toString(10),wo=Si==="video"?`${Ir}p`:Si==="audio"?`${Dr}Kbps`:Rr,_o=`${Ao}@${wo}`,ko=(x=(w=($=ye.querySelector("BaseURL"))===null||$===void 0?void 0:$.textContent)===null||w===void 0?void 0:w.trim())!==null&&x!==void 0?x:"",Cr=new URL(ko,e).toString(),Po=[...kt,...So,...yo];let ds;const Ro=ye.querySelector("SegmentBase"),gt=(W=ye.querySelector("SegmentTemplate"))!==null&&W!==void 0?W:bo;if(Ro){const jt=(U=(F=ye.querySelector("SegmentBase Initialization"))===null||F===void 0?void 0:F.getAttribute("range"))!==null&&U!==void 0?U:"",[Wt,ls]=jt.split("-").map(bt=>parseInt(bt,10)),Qt={from:Wt,to:ls},Jt=(Z=ye.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[cs,gi]=Jt?Jt.split("-").map(bt=>parseInt(bt,10)):[],Kt=Jt?{from:cs,to:gi}:void 0;ds={type:Le.BYTE_RANGE,url:Cr,initRange:Qt,indexRange:Kt}}else if(gt){const jt={representationId:(B=ye.getAttribute("id"))!==null&&B!==void 0?B:void 0,bandwidth:(O=ye.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},Wt=parseInt((ee=gt.getAttribute("timescale"))!==null&&ee!==void 0?ee:"",10),ls=(ue=gt.getAttribute("initialization"))!==null&&ue!==void 0?ue:"",Qt=gt.getAttribute("media"),Jt=(P=parseInt((me=gt.getAttribute("startNumber"))!==null&&me!==void 0?me:"",10))!==null&&P!==void 0?P:1,cs=Ms(ls,jt);if(!Qt)throw new ReferenceError("No media attribute in SegmentTemplate");const gi=(H=gt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],Kt=[];if(gi.length){let bt=Jt,yt=0;for(const Xt of gi){const Pt=parseInt((ne=Xt.getAttribute("d"))!==null&&ne!==void 0?ne:"",10)*1e3,Zt=parseInt((fe=Xt.getAttribute("r"))!==null&&fe!==void 0?fe:"",10)||0,ei=(we=parseInt((ve=Xt.getAttribute("t"))!==null&&ve!==void 0?ve:"",10))!==null&&we!==void 0?we:void 0;for(let xr=0;xr<Zt+1;xr++){const Io=Ms(Qt,{...jt,segmentNumber:bt.toString(10),segmentTime:ei.toString(10)}),Do=ei?ei/Wt:yt;yt+=Pt/Wt;const Lo=yt;bt++,Kt.push({time:{from:Do,to:Lo},url:Io})}}}else if(k(Ue)){const yt=parseInt((Fe=gt.getAttribute("duration"))!==null&&Fe!==void 0?Fe:"",10)/Wt*1e3,Xt=Math.ceil(Ue/yt);let Pt=0;for(let Zt=1;Zt<Xt;Zt++){const ei=Ms(Qt,{...jt,segmentNumber:Zt.toString(10),segmentTime:Pt.toString(10)});Kt.push({time:{from:Pt,to:Pt+yt},url:ei}),Pt+=yt}}ds={type:Le.TEMPLATE,baseUrl:Cr,initUrl:cs,segments:Kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Si||!zt)continue;const us={video:De.VIDEO,audio:De.AUDIO,text:De.TEXT}[Si];us&&be[us].push({id:_o,kind:us,segmentReference:ds,profiles:Po,duration:Ue,bitrate:Dr,mime:zt,codecs:Rr,width:To,height:Ir,fps:$o,quality:Eo})}}return{duration:Ue,container:mo,representations:be}},pm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ie;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ie||(Ie={}));let mm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ae,this.state$=new de(Ie.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new C,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new Et,this.initManifest=Ne(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(Ie.MANIFEST_READY);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=fm(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({mime:o,codecs:l})=>{var d,u,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(u=window.MediaSource)===null||u===void 0?void 0:u.isTypeSupported)===null||c===void 0?void 0:c.call(u,`${o}; codecs="${l}"`)))};this.manifest={...a,representations:hi(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(Ie.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=Ne(this.destroyController.signal,async function*(t,i){R(this.manifest),R(this.element),this.state$.startTransitionTo(Ie.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Fa(De.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(i)&&(this.audioBufferManager=new Fa(De.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(V(this.forceEnded$,qe({allBuffersFull:a,someBufferEnded:n}).pipe(te(({allBuffersFull:o,someBufferEnded:l})=>o&&l))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.subscription.add(V(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var l;return(l=this.source)===null||l===void 0?void 0:l.addEventListener("sourceopen",o)})),k(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&k(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ie.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=xo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new _p({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(Ie.RUNNING),this.subscription.add(V(...pm.map(e=>N(this.element,e)),N(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(N(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(N(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&or(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[De.VIDEO]:this.videoBufferManager,[De.AUDIO]:this.audioBufferManager,[De.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;R(this.element),R(this.videoBufferManager);let l;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?l=e:l=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),or(this.element.buffered,l)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(l),(o=this.audioBufferManager)===null||o===void 0||o.maintain(l),this.element.currentTime=l/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ie.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const vm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?pi(a):void 0)!==null&&n!==void 0?n:wt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Sm=({id:s,bitrate:e})=>({id:s,bitrate:e}),gm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Je(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Je(s,-1)};class bm{constructor(e){this.subscription=new ae,this.videoState=new de(le.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new je,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Hf,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===q.Requested&&(r==null?void 0:r.to)!==p.PAUSED&&t!==le.STOPPED&&i!==p.STOPPED&&this.seek(a.position,a.forcePrecise),i===p.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(t){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:i===p.PAUSED?(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case le.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return M(t)}}},this.params=e,this.video=nt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new mm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=ot(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:D.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,u)=>this.subscription.add(d.subscribe(u,r));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.isAudioAvailable$,e.isAudioAvailable$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(te(k),ge()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(_t(this.video,t.isLooped,r)),this.subscription.add(at(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ji(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),I(t.playbackState,p.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var u;if(d===Ie.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((S,b)=>b.bitrate-S.bitrate),f=Array.from(c.video).sort((S,b)=>b.bitrate-S.bitrate);if(!this.params.tuning.isAudioDisabled)for(const S of h){const b=Sm(S);b&&this.audioTracks.push({track:b,representation:S})}for(const S of f){const b=vm(S);if(b){this.videoTracks.push({track:b,representation:S});const m=!this.params.tuning.isAudioDisabled&&gm(h,f,S);m&&this.audioRepresentations.set(S.id,m)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();R(v),this.player.initRepresentations(v.id,(u=this.audioRepresentations.get(v.id))===null||u===void 0?void 0:u.id)}else d===Ie.REPRESENTATIOS_READY&&(this.videoState.setState(le.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(V(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,N(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),u=this.player.state$.getTransition();if(d!==Ie.RUNNING||u||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(De.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(De.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),_(d=>{var u;return d&&((u=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),pe());this.subscription.add(V(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(V(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const l=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),l=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:m}})=>m===l))===null||e===void 0?void 0:e.track,u=this.params.output.currentVideoTrack$.getValue(),c=Tt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,u&&(a=(r=this.audioRepresentations.get(u.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),S=fi(this.videoTracks.map(({track:m})=>m),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:u,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=o?S!=null?S:d:d!=null?d:S;return b&&((n=this.videoTracks.find(({track:m})=>m===b))===null||n===void 0?void 0:n.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),dt(this.video)}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const ym=5e3,We={};var Q;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const Ii=(s,e)=>new Ki(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class Tm{constructor(e){this.subscription=new ae,this.videoState=new de(Q.INITIALIZING),this.textTracksManager=new je,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==Q.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===q.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case Q.STOPPED:break;case Q.READY:case Q.PLAYING:case Q.PAUSED:this.stop();break;default:M(t)}break;case p.READY:switch(t){case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PLAYING:case Q.PAUSED:break;default:M(t)}break;case p.PLAYING:switch(t){case Q.PLAYING:break;case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PAUSED:this.playIfAllowed();break;default:M(t)}break;case p.PAUSED:switch(t){case Q.PAUSED:break;case Q.STOPPED:this.prepare();break;case Q.READY:this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case Q.PLAYING:this.pause();break;default:M(t)}break;default:M(i)}},this.video=nt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),dt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),ym);import("hls.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){R(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ot(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.isAudioAvailable$,t.isAudioAvailable$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(_t(this.video,e.isLooped,i)),this.subscription.add(at(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ii(this.hls,We.Events.ERROR).subscribe(d=>{var u;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:D.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(u=d.err)===null||u===void 0?void 0:u.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i)),a(Ii(this.hls,We.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((u,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:S,height:b}=c,m=(f=pi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:wt({width:S,height:b});if(!m)return u;const g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,E={id:v.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:g};return this.trackLevels.set(v,{track:E,level:c}),u.push(E),u},[]))),t.availableVideoTracks$),a(Ii(this.hls,We.Events.LEVEL_LOADING).pipe(_(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(Ge(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var u;return(u=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||u===void 0?void 0:u.track},o=Ii(this.hls,We.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(te(k)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ge(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var u;if(X(d))return;const c=(u=this.trackLevels.get(d))===null||u===void 0?void 0:u.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(_(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const l=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Q.PLAYING),await mt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:t}))||(this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Q.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const za="X-Playback-Duration";var ja=async s=>{const e=await Ft(s,{method:"HEAD"});return e.headers.has(za)?parseInt(e.headers.get(za),10):void 0};const Em=s=>{let e=null;if(s.QUALITY&&(e=pi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=wt({width:t,height:i})}return e!=null?e:null},co=async(s,e=s)=>{var t;const a=(await(await Ft(s)).text()).split(`
8
+ `),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const u=hi(d[1].split(",").map(m=>m.split("="))),c=(t=u.QUALITY)!==null&&t!==void 0?t:`stream-${u.BANDWIDTH}`,h=Em(u);let f;u.BANDWIDTH&&(f=parseInt(u.BANDWIDTH,10)/1e3||void 0),!f&&u["AVERAGE-BANDWIDTH"]&&(f=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let S;if(u.RESOLUTION){const[m,g]=u.RESOLUTION.split("x").map(E=>parseInt(E,10));m&&g&&(S={width:m,height:g})}const b=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:b,bandwidth:f,size:S,fps:v})}return n};var ie;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ie||(ie={}));class $m{constructor(e){var t;this.subscription=new ae,this.videoState=new de(ie.STOPPED),this.textTracksManager=new je,this.manifests$=new y([]),this.liveOffset=new $r,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),u.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&u.state===q.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return M(r)}},this.params=e,this.video=nt(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:re.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),co(Mt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",l=this.manifests$.getValue();if(!l)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),l.find(u=>u.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(at(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),l&&l.from===ie.CHANGING_MANIFEST&&this.videoState.setState(l.to),o&&o.state===q.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,l,d;const u=(d=(l=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||l===void 0?void 0:l.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(qe({startTime:this.manifestStartTime$.pipe(te(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),i)),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(Ce(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),dt(this.video)}prepare(){const e=this.selectManifest();if(X(e))return;const t=Mt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),ja(t).then(i=>{var r;if(!X(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(X(a)||!isFinite(a))try{Ft(t).then(n=>n.text()).then(n=>{var o;const l=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(l){const d=new URL(l,t).toString();ja(d).then(u=>{X(u)||this.maxSeekBackTime$.next(u)})}})}catch(n){}}})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class Am{constructor(e){this.subscription=new ae,this.videoState=new de(oe.STOPPED),this.textTracksManager=new je,this.manifests$=new y([]),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===p.STOPPED){i!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n||o){const u=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:c}=this.video;this.prepare(),d.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===q.Requested&&this.seek(d.position),i){case oe.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return M(i)}},this.params=e,this.video=nt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:re.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),co(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",l=this.manifests$.getValue();if(!l)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),l.find(u=>u.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(at(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),l&&l.from===oe.CHANGING_MANIFEST&&this.videoState.setState(l.to),o.state===q.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),dt(this.video)}prepare(){const e=this.selectManifest();X(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class wm{constructor(e){this.subscription=new ae,this.videoState=new de(ce.STOPPED),this.trackUrls={},this.textTracksManager=new je,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(n){const{currentTime:l}=this.video;this.prepare(),o.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==p.PAUSED&&o.state===q.Requested&&this.seek(o.position),t){case ce.READY:i===p.READY?I(this.params.desiredState.playbackState,p.READY):i===p.PAUSED?(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return M(t)}},this.params=e,this.video=nt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(at(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const l=this.params.desiredState.videoTrack.getTransition();l&&k(l.to)&&(this.params.desiredState.videoTrack.setState(l.to),this.params.output.currentVideoTrack$.next(this.trackUrls[l.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),dt(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();R(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];R(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=Ut(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ae(r))}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Wa=["stun:videostun.mycdn.me:80"],_m=1e3,km=3,Fs=()=>null;class Pm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Fs,this.externalStopCallback=Fs,this.externalErrorCallback=Fs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Wa}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:D.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),_m)}normalizeOptions(e={}){const t={stunServerList:Wa,maxRetryNumber:km,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));class Rm{constructor(e){this.videoState=new de(se.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:i===p.PAUSED?(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return M(t)}},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=nt(e.container),this.liveStreamClient=new Pm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),dt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(this.videoState.stateChangeStarted$.pipe(_(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=ot(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===se.READY&&this.videoState.setState(se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(at(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return M(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:re.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Qa{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var Im=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Us,Vs,Hs,Ys,qs,Gs,Di,zs,Li,js,Ci,Ws,xi,Qs,Oi,Js;const ho=Im(),ct=document.createElement("video"),Qe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Vs=(Us=window.SourceBuffer)===null||Us===void 0?void 0:Us.prototype)===null||Vs===void 0?void 0:Vs.appendBuffer)),hls:Boolean(((Hs=ct.canPlayType)===null||Hs===void 0?void 0:Hs.call(ct,"application/x-mpegurl"))||((Ys=ct.canPlayType)===null||Ys===void 0?void 0:Ys.call(ct,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((qs=ct.canPlayType)===null||qs===void 0?void 0:qs.call(ct,"video/mp4")),webm:Boolean((Gs=ct.canPlayType)===null||Gs===void 0?void 0:Gs.call(ct,"video/webm")),cmaf:!0},ht={h264:Boolean((zs=(Di=window.MediaSource)===null||Di===void 0?void 0:Di.isTypeSupported)===null||zs===void 0?void 0:zs.call(Di,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((js=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||js===void 0?void 0:js.call(Li,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Ws=(Ci=window.MediaSource)===null||Ci===void 0?void 0:Ci.isTypeSupported)===null||Ws===void 0?void 0:Ws.call(Ci,'video/webm; codecs="vp9"')),aac:Boolean((Qs=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||Qs===void 0?void 0:Qs.call(xi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Js=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||Js===void 0?void 0:Js.call(Oi,'audio/webm; codecs="opus"'))},Ct=(ht.h264||ht.h265)&&ht.aac,os=Qe.hls&&Re.mp4,Dm=Boolean(window.WebSocket),Lm=()=>Object.keys(ht).filter(s=>ht[s]),Cm=(s,e=!1)=>s.filter(t=>{switch(t){case T.DASH:return Qe.mse&&Re.mp4&&Ct;case T.DASH_SEP:return Qe.mse&&Re.mp4&&Ct;case T.DASH_WEBM:return Qe.mse&&Re.webm&&ht.vp9&&ht.opus;case T.DASH_LIVE:return Qe.mse&&Re.mp4&&Ct;case T.DASH_LIVE_CMAF:return Qe.mse&&Re.mp4&&Ct&&Re.cmaf;case T.DASH_ONDEMAND:return Qe.mse&&Re.mp4&&Ct;case T.HLS:case T.HLS_LIVE:case T.HLS_LIVE_CMAF:case T.HLS_ONDEMAND:return os||e&&Qe.mse&&Re.mp4&&Ct;case T.MPEG:return Re.mp4;case T.DASH_LIVE_WEBM:return!1;case T.WEB_RTC_LIVE:return Qe.webrtc&&Dm&&ht.h264&&(Re.mp4||Re.webm);default:return M(t)}}),xm=()=>ho?[T.MPEG,T.DASH_WEBM,T.DASH_SEP,T.DASH,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND]:os?[T.DASH_WEBM,T.DASH_SEP,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND,T.MPEG,T.DASH]:[T.DASH_WEBM,T.DASH_SEP,T.DASH,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND,T.MPEG],Om=()=>ho?[T.HLS_LIVE,T.HLS_LIVE_CMAF,T.WEB_RTC_LIVE,T.DASH_LIVE,T.DASH_LIVE_CMAF]:os?[T.WEB_RTC_LIVE,T.HLS_LIVE,T.HLS_LIVE_CMAF,T.DASH_LIVE,T.DASH_LIVE_CMAF]:[T.WEB_RTC_LIVE,T.DASH_LIVE,T.DASH_LIVE_CMAF,T.HLS_LIVE,T.HLS_LIVE_CMAF],Ja=s=>s?[T.HLS_LIVE]:[T.DASH_WEBM,T.DASH_SEP,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND,T.MPEG];var Nm=s=>new Ki(e=>{const t=new ae,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:u})=>`${d}-${u}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$,n=new C;let o=0,l="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),l=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),l="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ka={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Bm={cacheDuration:12e4},Mm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Fm={maxPausedTime:3e4},Xa={maxPausedTime:3e4};class Um{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0)},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Cm([...Om(),...xm()],this.params.tuning.useHlsJs).filter(n=>k(e.sources[n])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(n=>!i.includes(n)),...t.filter(n=>i.includes(n))]:t;this.screenFormatsIterator=new Qa(r);const a=[...Ja(!0),...Ja(!1)];this.chromecastFormatsIterator=new Qa(a.filter(n=>k(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(X(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;R(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==q.None;this.params.desiredState.seekState.setState({state:q.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return M(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case T.DASH:{const o=this.applyFailoverHost(t[e]);return R(o),new cp({...n,source:o,config:Bm})}case T.DASH_SEP:case T.DASH_WEBM:case T.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Ca({...n,source:o,format:e,config:Xa}):new bm({...n,source:o})}case T.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Ca({...n,source:o,format:e,config:Xa})}case T.HLS:case T.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),os||!this.params.tuning.useHlsJs?new Am({...n,source:o}):new Tm({...n,source:o})}case T.HLS_LIVE:case T.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new $m({...n,source:o,config:Fm})}case T.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new wm({...n,source:o})}case T.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new np({...n,source:o,config:Mm})}case T.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new Rm({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case T.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return R(o),new hf({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return M(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return M(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return M(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return hi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,i=0;return e.add(V(this.providerOutput.error$,Nm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ka.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(te(({type:r})=>r!==void 0))}).pipe(_(r=>({id:`ProviderHangup:${r}`,category:D.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(te(({to:a})=>a===p.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===D.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=i<Ka.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const dr=(s,e,t)=>t*e+(1-t)*s,fo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Vm=(s,e,t,i)=>{let r=0,a=t;const n=fo(s,e),o=e<i?e:i;for(let l=0;l<o;l++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class po{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${i}`),this.smoothedSeries$=new Ye(`smoothed_${i}`),this.reportedSeries$=new Ye(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(X(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Hm extends po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=dr(this.slow,e,this.params.emaAlphaSlow),this.fast=dr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ym extends po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=dr(this.emaSmoothed,e,this.params.emaAlpha);const i=Vm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Za{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Hm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ym({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const qm=5e3,en="one_video_throughput",tn="one_video_rtt",et=window.navigator.connection,sn=()=>{const s=et==null?void 0:et.downlink;if(k(s)&&s!==10)return s*1e3},rn=()=>{const s=et==null?void 0:et.rtt;if(k(s)&&s!==3e3)return s},an=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class ni{constructor(e){var t,i;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ni.load(en)||(e.useBrowserEstimation?sn():void 0)||qm,a=(i=(t=ni.load(tn))!==null&&t!==void 0?t:e.useBrowserEstimation?rn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(an(r,a,e.rttPenaltyRequestSize)),this.throughput=Za.getSmoothedValue(r,-1,e),this.rtt=Za.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const l=sn();l&&this.throughput.next(l);const d=rn();k(d)&&this.rtt.next(d)};et&&"onchange"in et&&this.subscription.add(N(et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hs.set(en,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hs.set(tn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(qe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>an(n,o,e.rttPenaltyRequestSize)),te(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=he();const r=new ae;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(N(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(N(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(N(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),l=n-t,d=o-i;this.addRawSpeed(l,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=he();let a=0,n=he();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:u})=>{d?(this.addRawSpeed(i,he()-r,1),this.concurrentDownloads.delete(e)):u&&(i+=u.byteLength,a+=u.byteLength,a>=this.tuningConfig.streamMinSampleSize&&he()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,he()-n,this.concurrentDownloads.size),a=0,n=he()),await(t==null?void 0:t.read().then(l,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(l,o)}addRawSpeed(e,t,i=1){if(ni.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=hs.get(e);if(k(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const nn={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Gm=s=>{const e={};for(const t of Object.keys(nn)){const i=nn[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var zm=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===q.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),te(k)),e.pipe(te(()=>s.getState().state===q.None))),jm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return R(e,`Wrong container or containerId {${s.container}}`),e};class Zm{constructor(e={}){if(this.subscription=new ae,this.logger=new Oo,this.isPlaybackStarted=!1,this.desiredState={playbackState:new de(p.STOPPED),seekState:new de({state:q.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({})},this.info={playbackState$:new y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),atLiveEdge$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(lt.NONE),chromecastState$:new y(Te.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new C,ready$:new C,started$:new C,playing$:new C,paused$:new C,stopped$:new C,willStart$:new C,willResume$:new C,willPause$:new C,willStop$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:Ff},this.initLogs(),this.tuning=Gm(e),this.chromecastInitializer=new Vo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ni(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const l=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,u=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:D.WTF,message:u,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=jm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Um({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==p.PLAYING&&e.startTransitionTo(p.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:q.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){R(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;R(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(X(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===q.None?void 0:t.position;return k(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(V(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(te(({from:e})=>e===p.STOPPED),ge()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===q.Requested?this.desiredState.seekState.setState({...n,state:q.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===q.Applying&&(this.desiredState.seekState.setState({state:q.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,l)=>Gi(o)?1:Gi(l)?-1:Fi(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(qe({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(_(({isLive:n,position:o})=>n&&o>-No),pe()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),pe()).subscribe(this.info.volume$)).add(zm({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(Bt(!0)),e.providerOutput.seekedEvent$.pipe(Bt(!1))).pipe(pe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:"NoProviders",category:D.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),_(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),_(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),_(()=>he()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new y(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(te(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),pe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(V(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,l;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(l=n==null?void 0:n.size)===null||l===void 0?void 0:l.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})),this.subscription.add(V(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let u;d===Te.CONNECTED?u=lt.SECOND_SCREEN:l?n?u=lt.PIP:o?u=lt.FULLSCREEN:u=lt.INLINE:u=lt.NONE,this.info.surface$.getValue()!==u&&this.info.surface$.next(u)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ae;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(te(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=fi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(V(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),Mf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Bf(i)),this.providerContainer.current$.subscribe(({type:i})=>ki("provider",i)),t.duration$.subscribe(i=>ki("duration",i)),t.availableVideoTracks$.pipe(te(i=>!!i.length),ge()).subscribe(i=>ki("tracks",i)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(i=>this.subscription.add(i)),ki("codecs",Lm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})};this.subscription.add(V(N(document,"visibilitychange"),N(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const ev=`${Fo}@${Mo}`;export{Te as ChromecastState,oi as HttpConnectionType,sv as Observable,p as PlaybackState,Zm as Player,ev as SDK_VERSION,rv as Subject,av as Subscription,lt as Surface,nv as ValueSubject,T as VideoFormat,re as VideoQuality};