@vkontakte/videoplayer-core 2.0.80 → 2.0.81
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/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/package.json +1 -1
package/es2015.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.81
|
|
3
|
+
* Tue, 28 Mar 2023 08:39:32 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-81/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as b,Subject as C,Subscription as se,isNonNullable as _,ErrorCategory as O,isNullable as K,fromEvent as G,assertNever as L,merge as x,tap as Fa,map as $,observableFrom as Ce,filterChanged as me,assertNonNullable as P,debounce as Ge,timeout as Iu,combine as nt,once as ye,mapTo as Ct,filter as j,now as pe,Observable as Pi,abortable as Fe,getExponentialDelay as Ha,interval as Du,Logger as Cu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as Ub,Subject as Vb,Subscription as Fb,ValueSubject as Hb}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Ou from"lodash/debounce.js";const Lu="2.0.80",xu="@vkontakte/videoplayer-core";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var T;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(T||(T={}));var Ie;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ie||(Ie={}));var we;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(we||(we={}));var wi;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(wi||(wi={}));var F;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(F||(F={}));var Nu=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Bu{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(we.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new b(we.NOT_AVAILABLE),this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)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||Nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:O.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 s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.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();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(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),s=cast.framework.CastContext.getInstance();this.subscription.add(G(s,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=s.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 L(r.sessionState)}})).add(x(G(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Ce([s.getCastState()])).pipe(me(),$(Mu),Fa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===we.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),c=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(c)||c===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===we.CONNECTED?_(this.connection$.getValue())?we.CONNECTED:we.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=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:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:O.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Mu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return we.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return we.AVAILABLE;case cast.framework.CastState.CONNECTING:return we.CONNECTING;case cast.framework.CastState.CONNECTED:return we.CONNECTED;default:return L(i)}};var Ga=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Ue=function(i){try{return!!i()}catch(e){return!0}},Uu=Ue,ws=!Uu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Io=ws,Do=Function.prototype,Br=Do.call,Vu=Io&&Do.bind.bind(Br,Br),Ze=Io?Vu:function(i){return function(){return Br.apply(i,arguments)}},Co=Ze,Fu=Co({}.toString),Hu=Co("".slice),_s=function(i){return Hu(Fu(i),8,-1)},Gu=Ze,Yu=Ue,qu=_s,Hs=Object,ju=Gu("".split),zu=Yu(function(){return!Hs("z").propertyIsEnumerable(0)})?function(i){return qu(i)=="String"?ju(i,""):Hs(i)}:Hs,ks=function(i){return i==null},Wu=ks,Qu=TypeError,Oo=function(i){if(Wu(i))throw Qu("Can't call method on "+i);return i},Ju=zu,Ku=Oo,Ri=function(i){return Ju(Ku(i))},Xu=function(){},ti={},Fi=function(i){return i&&i.Math==Math&&i},_e=Fi(typeof globalThis=="object"&&globalThis)||Fi(typeof window=="object"&&window)||Fi(typeof self=="object"&&self)||Fi(typeof Ga=="object"&&Ga)||function(){return this}()||Function("return this")(),Mr=typeof document=="object"&&document.all,Zu=typeof Mr=="undefined"&&Mr!==void 0,Lo={all:Mr,IS_HTMLDDA:Zu},xo=Lo,ec=xo.all,Te=xo.IS_HTMLDDA?function(i){return typeof i=="function"||i===ec}:function(i){return typeof i=="function"},tc=_e,ic=Te,Ya=tc.WeakMap,sc=ic(Ya)&&/native code/.test(String(Ya)),qa=Te,No=Lo,rc=No.all,bt=No.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:qa(i)||i===rc}:function(i){return typeof i=="object"?i!==null:qa(i)},ac=Ue,ut=!ac(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Lt={},nc=_e,ja=bt,Ur=nc.document,oc=ja(Ur)&&ja(Ur.createElement),na=function(i){return oc?Ur.createElement(i):{}},dc=ut,uc=Ue,cc=na,Bo=!dc&&!uc(function(){return Object.defineProperty(cc("div"),"a",{get:function(){return 7}}).a!=7}),lc=ut,hc=Ue,Mo=lc&&hc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),fc=bt,pc=String,vc=TypeError,yt=function(i){if(fc(i))return i;throw vc(pc(i)+" is not an object")},mc=ws,Hi=Function.prototype.call,qe=mc?Hi.bind(Hi):function(){return Hi.apply(Hi,arguments)},oa={},Gs=oa,Ys=_e,Sc=Te,za=function(i){return Sc(i)?i:void 0},xt=function(i,e){return arguments.length<2?za(Gs[i])||za(Ys[i]):Gs[i]&&Gs[i][e]||Ys[i]&&Ys[i][e]},gc=Ze,da=gc({}.isPrototypeOf),Ps=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Uo=_e,qs=Ps,Wa=Uo.process,Qa=Uo.Deno,Ja=Wa&&Wa.versions||Qa&&Qa.version,Ka=Ja&&Ja.v8,Ve,ps;Ka&&(Ve=Ka.split("."),ps=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ps&&qs&&(Ve=qs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=qs.match(/Chrome\/(\d+)/),Ve&&(ps=+Ve[1])));var Vo=ps,Xa=Vo,bc=Ue,Fo=!!Object.getOwnPropertySymbols&&!bc(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Xa&&Xa<41}),yc=Fo,Ho=yc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Tc=xt,Ec=Te,$c=da,Ac=Ho,wc=Object,Go=Ac?function(i){return typeof i=="symbol"}:function(i){var e=Tc("Symbol");return Ec(e)&&$c(e.prototype,wc(i))},_c=String,Rs=function(i){try{return _c(i)}catch(e){return"Object"}},kc=Te,Pc=Rs,Rc=TypeError,Nt=function(i){if(kc(i))return i;throw Rc(Pc(i)+" is not a function")},Ic=Nt,Dc=ks,ua=function(i,e){var t=i[e];return Dc(t)?void 0:Ic(t)},js=qe,zs=Te,Ws=bt,Cc=TypeError,Oc=function(i,e){var t,s;if(e==="string"&&zs(t=i.toString)&&!Ws(s=js(t,i))||zs(t=i.valueOf)&&!Ws(s=js(t,i))||e!=="string"&&zs(t=i.toString)&&!Ws(s=js(t,i)))return s;throw Cc("Can't convert object to primitive value")},vs={},Lc={get exports(){return vs},set exports(i){vs=i}},Yo=!0,Za=_e,xc=Object.defineProperty,Nc=function(i,e){try{xc(Za,i,{value:e,configurable:!0,writable:!0})}catch(t){Za[i]=e}return e},Bc=_e,Mc=Nc,en="__core-js_shared__",Uc=Bc[en]||Mc(en,{}),ca=Uc,tn=ca;(Lc.exports=function(i,e){return tn[i]||(tn[i]=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 Vc=Oo,Fc=Object,la=function(i){return Fc(Vc(i))},Hc=Ze,Gc=la,Yc=Hc({}.hasOwnProperty),ct=Object.hasOwn||function(e,t){return Yc(Gc(e),t)},qc=Ze,jc=0,zc=Math.random(),Wc=qc(1 .toString),qo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Wc(++jc+zc,36)},Qc=_e,Jc=vs,sn=ct,Kc=qo,Xc=Fo,Zc=Ho,qt=Qc.Symbol,Qs=Jc("wks"),el=Zc?qt.for||qt:qt&&qt.withoutSetter||Kc,Oe=function(i){return sn(Qs,i)||(Qs[i]=Xc&&sn(qt,i)?qt[i]:el("Symbol."+i)),Qs[i]},tl=qe,rn=bt,an=Go,il=ua,sl=Oc,rl=Oe,al=TypeError,nl=rl("toPrimitive"),ol=function(i,e){if(!rn(i)||an(i))return i;var t=il(i,nl),s;if(t){if(e===void 0&&(e="default"),s=tl(t,i,e),!rn(s)||an(s))return s;throw al("Can't convert object to primitive value")}return e===void 0&&(e="number"),sl(i,e)},dl=ol,ul=Go,ha=function(i){var e=dl(i,"string");return ul(e)?e:e+""},cl=ut,ll=Bo,hl=Mo,Gi=yt,nn=ha,fl=TypeError,Js=Object.defineProperty,pl=Object.getOwnPropertyDescriptor,Ks="enumerable",Xs="configurable",Zs="writable";Lt.f=cl?hl?function(e,t,s){if(Gi(e),t=nn(t),Gi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Zs in s&&!s[Zs]){var r=pl(e,t);r&&r[Zs]&&(e[t]=s.value,s={configurable:Xs in s?s[Xs]:r[Xs],enumerable:Ks in s?s[Ks]:r[Ks],writable:!1})}return Js(e,t,s)}:Js:function(e,t,s){if(Gi(e),t=nn(t),Gi(s),ll)try{return Js(e,t,s)}catch(r){}if("get"in s||"set"in s)throw fl("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Is=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},vl=ut,ml=Lt,Sl=Is,Ii=vl?function(i,e,t){return ml.f(i,e,Sl(1,t))}:function(i,e,t){return i[e]=t,i},gl=vs,bl=qo,on=gl("keys"),fa=function(i){return on[i]||(on[i]=bl(i))},pa={},yl=sc,jo=_e,Tl=bt,El=Ii,er=ct,tr=ca,$l=fa,Al=pa,dn="Object already initialized",Vr=jo.TypeError,wl=jo.WeakMap,ms,_i,Ss,_l=function(i){return Ss(i)?_i(i):ms(i,{})},kl=function(i){return function(e){var t;if(!Tl(e)||(t=_i(e)).type!==i)throw Vr("Incompatible receiver, "+i+" required");return t}};if(yl||tr.state){var Qe=tr.state||(tr.state=new wl);Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,ms=function(i,e){if(Qe.has(i))throw Vr(dn);return e.facade=i,Qe.set(i,e),e},_i=function(i){return Qe.get(i)||{}},Ss=function(i){return Qe.has(i)}}else{var Ft=$l("state");Al[Ft]=!0,ms=function(i,e){if(er(i,Ft))throw Vr(dn);return e.facade=i,El(i,Ft,e),e},_i=function(i){return er(i,Ft)?i[Ft]:{}},Ss=function(i){return er(i,Ft)}}var zo={set:ms,get:_i,has:Ss,enforce:_l,getterFor:kl},Pl=ws,Wo=Function.prototype,un=Wo.apply,cn=Wo.call,Qo=typeof Reflect=="object"&&Reflect.apply||(Pl?cn.bind(un):function(){return cn.apply(un,arguments)}),Rl=_s,Il=Ze,Jo=function(i){if(Rl(i)==="Function")return Il(i)},va={},Ko={},Xo={}.propertyIsEnumerable,Zo=Object.getOwnPropertyDescriptor,Dl=Zo&&!Xo.call({1:2},1);Ko.f=Dl?function(e){var t=Zo(this,e);return!!t&&t.enumerable}:Xo;var Cl=ut,Ol=qe,Ll=Ko,xl=Is,Nl=Ri,Bl=ha,Ml=ct,Ul=Bo,ln=Object.getOwnPropertyDescriptor;va.f=Cl?ln:function(e,t){if(e=Nl(e),t=Bl(t),Ul)try{return ln(e,t)}catch(s){}if(Ml(e,t))return xl(!Ol(Ll.f,e,t),e[t])};var Vl=Ue,Fl=Te,Hl=/#|\.prototype\./,Di=function(i,e){var t=Yl[Gl(i)];return t==jl?!0:t==ql?!1:Fl(e)?Vl(e):!!e},Gl=Di.normalize=function(i){return String(i).replace(Hl,".").toLowerCase()},Yl=Di.data={},ql=Di.NATIVE="N",jl=Di.POLYFILL="P",ed=Di,hn=Jo,zl=Nt,Wl=ws,Ql=hn(hn.bind),Ds=function(i,e){return zl(i),e===void 0?i:Wl?Ql(i,e):function(){return i.apply(e,arguments)}},Yi=_e,Jl=Qo,Kl=Jo,Xl=Te,Zl=va.f,eh=ed,Ht=oa,th=Ds,Gt=Ii,fn=ct,ih=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Jl(i,this,arguments)};return e.prototype=i.prototype,e},et=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Yi:r?Yi[t]:(Yi[t]||{}).prototype,o=s?Ht:Ht[t]||Gt(Ht,t,{})[t],u=o.prototype,d,c,l,h,f,m,p,S,g;for(h in e)d=eh(s?h:t+(r?".":"#")+h,i.forced),c=!d&&n&&fn(n,h),m=o[h],c&&(i.dontCallGetSet?(g=Zl(n,h),p=g&&g.value):p=n[h]),f=c&&p?p:e[h],!(c&&typeof m==typeof f)&&(i.bind&&c?S=th(f,Yi):i.wrap&&c?S=ih(f):a&&Xl(f)?S=Kl(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&Gt(S,"sham",!0),Gt(o,h,S),a&&(l=t+"Prototype",fn(Ht,l)||Gt(Ht,l,{}),Gt(Ht[l],h,f),i.real&&u&&(d||!u[h])&&Gt(u,h,f)))},Fr=ut,sh=ct,td=Function.prototype,rh=Fr&&Object.getOwnPropertyDescriptor,ma=sh(td,"name"),ah=ma&&function(){}.name==="something",nh=ma&&(!Fr||Fr&&rh(td,"name").configurable),oh={EXISTS:ma,PROPER:ah,CONFIGURABLE:nh},id={},dh=Math.ceil,uh=Math.floor,ch=Math.trunc||function(e){var t=+e;return(t>0?uh:dh)(t)},lh=ch,Sa=function(i){var e=+i;return e!==e||e===0?0:lh(e)},hh=Sa,fh=Math.max,ph=Math.min,vh=function(i,e){var t=hh(i);return t<0?fh(t+e,0):ph(t,e)},mh=Sa,Sh=Math.min,gh=function(i){return i>0?Sh(mh(i),9007199254740991):0},bh=gh,ga=function(i){return bh(i.length)},yh=Ri,Th=vh,Eh=ga,pn=function(i){return function(e,t,s){var r=yh(e),a=Eh(r),n=Th(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},$h={includes:pn(!0),indexOf:pn(!1)},Ah=Ze,ir=ct,wh=Ri,_h=$h.indexOf,kh=pa,vn=Ah([].push),Ph=function(i,e){var t=wh(i),s=0,r=[],a;for(a in t)!ir(kh,a)&&ir(t,a)&&vn(r,a);for(;e.length>s;)ir(t,a=e[s++])&&(~_h(r,a)||vn(r,a));return r},sd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rh=Ph,Ih=sd,Dh=Object.keys||function(e){return Rh(e,Ih)},Ch=ut,Oh=Mo,Lh=Lt,xh=yt,Nh=Ri,Bh=Dh;id.f=Ch&&!Oh?Object.defineProperties:function(e,t){xh(e);for(var s=Nh(t),r=Bh(t),a=r.length,n=0,o;a>n;)Lh.f(e,o=r[n++],s[o]);return e};var Mh=xt,rd=Mh("document","documentElement"),Uh=yt,Vh=id,mn=sd,Fh=pa,Hh=rd,Gh=na,Yh=fa,Sn=">",gn="<",Hr="prototype",Gr="script",ad=Yh("IE_PROTO"),sr=function(){},nd=function(i){return gn+Gr+Sn+i+gn+"/"+Gr+Sn},bn=function(i){i.write(nd("")),i.close();var e=i.parentWindow.Object;return i=null,e},qh=function(){var i=Gh("iframe"),e="java"+Gr+":",t;return i.style.display="none",Hh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(nd("document.F=Object")),t.close(),t.F},qi,us=function(){try{qi=new ActiveXObject("htmlfile")}catch(e){}us=typeof document!="undefined"?document.domain&&qi?bn(qi):qh():bn(qi);for(var i=mn.length;i--;)delete us[Hr][mn[i]];return us()};Fh[ad]=!0;var od=Object.create||function(e,t){var s;return e!==null?(sr[Hr]=Uh(e),s=new sr,sr[Hr]=null,s[ad]=e):s=us(),t===void 0?s:Vh.f(s,t)},jh=Ue,zh=!jh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Wh=ct,Qh=Te,Jh=la,Kh=fa,Xh=zh,yn=Kh("IE_PROTO"),Yr=Object,Zh=Yr.prototype,dd=Xh?Yr.getPrototypeOf:function(i){var e=Jh(i);if(Wh(e,yn))return e[yn];var t=e.constructor;return Qh(t)&&e instanceof t?t.prototype:e instanceof Yr?Zh:null},ef=Ii,ba=function(i,e,t,s){return s&&s.enumerable?i[e]=t:ef(i,e,t),i},tf=Ue,sf=Te,rf=bt,af=od,Tn=dd,nf=ba,of=Oe,qr=of("iterator"),ud=!1,ot,rr,ar;[].keys&&(ar=[].keys(),"next"in ar?(rr=Tn(Tn(ar)),rr!==Object.prototype&&(ot=rr)):ud=!0);var df=!rf(ot)||tf(function(){var i={};return ot[qr].call(i)!==i});df?ot={}:ot=af(ot);sf(ot[qr])||nf(ot,qr,function(){return this});var cd={IteratorPrototype:ot,BUGGY_SAFARI_ITERATORS:ud},uf=Oe,cf=uf("toStringTag"),ld={};ld[cf]="z";var ya=String(ld)==="[object z]",lf=ya,hf=Te,cs=_s,ff=Oe,pf=ff("toStringTag"),vf=Object,mf=cs(function(){return arguments}())=="Arguments",Sf=function(i,e){try{return i[e]}catch(t){}},Cs=lf?cs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Sf(e=vf(i),pf))=="string"?t:mf?cs(e):(s=cs(e))=="Object"&&hf(e.callee)?"Arguments":s},gf=ya,bf=Cs,yf=gf?{}.toString:function(){return"[object "+bf(this)+"]"},Tf=ya,Ef=Lt.f,$f=Ii,Af=ct,wf=yf,_f=Oe,En=_f("toStringTag"),Ta=function(i,e,t,s){if(i){var r=t?i:i.prototype;Af(r,En)||Ef(r,En,{configurable:!0,value:e}),s&&!Tf&&$f(r,"toString",wf)}},kf=cd.IteratorPrototype,Pf=od,Rf=Is,If=Ta,Df=ti,Cf=function(){return this},Of=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Pf(kf,{next:Rf(+!s,t)}),If(i,r,!1,!0),Df[r]=Cf,i},Lf=et,xf=qe,hd=oh,Nf=Of,Bf=dd,Mf=Ta,$n=ba,Uf=Oe,An=ti,fd=cd,Vf=hd.PROPER;hd.CONFIGURABLE;fd.IteratorPrototype;var ji=fd.BUGGY_SAFARI_ITERATORS,nr=Uf("iterator"),wn="keys",zi="values",_n="entries",Ff=function(){return this},Hf=function(i,e,t,s,r,a,n){Nf(t,e,s);var o=function(g){if(g===r&&h)return h;if(!ji&&g in c)return c[g];switch(g){case wn:return function(){return new t(this,g)};case zi:return function(){return new t(this,g)};case _n:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,c=i.prototype,l=c[nr]||c["@@iterator"]||r&&c[r],h=!ji&&l||o(r),f=e=="Array"&&c.entries||l,m,p,S;if(f&&(m=Bf(f.call(new i)),m!==Object.prototype&&m.next&&(Mf(m,u,!0,!0),An[u]=Ff)),Vf&&r==zi&&l&&l.name!==zi&&(d=!0,h=function(){return xf(l,this)}),r)if(p={values:o(zi),keys:a?h:o(wn),entries:o(_n)},n)for(S in p)(ji||d||!(S in c))&&$n(c,S,p[S]);else Lf({target:e,proto:!0,forced:ji||d},p);return n&&c[nr]!==h&&$n(c,nr,h,{name:r}),An[e]=h,p},Gf=function(i,e){return{value:i,done:e}},Yf=Ri,Ea=Xu,kn=ti,pd=zo,qf=Lt.f,jf=Hf,Wi=Gf,zf=Yo,Wf=ut,vd="Array Iterator",Qf=pd.set,Jf=pd.getterFor(vd);jf(Array,"Array",function(i,e){Qf(this,{type:vd,target:Yf(i),index:0,kind:e})},function(){var i=Jf(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Wi(void 0,!0)):t=="keys"?Wi(s,!1):t=="values"?Wi(e[s],!1):Wi([s,e[s]],!1)},"values");var Pn=kn.Arguments=kn.Array;Ea();Ea();Ea();if(!zf&&Wf&&Pn.name!=="values")try{qf(Pn,"name",{value:"values"})}catch(i){}var Kf=Oe,Xf=ti,Zf=Kf("iterator"),ep=Array.prototype,tp=function(i){return i!==void 0&&(Xf.Array===i||ep[Zf]===i)},ip=Cs,Rn=ua,sp=ks,rp=ti,ap=Oe,np=ap("iterator"),md=function(i){if(!sp(i))return Rn(i,np)||Rn(i,"@@iterator")||rp[ip(i)]},op=qe,dp=Nt,up=yt,cp=Rs,lp=md,hp=TypeError,fp=function(i,e){var t=arguments.length<2?lp(i):e;if(dp(t))return up(op(t,i));throw hp(cp(i)+" is not iterable")},pp=qe,In=yt,vp=ua,mp=function(i,e,t){var s,r;In(i);try{if(s=vp(i,"return"),!s){if(e==="throw")throw t;return t}s=pp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return In(s),t},Sp=Ds,gp=qe,bp=yt,yp=Rs,Tp=tp,Ep=ga,Dn=da,$p=fp,Ap=md,Cn=mp,wp=TypeError,ls=function(i,e){this.stopped=i,this.result=e},On=ls.prototype,$a=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Sp(e,s),d,c,l,h,f,m,p,S=function(y){return d&&Cn(d,"normal",y),new ls(!0,y)},g=function(y){return r?(bp(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)d=i.iterator;else if(n)d=i;else{if(c=Ap(i),!c)throw wp(yp(i)+" is not iterable");if(Tp(c)){for(l=0,h=Ep(i);h>l;l++)if(f=g(i[l]),f&&Dn(On,f))return f;return new ls(!1)}d=$p(i,c)}for(m=a?i.next:d.next;!(p=gp(m,d)).done;){try{f=g(p.value)}catch(y){Cn(d,"throw",y)}if(typeof f=="object"&&f&&Dn(On,f))return f}return new ls(!1)},_p=ha,kp=Lt,Pp=Is,Rp=function(i,e,t){var s=_p(e);s in i?kp.f(i,s,Pp(0,t)):i[s]=t},Ip=et,Dp=$a,Cp=Rp;Ip({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Dp(e,function(s,r){Cp(t,s,r)},{AS_ENTRIES:!0}),t}});var Op=oa,Lp=Op.Object.fromEntries,xp={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},Np=xp,Bp=_e,Mp=Cs,Up=Ii,Ln=ti,Vp=Oe,xn=Vp("toStringTag");for(var or in Np){var Nn=Bp[or],dr=Nn&&Nn.prototype;dr&&Mp(dr)!==xn&&Up(dr,xn,or),Ln[or]=Ln.Array}var Fp=Lp,Hp=Fp,Gp=Hp,Yp=Gp,Ci=Yp,qp=_s,Os=typeof process!="undefined"&&qp(process)=="process",jp=xt,zp=Lt,Wp=Oe,Qp=ut,Bn=Wp("species"),Jp=function(i){var e=jp(i),t=zp.f;Qp&&e&&!e[Bn]&&t(e,Bn,{configurable:!0,get:function(){return this}})},Kp=da,Xp=TypeError,Zp=function(i,e){if(Kp(e,i))return i;throw Xp("Incorrect invocation")},ev=Ze,tv=Te,jr=ca,iv=ev(Function.toString);tv(jr.inspectSource)||(jr.inspectSource=function(i){return iv(i)});var Sd=jr.inspectSource,sv=Ze,rv=Ue,gd=Te,av=Cs,nv=xt,ov=Sd,bd=function(){},dv=[],yd=nv("Reflect","construct"),Aa=/^\s*(?:class|function)\b/,uv=sv(Aa.exec),cv=!Aa.exec(bd),vi=function(e){if(!gd(e))return!1;try{return yd(bd,dv,e),!0}catch(t){return!1}},Td=function(e){if(!gd(e))return!1;switch(av(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cv||!!uv(Aa,ov(e))}catch(t){return!0}};Td.sham=!0;var lv=!yd||rv(function(){var i;return vi(vi.call)||!vi(Object)||!vi(function(){i=!0})||i})?Td:vi,hv=lv,fv=Rs,pv=TypeError,vv=function(i){if(hv(i))return i;throw pv(fv(i)+" is not a constructor")},Mn=yt,mv=vv,Sv=ks,gv=Oe,bv=gv("species"),Ed=function(i,e){var t=Mn(i).constructor,s;return t===void 0||Sv(s=Mn(t)[bv])?e:mv(s)},yv=Ze,Tv=yv([].slice),Ev=TypeError,$v=function(i,e){if(i<e)throw Ev("Not enough arguments");return i},Av=Ps,$d=/(?:ipad|iphone|ipod).*applewebkit/i.test(Av),De=_e,wv=Qo,_v=Ds,Un=Te,kv=ct,Ad=Ue,Vn=rd,Pv=Tv,Fn=na,Rv=$v,Iv=$d,Dv=Os,zr=De.setImmediate,Wr=De.clearImmediate,Cv=De.process,ur=De.Dispatch,Ov=De.Function,Hn=De.MessageChannel,Lv=De.String,cr=0,yi={},Gn="onreadystatechange",ki,Pt,lr,hr;Ad(function(){ki=De.location});var wa=function(i){if(kv(yi,i)){var e=yi[i];delete yi[i],e()}},fr=function(i){return function(){wa(i)}},Yn=function(i){wa(i.data)},qn=function(i){De.postMessage(Lv(i),ki.protocol+"//"+ki.host)};(!zr||!Wr)&&(zr=function(e){Rv(arguments.length,1);var t=Un(e)?e:Ov(e),s=Pv(arguments,1);return yi[++cr]=function(){wv(t,void 0,s)},Pt(cr),cr},Wr=function(e){delete yi[e]},Dv?Pt=function(i){Cv.nextTick(fr(i))}:ur&&ur.now?Pt=function(i){ur.now(fr(i))}:Hn&&!Iv?(lr=new Hn,hr=lr.port2,lr.port1.onmessage=Yn,Pt=_v(hr.postMessage,hr)):De.addEventListener&&Un(De.postMessage)&&!De.importScripts&&ki&&ki.protocol!=="file:"&&!Ad(qn)?(Pt=qn,De.addEventListener("message",Yn,!1)):Gn in Fn("script")?Pt=function(i){Vn.appendChild(Fn("script"))[Gn]=function(){Vn.removeChild(this),wa(i)}}:Pt=function(i){setTimeout(fr(i),0)});var wd={set:zr,clear:Wr},_d=function(){this.head=null,this.tail=null};_d.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var kd=_d,xv=Ps,Nv=/ipad|iphone|ipod/i.test(xv)&&typeof Pebble!="undefined",Bv=Ps,Mv=/web0s(?!.*chrome)/i.test(Bv),Ot=_e,jn=Ds,Uv=va.f,pr=wd.set,Vv=kd,Fv=$d,Hv=Nv,Gv=Mv,vr=Os,zn=Ot.MutationObserver||Ot.WebKitMutationObserver,Wn=Ot.document,Qn=Ot.process,Qi=Ot.Promise,Jn=Uv(Ot,"queueMicrotask"),Qr=Jn&&Jn.value,Yt,mr,Sr,Ji,Kn;if(!Qr){var Ki=new Vv,Xi=function(){var i,e;for(vr&&(i=Qn.domain)&&i.exit();e=Ki.get();)try{e()}catch(t){throw Ki.head&&Yt(),t}i&&i.enter()};!Fv&&!vr&&!Gv&&zn&&Wn?(mr=!0,Sr=Wn.createTextNode(""),new zn(Xi).observe(Sr,{characterData:!0}),Yt=function(){Sr.data=mr=!mr}):!Hv&&Qi&&Qi.resolve?(Ji=Qi.resolve(void 0),Ji.constructor=Qi,Kn=jn(Ji.then,Ji),Yt=function(){Kn(Xi)}):vr?Yt=function(){Qn.nextTick(Xi)}:(pr=jn(pr,Ot),Yt=function(){pr(Xi)}),Qr=function(i){Ki.head||Yt(),Ki.add(i)}}var Yv=Qr,qv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},_a=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},jv=_e,ii=jv.Promise,Pd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",zv=Pd,Wv=Os,Qv=!zv&&!Wv&&typeof window=="object"&&typeof document=="object",Jv=_e,Ti=ii,Kv=Te,Xv=ed,Zv=Sd,em=Oe,tm=Qv,im=Pd,gr=Vo,Xn=Ti&&Ti.prototype,sm=em("species"),Jr=!1,Rd=Kv(Jv.PromiseRejectionEvent),rm=Xv("Promise",function(){var i=Zv(Ti),e=i!==String(Ti);if(!e&&gr===66||!(Xn.catch&&Xn.finally))return!0;if(!gr||gr<51||!/native code/.test(i)){var t=new Ti(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[sm]=s,Jr=t.then(function(){})instanceof s,!Jr)return!0}return!e&&(tm||im)&&!Rd}),Oi={CONSTRUCTOR:rm,REJECTION_EVENT:Rd,SUBCLASSING:Jr},si={},Zn=Nt,am=TypeError,nm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw am("Bad Promise constructor");e=s,t=r}),this.resolve=Zn(e),this.reject=Zn(t)};si.f=function(i){return new nm(i)};var om=et,gs=Os,gt=_e,Li=qe,dm=ba,um=Ta,cm=Jp,lm=Nt,Kr=Te,hm=bt,fm=Zp,pm=Ed,Id=wd.set,ka=Yv,vm=qv,mm=_a,Sm=kd,Dd=zo,Xr=ii,Pa=Oi,Cd=si,Ls="Promise",Od=Pa.CONSTRUCTOR,gm=Pa.REJECTION_EVENT;Pa.SUBCLASSING;var br=Dd.getterFor(Ls),bm=Dd.set,ym=Xr&&Xr.prototype,jt=Xr,yr=ym,Ld=gt.TypeError,Zr=gt.document,Ra=gt.process,ea=Cd.f,Tm=ea,Em=!!(Zr&&Zr.createEvent&>.dispatchEvent),xd="unhandledrejection",$m="rejectionhandled",eo=0,Nd=1,Am=2,Ia=1,Bd=2,Zi,to,wm,Md=function(i){var e;return hm(i)&&Kr(e=i.then)?e:!1},Ud=function(i,e){var t=e.value,s=e.state==Nd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,c;try{r?(s||(e.rejection===Bd&&km(e),e.rejection=Ia),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===i.promise?n(Ld("Promise-chain cycle")):(d=Md(u))?Li(d,u,a,n):a(u)):n(t)}catch(l){o&&!c&&o.exit(),n(l)}},Vd=function(i,e){i.notified||(i.notified=!0,ka(function(){for(var t=i.reactions,s;s=t.get();)Ud(s,i);i.notified=!1,e&&!i.rejection&&_m(i)}))},Fd=function(i,e,t){var s,r;Em?(s=Zr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),gt.dispatchEvent(s)):s={promise:e,reason:t},!gm&&(r=gt["on"+i])?r(s):i===xd&&vm("Unhandled promise rejection",t)},_m=function(i){Li(Id,gt,function(){var e=i.facade,t=i.value,s=io(i),r;if(s&&(r=mm(function(){gs?Ra.emit("unhandledRejection",t,e):Fd(xd,e,t)}),i.rejection=gs||io(i)?Bd:Ia,r.error))throw r.value})},io=function(i){return i.rejection!==Ia&&!i.parent},km=function(i){Li(Id,gt,function(){var e=i.facade;gs?Ra.emit("rejectionHandled",e):Fd($m,e,i.value)})},zt=function(i,e,t){return function(s){i(e,s,t)}},Qt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Am,Vd(i,!0))},ta=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Ld("Promise can't be resolved itself");var s=Md(e);s?ka(function(){var r={done:!1};try{Li(s,e,zt(ta,r,i),zt(Qt,r,i))}catch(a){Qt(r,a,i)}}):(i.value=e,i.state=Nd,Vd(i,!1))}catch(r){Qt({done:!1},r,i)}}};Od&&(jt=function(e){fm(this,yr),lm(e),Li(Zi,this);var t=br(this);try{e(zt(ta,t),zt(Qt,t))}catch(s){Qt(t,s)}},yr=jt.prototype,Zi=function(e){bm(this,{type:Ls,done:!1,notified:!1,parent:!1,reactions:new Sm,rejection:!1,state:eo,value:void 0})},Zi.prototype=dm(yr,"then",function(e,t){var s=br(this),r=ea(pm(this,jt));return s.parent=!0,r.ok=Kr(e)?e:!0,r.fail=Kr(t)&&t,r.domain=gs?Ra.domain:void 0,s.state==eo?s.reactions.add(r):ka(function(){Ud(r,s)}),r.promise}),to=function(){var i=new Zi,e=br(i);this.promise=i,this.resolve=zt(ta,e),this.reject=zt(Qt,e)},Cd.f=ea=function(i){return i===jt||i===wm?new to(i):Tm(i)});om({global:!0,constructor:!0,wrap:!0,forced:Od},{Promise:jt});um(jt,Ls,!1,!0);cm(Ls);var Pm=Oe,Hd=Pm("iterator"),Gd=!1;try{var Rm=0,so={next:function(){return{done:!!Rm++}},return:function(){Gd=!0}};so[Hd]=function(){return this},Array.from(so,function(){throw 2})}catch(i){}var Im=function(i,e){if(!e&&!Gd)return!1;var t=!1;try{var s={};s[Hd]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Dm=ii,Cm=Im,Om=Oi.CONSTRUCTOR,Yd=Om||!Cm(function(i){Dm.all(i).then(void 0,function(){})}),Lm=et,xm=qe,Nm=Nt,Bm=si,Mm=_a,Um=$a,Vm=Yd;Lm({target:"Promise",stat:!0,forced:Vm},{all:function(e){var t=this,s=Bm.f(t),r=s.resolve,a=s.reject,n=Mm(function(){var o=Nm(t.resolve),u=[],d=0,c=1;Um(e,function(l){var h=d++,f=!1;c++,xm(o,t,l).then(function(m){f||(f=!0,u[h]=m,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),s.promise}});var Fm=et,Hm=Oi.CONSTRUCTOR,ro=ii;ro&&ro.prototype;Fm({target:"Promise",proto:!0,forced:Hm,real:!0},{catch:function(i){return this.then(void 0,i)}});var Gm=et,Ym=qe,qm=Nt,jm=si,zm=_a,Wm=$a,Qm=Yd;Gm({target:"Promise",stat:!0,forced:Qm},{race:function(e){var t=this,s=jm.f(t),r=s.reject,a=zm(function(){var n=qm(t.resolve);Wm(e,function(o){Ym(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Jm=et,Km=qe,Xm=si,Zm=Oi.CONSTRUCTOR;Jm({target:"Promise",stat:!0,forced:Zm},{reject:function(e){var t=Xm.f(this);return Km(t.reject,void 0,e),t.promise}});var eS=yt,tS=bt,iS=si,qd=function(i,e){if(eS(i),tS(e)&&e.constructor===i)return e;var t=iS.f(i),s=t.resolve;return s(e),t.promise},sS=et,rS=xt,aS=Yo,nS=ii,oS=Oi.CONSTRUCTOR,dS=qd,uS=rS("Promise"),cS=!oS;sS({target:"Promise",stat:!0,forced:aS},{resolve:function(e){return dS(cS&&this===uS?nS:this,e)}});var lS=et,ia=ii,hS=Ue,fS=xt,pS=Te,vS=Ed,ao=qd,mS=ia&&ia.prototype,SS=!!ia&&hS(function(){mS.finally.call({then:function(){}},function(){})});lS({target:"Promise",proto:!0,real:!0,forced:SS},{finally:function(i){var e=vS(this,fS("Promise")),t=pS(i);return this.then(t?function(s){return ao(e,i()).then(function(){return s})}:i,t?function(s){return ao(e,i()).then(function(){throw s})}:i)}});var gS=xt,jd=gS,bS=jd,yS=bS("Promise","finally"),TS=yS,ES=TS,$S=ES,AS=$S,xs=AS,Jt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Jt||(Jt={}));var Kt=(i,e=0,t=Jt.OFFSET_P)=>{switch(t){case Jt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Jt.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:L(t)}return i},R=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)},ne;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(ne||(ne={}));const Ye={[ne.Q_144P]:{width:256,height:144},[ne.Q_240P]:{width:428,height:240},[ne.Q_360P]:{width:640,height:360},[ne.Q_480P]:{width:856,height:480},[ne.Q_720P]:{width:1280,height:720},[ne.Q_1080P]:{width:1920,height:1080},[ne.Q_1440P]:{width:2560,height:1440},[ne.Q_2160P]:{width:3840,height:2160},[ne.Q_4320P]:{width:7680,height:4320}},hs=(i,e)=>Ye[i].height>Ye[e].height,wS=(i,e)=>Ye[i].height>=Ye[e].height,Ei=(i,e)=>Ye[i].height<Ye[e].height,_S=(i,e)=>Ye[i].height<=Ye[e].height,kS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:Ei(e,t)?1:-1)[0],PS=Object.keys(Ye).sort((i,e)=>Ei(i,e)?-1:1),Bt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return PS.find(r=>{const a=Ye[r];return a.width>=s&&a.height>=t})},RS=i=>Ye[i].height,bs=i=>i===ne.INVARIANT;class ue{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,s=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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===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:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const IS=i=>{switch(i){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.HLS_LIVE:case T.DASH_LIVE:case T.DASH_LIVE_WEBM:case T.WEB_RTC_LIVE:return!0;default:return L(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const DS=5,CS=5,OS=500,no=7e3;class LS{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===v.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==v.PAUSED&&o.state===F.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case v.READY:{switch(s){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}case v.PLAYING:{switch(s){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}case v.PAUSED:{switch(s){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}default:L(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(IS(e.format)),this.params.output.isAudioTracksExist$.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 se;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(Ge(OS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(G(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===F.Applying||Math.abs(o-a)>DS)&&r.next(o),a=o})),e.add(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(G(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<CS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,v.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:L(n)}}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=x(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));t(s,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(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:F.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s: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:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case T.MPEG:{const c=s[e];P(c);const l=kS(Object.keys(c));P(l);const h=c[l];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case T.HLS:case T.HLS_ONDEMAND:{const c=s[e];P(c),r=c.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 c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case T.HLS_LIVE:{const c=s[e];P(c),r=Kt(c.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 c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:O.VIDEO_PIPELINE,message:c,thrown:l}),l}case T.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return L(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 s=this.params.desiredState.seekState.getState();return s.state===F.Applying||s.state===F.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Iu(no).subscribe(()=>a(`timeout(${no})`)))});xs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===F.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:O.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function ce(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(c){try{d(s.next(c))}catch(l){n(l)}}function u(c){try{d(s.throw(c))}catch(l){n(l)}}function d(c){c.done?a(c.value):r(c.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function He(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,p){a.push([h,f,m,p])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(m){l(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,c):l(a[0][2],h)}function d(h){o("next",h)}function c(h){o("throw",h)}function l(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}class oo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[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 zd extends oo{constructor(){super(),this.listeners||oo.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 Wd=class{constructor(){Object.defineProperty(this,"signal",{value:new zd,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 s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Wd.prototype[Symbol.toStringTag]="AbortController",zd.prototype[Symbol.toStringTag]="AbortSignal");function Qd(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function xS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Qd({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,c){let l;c&&c.signal&&(l=c.signal,delete c.signal);const h=new t(d,c);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const c=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(c){let l;try{l=new DOMException("Aborted","AbortError")}catch(f){l=new Error("Aborted"),l.name="AbortError"}if(c.aborted)return Promise.reject(l);const h=new Promise((f,m)=>{c.addEventListener("abort",()=>m(l),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Ns=Qd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jd=Ns?xS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xt=Ns?Jd.fetch:window.fetch;Ns?Jd.Request:window.Request;const It=Ns?Wd:window.AbortController,mi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class $i{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return ce(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=mi(r.request);if(a>=s.from&&n<=s.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:s}=e,r=((t=this.dashJsRequestQueue.get(s.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(s.url);r&&a&&a.abortController.abort()}else for(const{abortController:s}of this.activeRequests.values())s.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(mi),r=s[0][0];let a=s[0][1];for(let h=1;h<s.length&&a<this.params.minDataSize;h++){const f=s[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(),u=new It,d=u.signal,c={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(c));const l=h=>{var f,m;throw(m=(f=this.params).onError)===null||m===void 0||m.call(f,{id:"BigRequestParsing",category:O.PARSER,message:"Error parsing response data",thrown:h}),h};return Xt(o,{signal:d}).then(h=>{var f,m,p;if(c.response=h,!h.ok||!h.body){this.onBigRequestError(c);return}const[S,g]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,g);const y=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;c.data=new ArrayBuffer(I);const w=new Uint8Array(c.data),A=({done:N,value:X})=>ce(this,void 0,void 0,function*(){N?this.onBigRequestProgress(c):X&&(w.set(X,c.loaded),c.loaded+=X.byteLength,this.onBigRequestProgress(c),yield y==null?void 0:y.read().then(A,$i.suppressStreamErrors).catch(l))});y==null||y.read().then(A,$i.suppressStreamErrors).catch(l)},$i.suppressAbort).catch(h=>this.onBigRequestError(c,h)),c}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,c,l,h,f,m;if(!this.activeRequests.has(e)||!a)return;const p=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of p){const{request:g}=S,[y,I]=mi(g),w=y>=t&&I<=t+r,A=t>=y&&t+r<I,N=a.slice(y-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=s-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(Y=>Y!==S)),(l=S.success)===null||l===void 0||l.call(S,N,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,U])=>`${Y}: ${U}`).join(`\r
|
|
7
|
-
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,X,[])}else A&&((m=S.progress)===null||m===void 0||m.call(S,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:O.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 c of d){const[l,h]=mi(c.request);(l>=t&&l<s||h>t&&h<=s)&&((u=c==null?void 0:c.error)===null||u===void 0||u.call(c,c.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:s}){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]=mi(o.request);(u>=t&&u<s||d>t&&d<=s)&&((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 ys{constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(ys.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;ys.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const NS=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new ys(r,e,s)}}),BS=(i,e)=>{const t=new $i(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return NS(n,t)}}},!0),()=>t.destroy()};var MS=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},US=i=>{const e=new b(1/0),t=new C,s=new b(void 0),r=new b(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=c=>{var l,h,f,m,p;const S=Ci(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((l=c.getResponseHeader("X-Playback-Duration"))!==null&&l!==void 0?l:"",10),w=parseInt((h=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=w!=null?w:I*1e3)!==null&&f!==void 0?f:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:wi.HTTP1,y=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(g),r.next(y)},d=c=>{c.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:c}=this,l=c.load.bind(c);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...p){return u(this),f(...p)},h.progress=function(...p){return d(this),m(...p)},o()}return l(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Zt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},VS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Zt}),!0),FS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Xe=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new se;return r&&d.add(r.subscribe(c=>{const l=i.getState();s(c,l)&&i.setState(c)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},a)),d},Mt=(i,e,t)=>Xe(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),lt=(i,e,t,s)=>Xe(e,()=>({muted:i.muted,volume:i.volume}),r=>{_(r)&&(i.muted=r.muted,i.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:s}),Tt=(i,e,t,s)=>Xe(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),HS=i=>["__",i.language,i.label].join("|"),GS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class tt{constructor(){this.available$=new C,this.current$=new b(void 0),this.error$=new C,this.subscription=new se,this.externalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:O.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Xe(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(Xe(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(Xe(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(G(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(x(G(e,"addtrack"),G(e,"removetrack"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),me((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(x(G(e,"change"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),me()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(G(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,c,l,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((l=(c=o.target)===null||c===void 0?void 0:c.cues)!==null&&l!==void 0?l:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(G(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;_(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(tt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:HS(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:s}}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(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))_(e)&&GS(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"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ht=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class Da{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 Kd=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const sa=3;class YS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<sa&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||sa))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var Xd=(i,e,t=sa)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const ft=i=>{const e=f=>G(i,f).pipe(Ct(void 0)),s=x(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(f=>G(i,f))).pipe($(f=>f.type==="ended"?i.readyState<2:i.readyState<3),me()),r=x(G(i,"progress"),G(i,"timeupdate")).pipe($(()=>Xd(i.buffered,i.currentTime))),a=Kd()?nt({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Ct(void 0)):e("playing"),n=G(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),o=G(i,"ratechange").pipe($(()=>i.playbackRate)),u=G(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var f;const m=i.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:O.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:(f=i.error)!==null&&f!==void 0?f:void 0}})),d=G(i,"timeupdate").pipe($(()=>i.currentTime)),c=new C,l=.3;let h;return d.subscribe(f=>{i.loop&&_(h)&&_(f)&&h>=i.duration-l&&f<=l&&c.next(h),h=f}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:G(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:n,playbackRateState$:o}},Ca=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var qS=et,jS=la,zS=ga,WS=Sa;qS({target:"Array",proto:!0},{at:function(e){var t=jS(this),s=zS(t),r=WS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var QS=jd,JS=QS("Array","at"),KS=JS,XS=KS,ZS=XS,eg=ZS,st=eg;let Oa=!1,rt={};const tg=i=>{Oa=i},ig=()=>{rt={}},sg=i=>{i(rt)},es=(i,e)=>{var t;Oa&&(rt.meta=(t=rt.meta)!==null&&t!==void 0?t:{},rt.meta[i]=e)};class Ke{constructor(e){this.name=e}next(e){var t,s;if(!Oa)return;rt.series=(t=rt.series)!==null&&t!==void 0?t:{};const r=(s=rt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),rt.series[this.name]=r}}const rg=new Ke("best_bitrate"),ag=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class ng{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const xi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var c,l,h,f;const m=s.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},S=p&&Bt(p),g=s.considerPlaybackRate&&_(o)?o:1,y=i.filter(V=>!bs(V.quality)).sort((V,B)=>hs(V.quality,B.quality)?-1:1),I=(l=st(y,-1))===null||l===void 0?void 0:l.quality,w=(h=st(y,0))===null||h===void 0?void 0:h.quality,A=K(r)||_(r.min)&&_(r.max)&&Ei(r.max,r.min)||_(r.min)&&w&&hs(r.min,w)||_(r.max)&&I&&Ei(r.max,I),N=g*ag(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=y.filter(V=>{const B=S?Ei(V.quality,S):!0,ie=_(t)&&isFinite(t)&&_(V.bitrate)?t-a>=V.bitrate*N:!0,le=s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!bs(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&hs(V.quality,u.quality),Se=A||(K(r.max)||_S(V.quality,r.max))&&(K(r.min)||wS(V.quality,r.min));return B&&ie&&!le&&Se})[0];Y&&Y.bitrate&&rg.next(Y.bitrate);const U=(f=Y!=null?Y:y[Math.ceil((y.length-1)/2)])!==null&&f!==void 0?f:i[0],Z=U&&d&&d.history[U.id]&&pe()-d.history[U.id]<=s.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!Z&&d.recordSelection(U),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(U),U};var Pe=i=>new URL(i).hostname;const og=300,Ts=(i,e=og)=>new Pi(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Ou(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(i),()=>a.disconnect()}),dg=5e3,Si={};var z;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const be=(i,e)=>new Pi(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class ug{constructor(e){this.subscription=new se,this.videoState=new ue(z.DOWNLOADING_LIB),this.textTracksManager=new tt,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new b(void 0),this.maxSeekBackTime$=new b(1/0),this.availableFrom$=new b(void 0),this.elementSize$=new b(void 0),this.liveOffset=new Da,this.syncPlayback=()=>{const t=this.videoState.getState(),s=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)!==v.PAUSED&&a.state===F.Requested&&t!==z.STOPPED&&s!==v.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case v.STOPPED:{switch(t){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:L(t)}break}case v.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:L(t)}break}case v.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:L(t)}break}case v.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,v.PAUSED);break;case z.STOPPED:this.prepare();break;default:L(t)}break}default:L(s)}},this.video=ht(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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(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:O.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},s=window.setTimeout(()=>t("timeout"),dg);xs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Si.MediaPlayer=r.MediaPlayer,Si.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),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?Ca(t.frameRate+""):void 0),!0)),(this.params.format===T.DASH_WEBM||this.params.format===T.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=BS(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&&FS(this.player),MS(this.player),this.params.tuning.requestQuick&&VS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=p=>{e.error$.next({id:"DashIFProvider",category:O.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,s));r(Ts(this.video),this.elementSize$),r(be(this.player,"error").pipe($(p=>{const S=typeof p.error=="object"?p.error.code:p.error,g=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(be(this.player,"playbackError").pipe($(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(j(({mediaType:p})=>p==="video"),$(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===p))===null||S===void 0?void 0:S.track}));a.pipe(j(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:p})=>p===z.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(Xe(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===g))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(K(p))return;const g=(S=this.videoTracks.find(({track:y})=>y.id===p))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(p=>p==null?void 0:p.id)),onError:s}))},s)),this.subscription.add(Xe(t.autoVideoTrackSwitching,()=>{var p,S,g;return(g=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(j(({mediaType:p})=>p==="video"),$(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var g,y;const I=this.player.getDashMetrics(),w=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:wi.HTTP1,N=(y={1:!0,0:!1}[w])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Pe(S))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(p),this.videoTracks=[];const y=this.player.getQualityFor("video");let I;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),N=Bt(w),X=w.bitrate/1e3,Y={width:w.width,height:w.height},U=this.frameRatesByFrameHeight[w.height];if(N){const Z={id:A,quality:N,bitrate:X,size:Y,fps:U};this.videoTracks.push({track:Z,bitrateInfo:w}),w.qualityIndex===y&&(I=Z)}}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(be(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),g=p.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 p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=xi(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:y})=>y===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(nt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(_))}).pipe(j(({isLive:p})=>p),$(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe($(({time:p})=>p!=null?p:0));r(nt({availableFrom:this.availableFrom$.pipe(j(_)),currentTime:n}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),r(n.pipe(j(()=>this.isLive$.getValue()===!1)),e.position$),r(be(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(be(this.player,"playbackEnded"),e.endedEvent$),r(be(this.player,"playbackProgress").pipe($(()=>Xd(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),R(t.playbackState,v.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),R(t.playbackState,v.PAUSED)}),r(be(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(Ts(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:c,connectionReused$:l}=US(this.player);r(c,this.params.output.httpConnectionType$),r(l,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ye()),e.firstBytesEvent$),r(be(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(nt({isLive:this.isLive$,isShort:e.duration$.pipe($(p=>p<60))}),({isLive:p,isShort:S})=>{const g=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(j(p=>p>this.params.tuning.insufficientBufferRuleMargin),ye()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(be(this.player,"manifestLoaded").pipe(ye()).subscribe(()=>{this.subscription.add(be(this.player,"playbackPlaying").pipe(ye(),Ct(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Mt(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m}=ft(this.video);this.subscription.add(lt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Tt(this.video,t.playbackRate,m,s))}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,v.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Kt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Jt.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(s){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ni=i=>{switch(i){case"mobile":return ne.Q_144P;case"lowest":return ne.Q_240P;case"low":return ne.Q_360P;case"sd":case"medium":return ne.Q_480P;case"hd":case"high":return ne.Q_720P;case"fullhd":case"full":return ne.Q_1080P;case"quadhd":case"quad":return ne.Q_1440P;case"ultrahd":case"ultra":return ne.Q_2160P}},Et=i=>ce(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return i.muted=!1,console.warn(s),!1}}return!0});function Ae(){return pe()}function Zd(i){return Ae()-i}function uo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.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 cg(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function fs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,c,l,h=!1,f="arraybuffer",m=7e3,p=2e3,S=()=>{if(u)return;P(c);const B=Zd(c);let ie;if(B<p){ie=p-B,setTimeout(S,ie);return}p*=2,p>m&&(p=m),n&&n.abort(),n=new r,N()};const g=B=>(a=B,V),y=B=>(l=B,V),I=()=>(f="json",V),w=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,l&&l(),t&&t()}},A=B=>(h=B,V),N=()=>{c=Ae(),n=new r,n.open("get",i);let B=0,ie,le=0;const Se=()=>(P(c),Math.max(c,Math.max(ie||0,le||0)));if(a&&n.addEventListener("progress",k=>{const H=Ae();a.updateChunk&&k.loaded>B&&(a.updateChunk(Se(),k.loaded-B),B=k.loaded,ie=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(Se(),H)}l&&l(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Ae(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),V},V={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,V),withRetryInterval:(B,ie)=>(_(B)&&(p=B),_(ie)&&(m=ie),V),withTimeout:B=>(o=B,V),withFinally:y,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return V}const lg=100,hg=2e3,fg=500;let pg=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,s){return{start:e,end:t,bytes:s}}_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-fg;if(t-e>hg){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=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;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/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(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>lg&&(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 vg{constructor(e,t,s,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=s,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 s=Ae(),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=Ae()-s,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=fs(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=Ae()}_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=Ae();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,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}`),s(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=s,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 ts=1e4,is=3,mg=300,Sg=2e3,gg=6e4,bg=10,yg=1,Tg=500;class Eg{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 pg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=uo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=uo(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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 s;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,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):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}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:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("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=()=>{cg(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 vg(is,ts,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,c=!1;const l=()=>{const w=a&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=fs(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(ts).withBitrateReporting(this.bitrateSwitcher).withRetryCount(is).withFinally(()=>{u=null}).send()},f=(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()},m=w=>{const A=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),s.playbackRate=w)},p=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const N=Ae()-1e4;let X=0;for(let U=0;U<this.bufferStates.length;U++){const Z=this.bufferStates[U];w=Math.min(w,Z.buf),Z.ts<N&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${w} drop=${X} jitter=${this.sourceJitter}`);let Y=w-yg;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?m(1.15):Y>1?m(1.1):Y>.3?m(1.05):m(1)}},g=w=>{let A;const N=()=>A&&A.start?A.start.length:0,X=k=>A.start[k]/1e3,Y=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,Z=(k,H)=>({chunkIdx:U(k),startTS:X(k),dur:Y(k),discontinuity:H}),V=()=>{let k=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=H;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(ve-=A.dur[ge],!(ve<=0));--ge);k=Math.min(ge,A.dur.length-1-oe),k=Math.max(k,0)}return Z(k,!0)},B=k=>{const H=N();if(!(H<=0)){if(_(k)){for(let oe=0;oe<H;oe++)if(X(oe)>k)return Z(oe)}return V()}},ie=k=>{const H=N(),oe=k?k.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(H<=0)){if(!k||ve<0||ve-H>bg)return t(`Resync: offset=${ve} bChunks=${H} chunk=`+JSON.stringify(k)),V();if(!(ve>=H))return Z(oe-A.fragIndex,!1)}},le=(k,H,oe)=>{d&&d.abort(),d=fs(this.urlResolver.resolve(k,!0,this.lowLatency),H,oe,()=>this._retryCallback()).withTimeout(ts).withRetryCount(is).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{le(w,oe=>{if(!l())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&p(ve);let ge=0;for(let Re=0;Re<A.dur.length;++Re)ge+=A.dur[Re];ge>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ge/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:ie}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{const{videoElement:A,logger:N}=this.params;let X=g(e.jidxUrl),Y,U,Z,V,B=0,ie,le,Se;const k=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(Tg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+ee,ke=Ae(),Le=Math.min(1e4,Ee-ke);B=ke;const $t=()=>{d||l()&&X.seek(()=>{l()&&(B=Ae(),H(),k())})};Le>0?ie=window.setTimeout(()=>{this.paused?k():$t()},Le):$t()},H=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,je(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(y(),this._initPlayerWith(e));return}Re(Ee)}else k()},oe=(ee,Ee)=>{if(!l()||!this.sourceBuffer)return;let ke,Le,$t;const ze=pt=>{window.setTimeout(()=>{l()&&oe(ee,Ee)},pt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),ze(100);else{const pt=Ae(),At=A.currentTime;!this.paused&&A.buffered.length>1&&le===At&&pt-Se>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),le!==At&&(le=At,Se=pt);const ai=this._getBufferSizeSec();if(ai>30)N(`Buffered ${ai} seconds; delaying appendBuffer`),ze(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:pt,buf:ai}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ut){if(Ut.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),$t=this.sourceBuffer.buffered.length,$t!==0&&(ke=this.sourceBuffer.buffered.start(0),Le=At,Le-ke>4&&this.sourceBuffer.remove(ke,Le-3)),ze(1e3);else throw Ut}}},ve=()=>{U&&Y&&(N([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Z)]),oe(U,function(){U=null,H()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Re=ee=>{l()&&f(ge(ee),(Ee,ke)=>{if(l()){if(ke/=1e3,U=Ee,Z=ee,n=ee.startTS,ke){const Le=Math.min(10,ee.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}ve()}},()=>this._handleNetworkError())},je=ee=>{l()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},ri=ee=>{l()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(l()){if(B=Ae(),!ee){k();return}V=ee,!K(w)||ee.startTS>w?Re(ee):(Z=ee,H())}},w),e.cachedHeader?ri(e.cachedHeader):h(e.headerUrl,ri,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){const{logger:t,playerCallback:s}=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),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=l=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),m=l/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,f)=>{const m=Ae();if(this.chunkRateEstimator.addInterval(h,m,f)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-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 l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Zd(n)<3e4)return;s(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{const f=a.updateChunk(l,h);return f&&d(),f},notifySwitch:l=>{const h=Ae();l<o&&(n=h),o=l}}}_fetchManifest(e,t,s){this.manifestRequest=fs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ts).withRetryCount(is).withRetryInterval(mg,Sg).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Et(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,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}`),s({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))},gg))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var W;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const $g=[W.PAUSED,W.PLAYING,W.READY],Ag=[W.PAUSED,W.PLAYING,W.READY];class wg{constructor(e){this.subscription=new se,this.videoState=new ue(W.STOPPED),this.representations$=new b([]),this.textTracksManager=new tt,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Da,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:O.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,c=[];for(const l of d){const h=(a=l.name)!==null&&a!==void 0?a:l.index.toString(10),f=(n=Ni(l.name))!==null&&n!==void 0?n:Bt(l.video),m=l.bitrate/1e3,p=Object.assign({},l.video);if(!f)continue;const S={id:h,quality:f,bitrate:m,size:p};c.push({track:S,representation:l})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:l})=>l)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,c=(u=this.representations$.getValue().find(({representation:l})=>l===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:d,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,c);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===v.STOPPED){a!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(W.STOPPED));return}if(!n){if(Ag.includes(a)){const c=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;_(c)&&this.setVideoTrack(c);const l=this.params.desiredState.autoVideoTrackSwitching.getTransition();l&&this.setAutoQuality(l.to)}if((u==null?void 0:u.to)!==v.PAUSED&&d.state===F.Requested&&$g.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(Kt(this.params.source.url));return;case W.MANIFEST_READY:this.videoState.startTransitionTo(W.READY),this.prepare();break;case W.READY:if(o===v.PAUSED)this.videoState.setState(W.PAUSED);else if(o===v.PLAYING){this.videoState.startTransitionTo(W.PLAYING);const c=u==null?void 0:u.from;c&&c===v.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)})}return;case W.PLAYING:o===v.PAUSED&&(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case W.PAUSED:o===v.PLAYING&&(this.videoState.startTransitionTo(W.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(W.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return L(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.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=ht(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=ft(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===W.READY&&this.videoState.setState(W.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===F.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(W.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(nt({zeroTime:this.zeroTime$.pipe(j(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Mt(this.video,this.params.desiredState.isLooped,t)).add(lt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Tt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&RS(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case W.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(v.STOPPED);break;case W.MANIFEST_READY:case W.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===v.READY&&this.params.desiredState.playbackState.setState(v.READY);break;case W.PAUSED:this.params.desiredState.playbackState.setState(v.PAUSED);break;case W.PLAYING:this.params.desiredState.playbackState.setState(v.PLAYING);break;default:return L(r.to)}},t)).add(x(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Eg({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,s,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=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!d&&_(u)?u:(a=xi(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,l=(n=o.find(({track:h})=>h.id===c))===null||n===void 0?void 0:n.representation;P(l,"Representations missing"),this.dash.startPlay(l,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.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,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(Kt(this.params.source.url,s))}}var eu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?wi.HTTP1:(e=s)!==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}},Rt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const _g=i=>{const e=document.createElement("a");return e.href=i,e.origin},kg=i=>{const e=document.createElement("a");return e.href=i,e.host};class tu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,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,s,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.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 c=Ci(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(l=>l.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(c))}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(c){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.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(kg(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 Es{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(s){if(s.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",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let c=0,l=0,h=0;const f=p=>{r(Es._str2ua(p.substr(u))),u=p.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Zt(m)),this._lastXhr=new tu(m,e.failoverHosts,p=>{this._lastXhr=void 0,f(p);const S=Date.now()-d;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),a==null||a()},p=>{if(p.length-u>o&&f(p),l===0){l=Date.now();return}h=p.length-c;const S=Date.now()-l;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,c=p.length,l=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},n,(p,S,g)=>this._params.onError(p,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(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=Es._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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 Pg{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)?)?$/,s=(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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Zt(s)),new tu(s,t,r=>{this.attachManifest(r,t,_g(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,c)=>{const l=d.attributes.getNamedItem(c);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var c,l,h,f,m,p,S,g,y,I,w,A,N,X,Y,U,Z,V,B;const ie=d.getElementsByTagName("SegmentBase")[0],le=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],k=Se&&n(Se,"range").split("-");if(!k||!le){const je=d.parentElement;if((je==null?void 0:je.getAttribute("contentType"))==="text"){const ri=(c=d.getAttribute("id"))!==null&&c!==void 0?c:void 0,ee=(s?s+"/":"")+((m=(f=(h=(l=d.getElementsByTagName("BaseURL"))===null||l===void 0?void 0:l[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ee=(p=je.getAttribute("lang"))!==null&&p!==void 0?p:void 0;ee&&u.push({id:ri,url:ee,language:Ee})}return}const H=.1,oe=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ve=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ge;const Re=(y=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&y!==void 0?y:void 0;ge=Re?Ca(Re):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:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(le[0]),indexTo:Number(le[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:(Y=(X=d.attributes.getNamedItem("mimeType"))===null||X===void 0?void 0:X.value)!==null&&Y!==void 0?Y:void 0,fps:ge,bufferSize:H*oe/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:(B=(V=d.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.value)!==null&&B!==void 0?B:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:c,url:l})=>{const h=document.createElement("track");h.setAttribute("src",l),d&&h.setAttribute("id",d),c&&h.setAttribute("srclang",c),this._video.appendChild(h)}),this._representations.sort((d,c)=>c.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 s=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 c=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<c;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},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 s=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 c=this._appendVector[String(d.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let l;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}l=f.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},l*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=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Es({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.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||K(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Q;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const Rg=[Q.PAUSED,Q.PLAYING];class Ig{constructor(e){this.videoState=new ue(Q.STOPPED),this.subscription=new se,this.representations$=new b([]),this.currentRepresentation$=new b(void 0),this.textTracksManager=new tt,this.elementSize$=new b(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var s,r,a;const n=[];for(const o of t){const u=(r=(s=o.name)!==null&&s!==void 0?s:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&Ni(o.name))!==null&&a!==void 0?a:Bt(o),c=o.bandwidth/1e3,l={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:c,size:l,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(Q.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.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(),s=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(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===v.STOPPED){t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.dash.destroy(),this.video.setAttribute("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(Q.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==v.PAUSED&&n.state===F.Requested&&Rg.includes(t)&&this.seek(n.position,n.forcePrecise),t){case Q.STOPPED:this.videoState.startTransitionTo(Q.MANIFEST_LOADED),this.prepare();return;case Q.MANIFEST_LOADED:this.videoState.startTransitionTo(Q.INITIAL_REPRESENTATION_SELECTED);return;case Q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Q.METADATA_LOADED:this.videoState.startTransitionTo(Q.READY),this.dash.updateRefsForCurrentTime();return;case Q.READY:r===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case Q.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(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:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=ht(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.isAudioTracksExist$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new YS(this.video),this.dash=new Pg({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,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:O.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,s=o=>{e.error$.next({id:"DashProvider",category:O.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=ft(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));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$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==F.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(lt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(Ts(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Q.READY&&this.videoState.setState(Q.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:O.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$,G(this.video,"progress")).pipe($(()=>{var o,u,d;const c=this.currentRepresentation$.getValue(),l=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(f))g=f;else{const y=Rt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(y/I,1);g=(u=xi(l.map(({track:A})=>A),{container:p,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=l.find(({representation:A})=>A===c))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=l.find(({track:y})=>y.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(nt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j(_))}).pipe(ye()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j(_),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Rt(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(Pe(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=eu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),Ct(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(j(_)).subscribe(this.handleRepresentationPlay,s)).add(x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 L(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}var Ne;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Ne||(Ne={}));var $s;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})($s||($s={}));var Be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Be||(Be={}));var te;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(te||(te={}));var ei;(function(i){i.MP4="mp4",i.WEBM="webm"})(ei||(ei={}));var ra=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Dg=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Cg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",co=Cg?Dg:window.requestIdleCallback;var Tr,Er;let iu=!1;try{iu=Kd()&&parseInt((Er=(Tr=navigator.userAgent.match(/Version\/(\d+)/))===null||Tr===void 0?void 0:Tr[1])!==null&&Er!==void 0?Er:"",10)<16}catch(i){console.error(i)}class Og{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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:O.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ce(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ce(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ce(this,void 0,void 0,function*(){return new Promise(t=>{let s;iu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"&&s==="remove"||this.error$.next({id:`BufferTaskQueue:${s}`,category:O.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:L(t)}}}var lo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const su=new TextDecoder("ascii"),ru=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=su.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,i.byteLength)-e,n=new DataView(i.buffer,i.byteOffset+e,a);return{id:r,size:t,contents:n}},Lg=i=>su.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",xg=(i,e,t)=>{const s=ru(i),r=[];let a=0;const n=()=>{const p=s.contents.getUint32(a);return a+=4,p};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),c=n(),l=n(),h=n()&4294967295;let f=c/d*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+l;for(let p=0;p<h;p++){const S=n(),g=S>>>31,y=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const w=I/d*1e3;r.push({status:te.NONE,time:{from:f,to:f+w},byte:{from:m,to:m+y-1}}),f+=w,m+=y}return r},Ng=i=>{let e=0,t=!1,s=!1;for(;e<=i.byteLength&&!t;){const r=new DataView(i.buffer,i.byteOffset+e);try{const a=ru(r);if(s||(s=a.id==="mdat"),e+a.size<=i.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=i.byteLength&&s?new DataView(i.buffer,i.byteOffset,e):null},Bg={validateData:Lg,parseInit:()=>null,getIndexRange:()=>{},parseSegments:xg,parseFeedableSegmentChunk:Ng};var E;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(D||(D={}));const ho={[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}},au=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=As(i,t),r=s in ho,a=r?ho[s].type:D.Binary,n=i.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(i.buffer,i.byteOffset+t+1,o-1),d=((n&255>>o)<<(o-1)*8)+As(u),c=t+o;let l;return c+d>i.byteLength?l=new DataView(i.buffer,i.byteOffset+c):l=new DataView(i.buffer,i.byteOffset+c,d),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:c,tagSize:c+d,value:l,valueSize:d}},As=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},at=(i,e)=>{switch(e){case D.SignedInteger:return i.getInt8(0);case D.UnsignedInteger:return As(i);case D.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(i);case D.UTF8:return new TextDecoder("utf-8").decode(i);case D.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case D.Master:return i;case D.Binary:return i;default:L(e)}},Bi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=au(s);if(!e(r))return;r.type===D.Master&&Bi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Mg=i=>{if(i.getUint32(0)!==E.EBML)return!1;let e,t,s;const r=au(i);return Bi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=at(o,n):a===E.DocType?t=at(o,n):a===E.DocTypeReadVersion&&(s=at(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},nu=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],Ug=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],Vg=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d;return Bi(i,({tag:c,type:l,value:h,valueSize:f})=>{if(c===E.SeekID){const m=at(h,l);d=As(m)}else c!==E.SeekPosition&&(d=void 0);return c===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):c===E.Info?a=!0:c===E.SeekHead?n=!0:c===E.TimestampScale?s=at(h,l):c===E.Duration?r=at(h,l):c===E.SeekPosition&&d===E.Cues?u=at(h,l):a&&n&&nu.includes(c)&&(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"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u}},Fg=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Hg=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Bi(i,({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=at(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=at(d,u));break;default:t&&nu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:c}=o,l=a[u+1];return{status:te.NONE,time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Gg=i=>{let e=0,t=!1;try{Bi(i,s=>s.tag===E.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Ug.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Yg={validateData:Mg,parseInit:Vg,getIndexRange:Fg,parseSegments:Hg,parseFeedableSegmentChunk:Gg};class fo{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.error$=new C,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new It,this.destroyAbortController=new It,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Fe(this.destroyAbortController.signal,function(d){return He(this,arguments,function*(){const c=this.representations.get(d);P(c,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Og(this.sourceBuffer),this.subscription.add(G(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:O.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(G(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:O.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,lo(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield M(this.loadInit(c,"high",!0));const l=this.initData.get(c.id),h=this.segments.get(c.id);if(P(l,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(l instanceof ArrayBuffer))return yield M(void 0);let f=0;for(const m of h)m.time.from-f>0&&this.gaps.push({representation:c.id,from:f,to:m.time.from}),f=m.time.to;_(c.duration)&&c.duration-f>0&&this.gaps.push({representation:c.id,from:f,to:c.duration}),yield yield M(this.sourceBufferTaskQueue.append(l,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=Fe(this.destroyAbortController.signal,function(d){return He(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const c=this.representations.get(d);P(c,`No such representation ${d}`);let l=this.initData.get(d);if(K(l)?yield yield M(this.loadInit(c,"high",!1)):l instanceof Promise&&(yield yield M(l)),l=this.initData.get(d),!l||!(l instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(l,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=s,s){case ei.MP4:this.containerParser=Bg;break;case ei.WEBM:this.containerParser=Yg;break;default:L(s)}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 It,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Rt(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&lo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Rt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const c=st(o,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&Rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=st(s,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s: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,s){const r=e.findIndex(({status:l,time:{from:h,to:f}},m)=>{const p=h<=s&&f>=s,S=h>s||p||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=s+g||f<=s+g;return(l===te.NONE||l===te.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!ra(this.sourceBuffer.buffered,s))&&S&&y});if(r===-1)return[];if(t!==Be.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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(n<=d||o<=c);l++){const h=a[l];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ce(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Be.BYTE_RANGE:{r=t.segmentReference.url,a={from:st(e,0).byte.from,to:st(e,-1).byte.to};break}case Be.TEMPLATE:{const d=st(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:L(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield Fe(u,function(){return He(this,arguments,function*(){const d=Ha(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,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,c)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,c,u)}catch(l){this.error$.next({id:"SegmentFeeding",category:O.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:u,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(d)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(s=Rt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:O.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=l=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),l.segment.status=te.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===te.FED&&m.time.from===l.segment.time.from&&m.time.to===l.segment.time.to&&(m.status=te.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const l of this.activeSegments){const{segment:h}=l,f=d===Be.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:c;if(l.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const S=f?h.byte.from-s:0,g=f?h.byte.to-s:e.byteLength,y=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&y&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(l);const w=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(l):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(l.loadedBytes=Math.min(m,r-S),l.loadedBytes>l.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),A=l.loadedBytes===m?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,l.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)l.fedBytes+=A.byteLength,l.fedBytes===m&&o(l);else{if(l.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.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 s=this.representations.get(e);s&&(this.initLoadIdleCallback=co(()=>xs(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ce(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Fe(this.destroyAbortController.signal,function(){return He(this,arguments,function*(){const o=Ha(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:O.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ce(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var c;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const l="size"in d?(c=d.size)!==null&&c!==void 0?c:0:d.byte.to-d.byte.from;r+=l};for(const d of this.segments.values())for(const c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===te.FED&&u(c)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===te.FED&&u(c)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(l)){a=c,n=l;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const l of c)l.time.from>e+d&&l.status===te.FED&&u(l)}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 s of t){let r={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.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=co(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:O.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),d=e.some(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Wt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Wt||(Wt={}));class qg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new It,this.subscription=new se,this.fetchManifest=Fe(this.abortAllController.signal,function(r){return He(this,arguments,function*(){let a=r;this.requestQuic&&(a=Zt(a));const n=yield yield M(Xt(a,{signal:this.abortAllController.signal}).catch(gi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Wt.HEADER:Wt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:c=!0}={}){var l,h,f,m;return He(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case Wt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Wt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:L(a)}this.requestQuic&&(p=Zt(p));let g=this.abortAllController.signal;if(d){const k=new It;if(this.subscription.add(x(G(this.abortAllController.signal,"abort"),G(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){gi(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){gi(H)}g=k.signal}const y=pe(),I=yield yield M(Xt(p,{priority:u,headers:S,signal:g}).catch(gi)),w=pe();if((l=this.throughputEstimator)===null||l===void 0||l.addRawRtt(w-y),!I)return yield M(null);if(!I.ok||!I.body)return yield M(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 yield M(I.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,pe()-w),o==null||o(new DataView(k),k.byteLength),yield M(k)}if(!o&&!c)return yield M(I.arrayBuffer());const[N,X]=I.body.tee(),Y=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let U=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),B=new DataView(Z);let ie=!1;const le=k=>{ie=!0,gi(k)},Se=Fe(g,function({done:k,value:H}){return He(this,arguments,function*(){if(U===0&&this.lastRequestFirstBytes$.next(pe()-y),g.aborted)return yield M(void 0);k?o==null||o(B,U):H&&(V.set(H,U),U+=H.byteLength,o==null||o(B,U),yield yield M(Y==null?void 0:Y.read().then(Se,le)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,le)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=Fe(this.abortAllController.signal,function(r,a,n){var o;return He(this,arguments,function*(){if(r.type!==Be.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let c=u,l=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(c=Math.min(f,u),l=Math.max(m,d))),c=Math.min(c,0);const p=yield yield M(this.fetch(r.url,{range:{from:c,to:l},priority:n,measureThroughput:!1}));if(!p)return yield M(null);const S=new DataView(p,u-c,d-c+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(p,y.from-c,y.to-y.from+1);else{const A=yield yield M(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!A)return yield M(null);I=new DataView(A)}const w=a.parseSegments(I,g,y);return yield M({dataView:new DataView(p),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=Fe(this.abortAllController.signal,function(r,a){return He(this,arguments,function*(){if(r.type!==Be.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=eu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ce(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:L(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const gi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},po=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},$r=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jg=(i,e)=>{var t,s,r,a,n,o,u,d,c,l,h,f,m,p,S,g,y,I,w,A,N,X,Y,U,Z,V,B,ie,le,Se,k,H,oe,ve,ge,Re,je;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},ke=ee.children[0],Le=ke.getElementsByTagName("Period")[0],$t=Le.children;let ze;const pt=ke.getAttribute("mediaPresentationDuration"),At=Le.getAttribute("duration");if(pt)ze=po(pt);else if(At){const We=po(At);_(We)&&(ze=We)}let ai=0;const Ut=(s=(t=ke.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],hu=Ut.includes($s.WEBM_AS_IN_FFMPEG)||Ut.includes($s.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const We of $t){const Mi=We.getAttribute("mimeType"),fu=We.getAttribute("codecs"),La=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:Mi==null?void 0:Mi.split("/")[0],pu=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],vu=We.querySelectorAll("Representation"),mu=We.querySelector("SegmentTemplate");if(La!=="text")for(const $e of vu){const ni=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Mi,xa=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:fu)!==null&&d!==void 0?d:"",Ui=(l=(c=$e.getAttribute("contentType"))!==null&&c!==void 0?c:ni==null?void 0:ni.split("/")[0])!==null&&l!==void 0?l:La,Su=(f=(h=We.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],gu=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Na=parseInt((p=$e.getAttribute("height"))!==null&&p!==void 0?p:"",10),Ba=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Ma=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",bu=(y=$e.getAttribute("quality"))!==null&&y!==void 0?y:void 0,yu=Ma?Ca(Ma):void 0,Tu=(I=$e.getAttribute("id"))!==null&&I!==void 0?I:(ai++).toString(10),Eu=Ui==="video"?`${Na}p`:Ui==="audio"?`${Ba}Kbps`:xa,$u=`${Tu}@${Eu}`,Au=(N=(A=(w=$e.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",Ua=new URL(Au,e).toString(),wu=[...Ut,...pu,...Su];let Ms;const _u=$e.querySelector("SegmentBase"),wt=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:mu;if(_u){const oi=(U=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&U!==void 0?U:"",[di,Vs]=oi.split("-").map(_t=>parseInt(_t,10)),ui={from:di,to:Vs},ci=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[Fs,Vi]=ci?ci.split("-").map(_t=>parseInt(_t,10)):[],li=ci?{from:Fs,to:Vi}:void 0;Ms={type:Be.BYTE_RANGE,url:Ua,initRange:ui,indexRange:li}}else if(wt){const oi={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(B=$e.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},di=parseInt((ie=wt.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),Vs=(le=wt.getAttribute("initialization"))!==null&&le!==void 0?le:"",ui=wt.getAttribute("media"),ci=(k=parseInt((Se=wt.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&k!==void 0?k:1,Fs=$r(Vs,oi);if(!ui)throw new ReferenceError("No media attribute in SegmentTemplate");const Vi=(H=wt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],li=[];if(Vi.length){let _t=ci,kt=0;for(const hi of Vi){const Vt=parseInt((oe=hi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,fi=parseInt((ve=hi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,pi=(Re=parseInt((ge=hi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Re!==void 0?Re:void 0;for(let Va=0;Va<fi+1;Va++){const ku=$r(ui,Object.assign(Object.assign({},oi),{segmentNumber:_t.toString(10),segmentTime:pi.toString(10)})),Pu=pi?pi/di:kt;kt+=Vt/di;const Ru=kt;_t++,li.push({time:{from:Pu,to:Ru},url:ku})}}}else if(_(ze)){const kt=parseInt((je=wt.getAttribute("duration"))!==null&&je!==void 0?je:"",10)/di*1e3,hi=Math.ceil(ze/kt);let Vt=0;for(let fi=1;fi<hi;fi++){const pi=$r(ui,Object.assign(Object.assign({},oi),{segmentNumber:fi.toString(10),segmentTime:Vt.toString(10)}));li.push({time:{from:Vt,to:Vt+kt},url:pi}),Vt+=kt}}Ms={type:Be.TEMPLATE,baseUrl:Ua,initUrl:Fs,segments:li}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ui||!ni)continue;const Us={video:Ne.VIDEO,audio:Ne.AUDIO,text:Ne.TEXT}[Ui];Us&&Ee[Us].push({id:$u,kind:Us,segmentReference:Ms,profiles:wu,duration:ze,bitrate:Ba,mime:ni,codecs:xa,width:gu,height:Na,fps:yu,quality:bu})}}return{duration:ze,container:hu,representations:Ee}},zg=["timeupdate","progress","play","seeked","stalled"];var xe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(xe||(xe={}));let Wg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new ue(xe.NONE),this.currentVideoRepresentation$=new b(void 0),this.error$=new C,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new It,this.initManifest=Fe(this.destroyController.signal,function(t,s){return He(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:O.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=jg(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:O.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,c,l;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((l=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||l===void 0?void 0:l.call(c,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Ci(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:O.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=Fe(this.destroyController.signal,function(t,s){return He(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(xe.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 fo(Ne.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new fo(Ne.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$,nt({allBuffersFull:a,someBufferEnded:n}).pipe(j(({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:O.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 yield M(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&&_(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(xe.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;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||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Du(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:O.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new qg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(xe.RUNNING),this.subscription.add(x(...zg.map(e=>G(this.element,e)),G(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:O.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(G(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(G(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ra(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ce(this,void 0,void 0,function*(){const s={[Ne.VIDEO]:this.videoBufferManager,[Ne.AUDIO]:this.audioBufferManager,[Ne.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,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((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),ra(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(xe.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const r of s.gaps)s.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 s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));const Qg=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ni(a):void 0)!==null&&n!==void 0?n:Bt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Jg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Kg=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=st(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:st(i,-1)};class Xg{constructor(e){this.subscription=new se,this.videoState=new ue(he.STOPPED),this.elementSize$=new b(void 0),this.textTracksManager=new tt,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ng,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===F.Requested&&(r==null?void 0:r.to)!==v.PAUSED&&t!==he.STOPPED&&s!==v.STOPPED&&this.seek(a.position,a.forcePrecise),s===v.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.player.stop(),this.video.setAttribute("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(he.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}switch(t){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:s===v.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY);return;case he.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case he.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(t)}}},this.params=e,this.video=ht(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Wg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=ft(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:O.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,c)=>this.subscription.add(d.subscribe(c,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(_),ye(),Ct(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Mt(this.video,t.isLooped,r)),this.subscription.add(lt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Tt(this.video,t.playbackRate,s.playbackRateState$,r)),a(Ts(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,v.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,v.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var c;if(d===xe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const l=this.player.getRepresentations();P(l,"Manifest not loaded or empty");const h=Array.from(l.audio).sort((p,S)=>S.bitrate-p.bitrate),f=Array.from(l.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const S=Jg(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of f){const S=Qg(p);if(S){this.videoTracks.push({track:S,representation:p});const g=!this.params.tuning.isAudioDisabled&&Kg(h,f,p);g&&this.audioRepresentations.set(p.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioTracksExist$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(c=this.audioRepresentations.get(m.id))===null||c===void 0?void 0:c.id)}else d===xe.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:O.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$,G(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!==xe.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation();if(l){this.player.switchRepresentation(Ne.VIDEO,l.id).catch(n);const h=this.audioRepresentations.get(l.id);h&&this.player.switchRepresentation(Ne.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),$(d=>{var c;return d&&((c=this.videoTracks.find(({representation:{id:l}})=>l===d))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===v.READY),me());this.subscription.add(x(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(x(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,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,c=this.params.output.currentVideoTrack$.getValue(),l=Rt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(l/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!o&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,c&&(a=(r=this.audioRepresentations.get(c.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),p=xi(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:m,forwardBufferHealth:f,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?p!=null?p:d:d!=null?d:p;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}prepare(){return ce(this,void 0,void 0,function*(){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.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}const Zg=5e3,it={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const ss=(i,e)=>new Pi(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class eb{constructor(e){this.subscription=new se,this.videoState=new ue(J.INITIALIZING),this.textTracksManager=new tt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==J.INITIALIZING)switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===F.Requested&&this.seek(a.position),s){case v.STOPPED:switch(t){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:L(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:L(t)}break;case v.PLAYING:switch(t){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:L(t)}break;case v.PAUSED:switch(t){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case J.PLAYING:this.pause();break;default:L(t)}break;default:L(s)}},this.video=ht(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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:O.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Zg);xs(import("hls.js/dist/hls.min.js").then(r=>{e||(it.Hls=r.default,it.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(it.Hls,"hls.js not loaded"),this.hls=new it.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(it.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:O.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ft(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,s));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$),this.subscription.add(Mt(this.video,e.isLooped,s)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ss(this.hls,it.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:O.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)===null||c===void 0?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),R(e.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),R(e.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(ss(this.hls,it.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((c,l)=>{var h,f;const m=l.name||l.height.toString(10),{width:p,height:S}=l,g=(f=Ni((h=l.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Bt({width:p,height:S});if(!g)return c;const y=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,I={id:m.toString(),quality:g,bitrate:l.bitrate/1e3,size:{width:p,height:S},fps:y};return this.trackLevels.set(m,{track:I,level:l}),c.push(I),c},[]))),t.availableVideoTracks$),a(ss(this.hls,it.Events.LEVEL_LOADING).pipe($(({url:d})=>Pe(d))),t.hostname$),this.subscription.add(Xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))===null||c===void 0?void 0:c.track},o=ss(this.hls,it.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Xe(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var c;if(K(d))return;const l=(c=this.trackLevels.get(d))===null||c===void 0?void 0:c.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,m=this.hls.levels[f];!m||l.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:s})),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$,Ce(["init"])).pipe(Ge(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ce(this,void 0,void 0,function*(){this.videoState.startTransitionTo(J.PLAYING),(yield Et(this.video))||(this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(J.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.setAttribute("src",""),this.video.load(),this.videoState.setState(J.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}}const vo="X-Playback-Duration";var mo=i=>ce(void 0,void 0,void 0,function*(){const e=yield Xt(i,{method:"HEAD"});return e.headers.has(vo)?parseInt(e.headers.get(vo),10):void 0});const tb=i=>{let e=null;if(i.QUALITY&&(e=Ni(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Bt({width:t,height:s})}return e!=null?e:null},ou=(i,e=i)=>ce(void 0,void 0,void 0,function*(){var t;const a=(yield(yield Xt(i)).text()).split(`
|
|
6
|
+
import{ValueSubject as b,Subject as C,Subscription as se,isNonNullable as _,ErrorCategory as O,isNullable as K,fromEvent as G,assertNever as L,merge as x,tap as Fa,map as $,observableFrom as Ce,filterChanged as me,assertNonNullable as P,debounce as Ge,timeout as Iu,combine as nt,once as ye,mapTo as Ct,filter as j,now as pe,Observable as Pi,abortable as Fe,getExponentialDelay as Ha,interval as Du,Logger as Cu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as Ub,Subject as Vb,Subscription as Fb,ValueSubject as Hb}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Ou from"lodash/debounce.js";const Lu="2.0.81",xu="@vkontakte/videoplayer-core";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var T;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(T||(T={}));var Ie;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ie||(Ie={}));var we;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(we||(we={}));var wi;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(wi||(wi={}));var F;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(F||(F={}));var Nu=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Bu{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(we.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new b(we.NOT_AVAILABLE),this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)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||Nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:O.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 s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.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();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(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),s=cast.framework.CastContext.getInstance();this.subscription.add(G(s,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=s.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 L(r.sessionState)}})).add(x(G(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Ce([s.getCastState()])).pipe(me(),$(Mu),Fa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===we.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),c=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(c)||c===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===we.CONNECTED?_(this.connection$.getValue())?we.CONNECTED:we.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=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:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:O.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Mu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return we.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return we.AVAILABLE;case cast.framework.CastState.CONNECTING:return we.CONNECTING;case cast.framework.CastState.CONNECTED:return we.CONNECTED;default:return L(i)}};var Ga=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Ue=function(i){try{return!!i()}catch(e){return!0}},Uu=Ue,ws=!Uu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Io=ws,Do=Function.prototype,Br=Do.call,Vu=Io&&Do.bind.bind(Br,Br),Ze=Io?Vu:function(i){return function(){return Br.apply(i,arguments)}},Co=Ze,Fu=Co({}.toString),Hu=Co("".slice),_s=function(i){return Hu(Fu(i),8,-1)},Gu=Ze,Yu=Ue,qu=_s,Hs=Object,ju=Gu("".split),zu=Yu(function(){return!Hs("z").propertyIsEnumerable(0)})?function(i){return qu(i)=="String"?ju(i,""):Hs(i)}:Hs,ks=function(i){return i==null},Wu=ks,Qu=TypeError,Oo=function(i){if(Wu(i))throw Qu("Can't call method on "+i);return i},Ju=zu,Ku=Oo,Ri=function(i){return Ju(Ku(i))},Xu=function(){},ti={},Fi=function(i){return i&&i.Math==Math&&i},_e=Fi(typeof globalThis=="object"&&globalThis)||Fi(typeof window=="object"&&window)||Fi(typeof self=="object"&&self)||Fi(typeof Ga=="object"&&Ga)||function(){return this}()||Function("return this")(),Mr=typeof document=="object"&&document.all,Zu=typeof Mr=="undefined"&&Mr!==void 0,Lo={all:Mr,IS_HTMLDDA:Zu},xo=Lo,ec=xo.all,Te=xo.IS_HTMLDDA?function(i){return typeof i=="function"||i===ec}:function(i){return typeof i=="function"},tc=_e,ic=Te,Ya=tc.WeakMap,sc=ic(Ya)&&/native code/.test(String(Ya)),qa=Te,No=Lo,rc=No.all,bt=No.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:qa(i)||i===rc}:function(i){return typeof i=="object"?i!==null:qa(i)},ac=Ue,ut=!ac(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Lt={},nc=_e,ja=bt,Ur=nc.document,oc=ja(Ur)&&ja(Ur.createElement),na=function(i){return oc?Ur.createElement(i):{}},dc=ut,uc=Ue,cc=na,Bo=!dc&&!uc(function(){return Object.defineProperty(cc("div"),"a",{get:function(){return 7}}).a!=7}),lc=ut,hc=Ue,Mo=lc&&hc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),fc=bt,pc=String,vc=TypeError,yt=function(i){if(fc(i))return i;throw vc(pc(i)+" is not an object")},mc=ws,Hi=Function.prototype.call,qe=mc?Hi.bind(Hi):function(){return Hi.apply(Hi,arguments)},oa={},Gs=oa,Ys=_e,Sc=Te,za=function(i){return Sc(i)?i:void 0},xt=function(i,e){return arguments.length<2?za(Gs[i])||za(Ys[i]):Gs[i]&&Gs[i][e]||Ys[i]&&Ys[i][e]},gc=Ze,da=gc({}.isPrototypeOf),Ps=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Uo=_e,qs=Ps,Wa=Uo.process,Qa=Uo.Deno,Ja=Wa&&Wa.versions||Qa&&Qa.version,Ka=Ja&&Ja.v8,Ve,ps;Ka&&(Ve=Ka.split("."),ps=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ps&&qs&&(Ve=qs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=qs.match(/Chrome\/(\d+)/),Ve&&(ps=+Ve[1])));var Vo=ps,Xa=Vo,bc=Ue,Fo=!!Object.getOwnPropertySymbols&&!bc(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Xa&&Xa<41}),yc=Fo,Ho=yc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Tc=xt,Ec=Te,$c=da,Ac=Ho,wc=Object,Go=Ac?function(i){return typeof i=="symbol"}:function(i){var e=Tc("Symbol");return Ec(e)&&$c(e.prototype,wc(i))},_c=String,Rs=function(i){try{return _c(i)}catch(e){return"Object"}},kc=Te,Pc=Rs,Rc=TypeError,Nt=function(i){if(kc(i))return i;throw Rc(Pc(i)+" is not a function")},Ic=Nt,Dc=ks,ua=function(i,e){var t=i[e];return Dc(t)?void 0:Ic(t)},js=qe,zs=Te,Ws=bt,Cc=TypeError,Oc=function(i,e){var t,s;if(e==="string"&&zs(t=i.toString)&&!Ws(s=js(t,i))||zs(t=i.valueOf)&&!Ws(s=js(t,i))||e!=="string"&&zs(t=i.toString)&&!Ws(s=js(t,i)))return s;throw Cc("Can't convert object to primitive value")},vs={},Lc={get exports(){return vs},set exports(i){vs=i}},Yo=!0,Za=_e,xc=Object.defineProperty,Nc=function(i,e){try{xc(Za,i,{value:e,configurable:!0,writable:!0})}catch(t){Za[i]=e}return e},Bc=_e,Mc=Nc,en="__core-js_shared__",Uc=Bc[en]||Mc(en,{}),ca=Uc,tn=ca;(Lc.exports=function(i,e){return tn[i]||(tn[i]=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 Vc=Oo,Fc=Object,la=function(i){return Fc(Vc(i))},Hc=Ze,Gc=la,Yc=Hc({}.hasOwnProperty),ct=Object.hasOwn||function(e,t){return Yc(Gc(e),t)},qc=Ze,jc=0,zc=Math.random(),Wc=qc(1 .toString),qo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Wc(++jc+zc,36)},Qc=_e,Jc=vs,sn=ct,Kc=qo,Xc=Fo,Zc=Ho,qt=Qc.Symbol,Qs=Jc("wks"),el=Zc?qt.for||qt:qt&&qt.withoutSetter||Kc,Oe=function(i){return sn(Qs,i)||(Qs[i]=Xc&&sn(qt,i)?qt[i]:el("Symbol."+i)),Qs[i]},tl=qe,rn=bt,an=Go,il=ua,sl=Oc,rl=Oe,al=TypeError,nl=rl("toPrimitive"),ol=function(i,e){if(!rn(i)||an(i))return i;var t=il(i,nl),s;if(t){if(e===void 0&&(e="default"),s=tl(t,i,e),!rn(s)||an(s))return s;throw al("Can't convert object to primitive value")}return e===void 0&&(e="number"),sl(i,e)},dl=ol,ul=Go,ha=function(i){var e=dl(i,"string");return ul(e)?e:e+""},cl=ut,ll=Bo,hl=Mo,Gi=yt,nn=ha,fl=TypeError,Js=Object.defineProperty,pl=Object.getOwnPropertyDescriptor,Ks="enumerable",Xs="configurable",Zs="writable";Lt.f=cl?hl?function(e,t,s){if(Gi(e),t=nn(t),Gi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Zs in s&&!s[Zs]){var r=pl(e,t);r&&r[Zs]&&(e[t]=s.value,s={configurable:Xs in s?s[Xs]:r[Xs],enumerable:Ks in s?s[Ks]:r[Ks],writable:!1})}return Js(e,t,s)}:Js:function(e,t,s){if(Gi(e),t=nn(t),Gi(s),ll)try{return Js(e,t,s)}catch(r){}if("get"in s||"set"in s)throw fl("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Is=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},vl=ut,ml=Lt,Sl=Is,Ii=vl?function(i,e,t){return ml.f(i,e,Sl(1,t))}:function(i,e,t){return i[e]=t,i},gl=vs,bl=qo,on=gl("keys"),fa=function(i){return on[i]||(on[i]=bl(i))},pa={},yl=sc,jo=_e,Tl=bt,El=Ii,er=ct,tr=ca,$l=fa,Al=pa,dn="Object already initialized",Vr=jo.TypeError,wl=jo.WeakMap,ms,_i,Ss,_l=function(i){return Ss(i)?_i(i):ms(i,{})},kl=function(i){return function(e){var t;if(!Tl(e)||(t=_i(e)).type!==i)throw Vr("Incompatible receiver, "+i+" required");return t}};if(yl||tr.state){var Qe=tr.state||(tr.state=new wl);Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,ms=function(i,e){if(Qe.has(i))throw Vr(dn);return e.facade=i,Qe.set(i,e),e},_i=function(i){return Qe.get(i)||{}},Ss=function(i){return Qe.has(i)}}else{var Ft=$l("state");Al[Ft]=!0,ms=function(i,e){if(er(i,Ft))throw Vr(dn);return e.facade=i,El(i,Ft,e),e},_i=function(i){return er(i,Ft)?i[Ft]:{}},Ss=function(i){return er(i,Ft)}}var zo={set:ms,get:_i,has:Ss,enforce:_l,getterFor:kl},Pl=ws,Wo=Function.prototype,un=Wo.apply,cn=Wo.call,Qo=typeof Reflect=="object"&&Reflect.apply||(Pl?cn.bind(un):function(){return cn.apply(un,arguments)}),Rl=_s,Il=Ze,Jo=function(i){if(Rl(i)==="Function")return Il(i)},va={},Ko={},Xo={}.propertyIsEnumerable,Zo=Object.getOwnPropertyDescriptor,Dl=Zo&&!Xo.call({1:2},1);Ko.f=Dl?function(e){var t=Zo(this,e);return!!t&&t.enumerable}:Xo;var Cl=ut,Ol=qe,Ll=Ko,xl=Is,Nl=Ri,Bl=ha,Ml=ct,Ul=Bo,ln=Object.getOwnPropertyDescriptor;va.f=Cl?ln:function(e,t){if(e=Nl(e),t=Bl(t),Ul)try{return ln(e,t)}catch(s){}if(Ml(e,t))return xl(!Ol(Ll.f,e,t),e[t])};var Vl=Ue,Fl=Te,Hl=/#|\.prototype\./,Di=function(i,e){var t=Yl[Gl(i)];return t==jl?!0:t==ql?!1:Fl(e)?Vl(e):!!e},Gl=Di.normalize=function(i){return String(i).replace(Hl,".").toLowerCase()},Yl=Di.data={},ql=Di.NATIVE="N",jl=Di.POLYFILL="P",ed=Di,hn=Jo,zl=Nt,Wl=ws,Ql=hn(hn.bind),Ds=function(i,e){return zl(i),e===void 0?i:Wl?Ql(i,e):function(){return i.apply(e,arguments)}},Yi=_e,Jl=Qo,Kl=Jo,Xl=Te,Zl=va.f,eh=ed,Ht=oa,th=Ds,Gt=Ii,fn=ct,ih=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Jl(i,this,arguments)};return e.prototype=i.prototype,e},et=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Yi:r?Yi[t]:(Yi[t]||{}).prototype,o=s?Ht:Ht[t]||Gt(Ht,t,{})[t],u=o.prototype,d,c,l,h,f,m,p,S,g;for(h in e)d=eh(s?h:t+(r?".":"#")+h,i.forced),c=!d&&n&&fn(n,h),m=o[h],c&&(i.dontCallGetSet?(g=Zl(n,h),p=g&&g.value):p=n[h]),f=c&&p?p:e[h],!(c&&typeof m==typeof f)&&(i.bind&&c?S=th(f,Yi):i.wrap&&c?S=ih(f):a&&Xl(f)?S=Kl(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&Gt(S,"sham",!0),Gt(o,h,S),a&&(l=t+"Prototype",fn(Ht,l)||Gt(Ht,l,{}),Gt(Ht[l],h,f),i.real&&u&&(d||!u[h])&&Gt(u,h,f)))},Fr=ut,sh=ct,td=Function.prototype,rh=Fr&&Object.getOwnPropertyDescriptor,ma=sh(td,"name"),ah=ma&&function(){}.name==="something",nh=ma&&(!Fr||Fr&&rh(td,"name").configurable),oh={EXISTS:ma,PROPER:ah,CONFIGURABLE:nh},id={},dh=Math.ceil,uh=Math.floor,ch=Math.trunc||function(e){var t=+e;return(t>0?uh:dh)(t)},lh=ch,Sa=function(i){var e=+i;return e!==e||e===0?0:lh(e)},hh=Sa,fh=Math.max,ph=Math.min,vh=function(i,e){var t=hh(i);return t<0?fh(t+e,0):ph(t,e)},mh=Sa,Sh=Math.min,gh=function(i){return i>0?Sh(mh(i),9007199254740991):0},bh=gh,ga=function(i){return bh(i.length)},yh=Ri,Th=vh,Eh=ga,pn=function(i){return function(e,t,s){var r=yh(e),a=Eh(r),n=Th(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},$h={includes:pn(!0),indexOf:pn(!1)},Ah=Ze,ir=ct,wh=Ri,_h=$h.indexOf,kh=pa,vn=Ah([].push),Ph=function(i,e){var t=wh(i),s=0,r=[],a;for(a in t)!ir(kh,a)&&ir(t,a)&&vn(r,a);for(;e.length>s;)ir(t,a=e[s++])&&(~_h(r,a)||vn(r,a));return r},sd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rh=Ph,Ih=sd,Dh=Object.keys||function(e){return Rh(e,Ih)},Ch=ut,Oh=Mo,Lh=Lt,xh=yt,Nh=Ri,Bh=Dh;id.f=Ch&&!Oh?Object.defineProperties:function(e,t){xh(e);for(var s=Nh(t),r=Bh(t),a=r.length,n=0,o;a>n;)Lh.f(e,o=r[n++],s[o]);return e};var Mh=xt,rd=Mh("document","documentElement"),Uh=yt,Vh=id,mn=sd,Fh=pa,Hh=rd,Gh=na,Yh=fa,Sn=">",gn="<",Hr="prototype",Gr="script",ad=Yh("IE_PROTO"),sr=function(){},nd=function(i){return gn+Gr+Sn+i+gn+"/"+Gr+Sn},bn=function(i){i.write(nd("")),i.close();var e=i.parentWindow.Object;return i=null,e},qh=function(){var i=Gh("iframe"),e="java"+Gr+":",t;return i.style.display="none",Hh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(nd("document.F=Object")),t.close(),t.F},qi,us=function(){try{qi=new ActiveXObject("htmlfile")}catch(e){}us=typeof document!="undefined"?document.domain&&qi?bn(qi):qh():bn(qi);for(var i=mn.length;i--;)delete us[Hr][mn[i]];return us()};Fh[ad]=!0;var od=Object.create||function(e,t){var s;return e!==null?(sr[Hr]=Uh(e),s=new sr,sr[Hr]=null,s[ad]=e):s=us(),t===void 0?s:Vh.f(s,t)},jh=Ue,zh=!jh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Wh=ct,Qh=Te,Jh=la,Kh=fa,Xh=zh,yn=Kh("IE_PROTO"),Yr=Object,Zh=Yr.prototype,dd=Xh?Yr.getPrototypeOf:function(i){var e=Jh(i);if(Wh(e,yn))return e[yn];var t=e.constructor;return Qh(t)&&e instanceof t?t.prototype:e instanceof Yr?Zh:null},ef=Ii,ba=function(i,e,t,s){return s&&s.enumerable?i[e]=t:ef(i,e,t),i},tf=Ue,sf=Te,rf=bt,af=od,Tn=dd,nf=ba,of=Oe,qr=of("iterator"),ud=!1,ot,rr,ar;[].keys&&(ar=[].keys(),"next"in ar?(rr=Tn(Tn(ar)),rr!==Object.prototype&&(ot=rr)):ud=!0);var df=!rf(ot)||tf(function(){var i={};return ot[qr].call(i)!==i});df?ot={}:ot=af(ot);sf(ot[qr])||nf(ot,qr,function(){return this});var cd={IteratorPrototype:ot,BUGGY_SAFARI_ITERATORS:ud},uf=Oe,cf=uf("toStringTag"),ld={};ld[cf]="z";var ya=String(ld)==="[object z]",lf=ya,hf=Te,cs=_s,ff=Oe,pf=ff("toStringTag"),vf=Object,mf=cs(function(){return arguments}())=="Arguments",Sf=function(i,e){try{return i[e]}catch(t){}},Cs=lf?cs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Sf(e=vf(i),pf))=="string"?t:mf?cs(e):(s=cs(e))=="Object"&&hf(e.callee)?"Arguments":s},gf=ya,bf=Cs,yf=gf?{}.toString:function(){return"[object "+bf(this)+"]"},Tf=ya,Ef=Lt.f,$f=Ii,Af=ct,wf=yf,_f=Oe,En=_f("toStringTag"),Ta=function(i,e,t,s){if(i){var r=t?i:i.prototype;Af(r,En)||Ef(r,En,{configurable:!0,value:e}),s&&!Tf&&$f(r,"toString",wf)}},kf=cd.IteratorPrototype,Pf=od,Rf=Is,If=Ta,Df=ti,Cf=function(){return this},Of=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Pf(kf,{next:Rf(+!s,t)}),If(i,r,!1,!0),Df[r]=Cf,i},Lf=et,xf=qe,hd=oh,Nf=Of,Bf=dd,Mf=Ta,$n=ba,Uf=Oe,An=ti,fd=cd,Vf=hd.PROPER;hd.CONFIGURABLE;fd.IteratorPrototype;var ji=fd.BUGGY_SAFARI_ITERATORS,nr=Uf("iterator"),wn="keys",zi="values",_n="entries",Ff=function(){return this},Hf=function(i,e,t,s,r,a,n){Nf(t,e,s);var o=function(g){if(g===r&&h)return h;if(!ji&&g in c)return c[g];switch(g){case wn:return function(){return new t(this,g)};case zi:return function(){return new t(this,g)};case _n:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,c=i.prototype,l=c[nr]||c["@@iterator"]||r&&c[r],h=!ji&&l||o(r),f=e=="Array"&&c.entries||l,m,p,S;if(f&&(m=Bf(f.call(new i)),m!==Object.prototype&&m.next&&(Mf(m,u,!0,!0),An[u]=Ff)),Vf&&r==zi&&l&&l.name!==zi&&(d=!0,h=function(){return xf(l,this)}),r)if(p={values:o(zi),keys:a?h:o(wn),entries:o(_n)},n)for(S in p)(ji||d||!(S in c))&&$n(c,S,p[S]);else Lf({target:e,proto:!0,forced:ji||d},p);return n&&c[nr]!==h&&$n(c,nr,h,{name:r}),An[e]=h,p},Gf=function(i,e){return{value:i,done:e}},Yf=Ri,Ea=Xu,kn=ti,pd=zo,qf=Lt.f,jf=Hf,Wi=Gf,zf=Yo,Wf=ut,vd="Array Iterator",Qf=pd.set,Jf=pd.getterFor(vd);jf(Array,"Array",function(i,e){Qf(this,{type:vd,target:Yf(i),index:0,kind:e})},function(){var i=Jf(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Wi(void 0,!0)):t=="keys"?Wi(s,!1):t=="values"?Wi(e[s],!1):Wi([s,e[s]],!1)},"values");var Pn=kn.Arguments=kn.Array;Ea();Ea();Ea();if(!zf&&Wf&&Pn.name!=="values")try{qf(Pn,"name",{value:"values"})}catch(i){}var Kf=Oe,Xf=ti,Zf=Kf("iterator"),ep=Array.prototype,tp=function(i){return i!==void 0&&(Xf.Array===i||ep[Zf]===i)},ip=Cs,Rn=ua,sp=ks,rp=ti,ap=Oe,np=ap("iterator"),md=function(i){if(!sp(i))return Rn(i,np)||Rn(i,"@@iterator")||rp[ip(i)]},op=qe,dp=Nt,up=yt,cp=Rs,lp=md,hp=TypeError,fp=function(i,e){var t=arguments.length<2?lp(i):e;if(dp(t))return up(op(t,i));throw hp(cp(i)+" is not iterable")},pp=qe,In=yt,vp=ua,mp=function(i,e,t){var s,r;In(i);try{if(s=vp(i,"return"),!s){if(e==="throw")throw t;return t}s=pp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return In(s),t},Sp=Ds,gp=qe,bp=yt,yp=Rs,Tp=tp,Ep=ga,Dn=da,$p=fp,Ap=md,Cn=mp,wp=TypeError,ls=function(i,e){this.stopped=i,this.result=e},On=ls.prototype,$a=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Sp(e,s),d,c,l,h,f,m,p,S=function(y){return d&&Cn(d,"normal",y),new ls(!0,y)},g=function(y){return r?(bp(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)d=i.iterator;else if(n)d=i;else{if(c=Ap(i),!c)throw wp(yp(i)+" is not iterable");if(Tp(c)){for(l=0,h=Ep(i);h>l;l++)if(f=g(i[l]),f&&Dn(On,f))return f;return new ls(!1)}d=$p(i,c)}for(m=a?i.next:d.next;!(p=gp(m,d)).done;){try{f=g(p.value)}catch(y){Cn(d,"throw",y)}if(typeof f=="object"&&f&&Dn(On,f))return f}return new ls(!1)},_p=ha,kp=Lt,Pp=Is,Rp=function(i,e,t){var s=_p(e);s in i?kp.f(i,s,Pp(0,t)):i[s]=t},Ip=et,Dp=$a,Cp=Rp;Ip({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Dp(e,function(s,r){Cp(t,s,r)},{AS_ENTRIES:!0}),t}});var Op=oa,Lp=Op.Object.fromEntries,xp={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},Np=xp,Bp=_e,Mp=Cs,Up=Ii,Ln=ti,Vp=Oe,xn=Vp("toStringTag");for(var or in Np){var Nn=Bp[or],dr=Nn&&Nn.prototype;dr&&Mp(dr)!==xn&&Up(dr,xn,or),Ln[or]=Ln.Array}var Fp=Lp,Hp=Fp,Gp=Hp,Yp=Gp,Ci=Yp,qp=_s,Os=typeof process!="undefined"&&qp(process)=="process",jp=xt,zp=Lt,Wp=Oe,Qp=ut,Bn=Wp("species"),Jp=function(i){var e=jp(i),t=zp.f;Qp&&e&&!e[Bn]&&t(e,Bn,{configurable:!0,get:function(){return this}})},Kp=da,Xp=TypeError,Zp=function(i,e){if(Kp(e,i))return i;throw Xp("Incorrect invocation")},ev=Ze,tv=Te,jr=ca,iv=ev(Function.toString);tv(jr.inspectSource)||(jr.inspectSource=function(i){return iv(i)});var Sd=jr.inspectSource,sv=Ze,rv=Ue,gd=Te,av=Cs,nv=xt,ov=Sd,bd=function(){},dv=[],yd=nv("Reflect","construct"),Aa=/^\s*(?:class|function)\b/,uv=sv(Aa.exec),cv=!Aa.exec(bd),vi=function(e){if(!gd(e))return!1;try{return yd(bd,dv,e),!0}catch(t){return!1}},Td=function(e){if(!gd(e))return!1;switch(av(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cv||!!uv(Aa,ov(e))}catch(t){return!0}};Td.sham=!0;var lv=!yd||rv(function(){var i;return vi(vi.call)||!vi(Object)||!vi(function(){i=!0})||i})?Td:vi,hv=lv,fv=Rs,pv=TypeError,vv=function(i){if(hv(i))return i;throw pv(fv(i)+" is not a constructor")},Mn=yt,mv=vv,Sv=ks,gv=Oe,bv=gv("species"),Ed=function(i,e){var t=Mn(i).constructor,s;return t===void 0||Sv(s=Mn(t)[bv])?e:mv(s)},yv=Ze,Tv=yv([].slice),Ev=TypeError,$v=function(i,e){if(i<e)throw Ev("Not enough arguments");return i},Av=Ps,$d=/(?:ipad|iphone|ipod).*applewebkit/i.test(Av),De=_e,wv=Qo,_v=Ds,Un=Te,kv=ct,Ad=Ue,Vn=rd,Pv=Tv,Fn=na,Rv=$v,Iv=$d,Dv=Os,zr=De.setImmediate,Wr=De.clearImmediate,Cv=De.process,ur=De.Dispatch,Ov=De.Function,Hn=De.MessageChannel,Lv=De.String,cr=0,yi={},Gn="onreadystatechange",ki,Pt,lr,hr;Ad(function(){ki=De.location});var wa=function(i){if(kv(yi,i)){var e=yi[i];delete yi[i],e()}},fr=function(i){return function(){wa(i)}},Yn=function(i){wa(i.data)},qn=function(i){De.postMessage(Lv(i),ki.protocol+"//"+ki.host)};(!zr||!Wr)&&(zr=function(e){Rv(arguments.length,1);var t=Un(e)?e:Ov(e),s=Pv(arguments,1);return yi[++cr]=function(){wv(t,void 0,s)},Pt(cr),cr},Wr=function(e){delete yi[e]},Dv?Pt=function(i){Cv.nextTick(fr(i))}:ur&&ur.now?Pt=function(i){ur.now(fr(i))}:Hn&&!Iv?(lr=new Hn,hr=lr.port2,lr.port1.onmessage=Yn,Pt=_v(hr.postMessage,hr)):De.addEventListener&&Un(De.postMessage)&&!De.importScripts&&ki&&ki.protocol!=="file:"&&!Ad(qn)?(Pt=qn,De.addEventListener("message",Yn,!1)):Gn in Fn("script")?Pt=function(i){Vn.appendChild(Fn("script"))[Gn]=function(){Vn.removeChild(this),wa(i)}}:Pt=function(i){setTimeout(fr(i),0)});var wd={set:zr,clear:Wr},_d=function(){this.head=null,this.tail=null};_d.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var kd=_d,xv=Ps,Nv=/ipad|iphone|ipod/i.test(xv)&&typeof Pebble!="undefined",Bv=Ps,Mv=/web0s(?!.*chrome)/i.test(Bv),Ot=_e,jn=Ds,Uv=va.f,pr=wd.set,Vv=kd,Fv=$d,Hv=Nv,Gv=Mv,vr=Os,zn=Ot.MutationObserver||Ot.WebKitMutationObserver,Wn=Ot.document,Qn=Ot.process,Qi=Ot.Promise,Jn=Uv(Ot,"queueMicrotask"),Qr=Jn&&Jn.value,Yt,mr,Sr,Ji,Kn;if(!Qr){var Ki=new Vv,Xi=function(){var i,e;for(vr&&(i=Qn.domain)&&i.exit();e=Ki.get();)try{e()}catch(t){throw Ki.head&&Yt(),t}i&&i.enter()};!Fv&&!vr&&!Gv&&zn&&Wn?(mr=!0,Sr=Wn.createTextNode(""),new zn(Xi).observe(Sr,{characterData:!0}),Yt=function(){Sr.data=mr=!mr}):!Hv&&Qi&&Qi.resolve?(Ji=Qi.resolve(void 0),Ji.constructor=Qi,Kn=jn(Ji.then,Ji),Yt=function(){Kn(Xi)}):vr?Yt=function(){Qn.nextTick(Xi)}:(pr=jn(pr,Ot),Yt=function(){pr(Xi)}),Qr=function(i){Ki.head||Yt(),Ki.add(i)}}var Yv=Qr,qv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},_a=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},jv=_e,ii=jv.Promise,Pd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",zv=Pd,Wv=Os,Qv=!zv&&!Wv&&typeof window=="object"&&typeof document=="object",Jv=_e,Ti=ii,Kv=Te,Xv=ed,Zv=Sd,em=Oe,tm=Qv,im=Pd,gr=Vo,Xn=Ti&&Ti.prototype,sm=em("species"),Jr=!1,Rd=Kv(Jv.PromiseRejectionEvent),rm=Xv("Promise",function(){var i=Zv(Ti),e=i!==String(Ti);if(!e&&gr===66||!(Xn.catch&&Xn.finally))return!0;if(!gr||gr<51||!/native code/.test(i)){var t=new Ti(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[sm]=s,Jr=t.then(function(){})instanceof s,!Jr)return!0}return!e&&(tm||im)&&!Rd}),Oi={CONSTRUCTOR:rm,REJECTION_EVENT:Rd,SUBCLASSING:Jr},si={},Zn=Nt,am=TypeError,nm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw am("Bad Promise constructor");e=s,t=r}),this.resolve=Zn(e),this.reject=Zn(t)};si.f=function(i){return new nm(i)};var om=et,gs=Os,gt=_e,Li=qe,dm=ba,um=Ta,cm=Jp,lm=Nt,Kr=Te,hm=bt,fm=Zp,pm=Ed,Id=wd.set,ka=Yv,vm=qv,mm=_a,Sm=kd,Dd=zo,Xr=ii,Pa=Oi,Cd=si,Ls="Promise",Od=Pa.CONSTRUCTOR,gm=Pa.REJECTION_EVENT;Pa.SUBCLASSING;var br=Dd.getterFor(Ls),bm=Dd.set,ym=Xr&&Xr.prototype,jt=Xr,yr=ym,Ld=gt.TypeError,Zr=gt.document,Ra=gt.process,ea=Cd.f,Tm=ea,Em=!!(Zr&&Zr.createEvent&>.dispatchEvent),xd="unhandledrejection",$m="rejectionhandled",eo=0,Nd=1,Am=2,Ia=1,Bd=2,Zi,to,wm,Md=function(i){var e;return hm(i)&&Kr(e=i.then)?e:!1},Ud=function(i,e){var t=e.value,s=e.state==Nd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,c;try{r?(s||(e.rejection===Bd&&km(e),e.rejection=Ia),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===i.promise?n(Ld("Promise-chain cycle")):(d=Md(u))?Li(d,u,a,n):a(u)):n(t)}catch(l){o&&!c&&o.exit(),n(l)}},Vd=function(i,e){i.notified||(i.notified=!0,ka(function(){for(var t=i.reactions,s;s=t.get();)Ud(s,i);i.notified=!1,e&&!i.rejection&&_m(i)}))},Fd=function(i,e,t){var s,r;Em?(s=Zr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),gt.dispatchEvent(s)):s={promise:e,reason:t},!gm&&(r=gt["on"+i])?r(s):i===xd&&vm("Unhandled promise rejection",t)},_m=function(i){Li(Id,gt,function(){var e=i.facade,t=i.value,s=io(i),r;if(s&&(r=mm(function(){gs?Ra.emit("unhandledRejection",t,e):Fd(xd,e,t)}),i.rejection=gs||io(i)?Bd:Ia,r.error))throw r.value})},io=function(i){return i.rejection!==Ia&&!i.parent},km=function(i){Li(Id,gt,function(){var e=i.facade;gs?Ra.emit("rejectionHandled",e):Fd($m,e,i.value)})},zt=function(i,e,t){return function(s){i(e,s,t)}},Qt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Am,Vd(i,!0))},ta=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Ld("Promise can't be resolved itself");var s=Md(e);s?ka(function(){var r={done:!1};try{Li(s,e,zt(ta,r,i),zt(Qt,r,i))}catch(a){Qt(r,a,i)}}):(i.value=e,i.state=Nd,Vd(i,!1))}catch(r){Qt({done:!1},r,i)}}};Od&&(jt=function(e){fm(this,yr),lm(e),Li(Zi,this);var t=br(this);try{e(zt(ta,t),zt(Qt,t))}catch(s){Qt(t,s)}},yr=jt.prototype,Zi=function(e){bm(this,{type:Ls,done:!1,notified:!1,parent:!1,reactions:new Sm,rejection:!1,state:eo,value:void 0})},Zi.prototype=dm(yr,"then",function(e,t){var s=br(this),r=ea(pm(this,jt));return s.parent=!0,r.ok=Kr(e)?e:!0,r.fail=Kr(t)&&t,r.domain=gs?Ra.domain:void 0,s.state==eo?s.reactions.add(r):ka(function(){Ud(r,s)}),r.promise}),to=function(){var i=new Zi,e=br(i);this.promise=i,this.resolve=zt(ta,e),this.reject=zt(Qt,e)},Cd.f=ea=function(i){return i===jt||i===wm?new to(i):Tm(i)});om({global:!0,constructor:!0,wrap:!0,forced:Od},{Promise:jt});um(jt,Ls,!1,!0);cm(Ls);var Pm=Oe,Hd=Pm("iterator"),Gd=!1;try{var Rm=0,so={next:function(){return{done:!!Rm++}},return:function(){Gd=!0}};so[Hd]=function(){return this},Array.from(so,function(){throw 2})}catch(i){}var Im=function(i,e){if(!e&&!Gd)return!1;var t=!1;try{var s={};s[Hd]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Dm=ii,Cm=Im,Om=Oi.CONSTRUCTOR,Yd=Om||!Cm(function(i){Dm.all(i).then(void 0,function(){})}),Lm=et,xm=qe,Nm=Nt,Bm=si,Mm=_a,Um=$a,Vm=Yd;Lm({target:"Promise",stat:!0,forced:Vm},{all:function(e){var t=this,s=Bm.f(t),r=s.resolve,a=s.reject,n=Mm(function(){var o=Nm(t.resolve),u=[],d=0,c=1;Um(e,function(l){var h=d++,f=!1;c++,xm(o,t,l).then(function(m){f||(f=!0,u[h]=m,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),s.promise}});var Fm=et,Hm=Oi.CONSTRUCTOR,ro=ii;ro&&ro.prototype;Fm({target:"Promise",proto:!0,forced:Hm,real:!0},{catch:function(i){return this.then(void 0,i)}});var Gm=et,Ym=qe,qm=Nt,jm=si,zm=_a,Wm=$a,Qm=Yd;Gm({target:"Promise",stat:!0,forced:Qm},{race:function(e){var t=this,s=jm.f(t),r=s.reject,a=zm(function(){var n=qm(t.resolve);Wm(e,function(o){Ym(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Jm=et,Km=qe,Xm=si,Zm=Oi.CONSTRUCTOR;Jm({target:"Promise",stat:!0,forced:Zm},{reject:function(e){var t=Xm.f(this);return Km(t.reject,void 0,e),t.promise}});var eS=yt,tS=bt,iS=si,qd=function(i,e){if(eS(i),tS(e)&&e.constructor===i)return e;var t=iS.f(i),s=t.resolve;return s(e),t.promise},sS=et,rS=xt,aS=Yo,nS=ii,oS=Oi.CONSTRUCTOR,dS=qd,uS=rS("Promise"),cS=!oS;sS({target:"Promise",stat:!0,forced:aS},{resolve:function(e){return dS(cS&&this===uS?nS:this,e)}});var lS=et,ia=ii,hS=Ue,fS=xt,pS=Te,vS=Ed,ao=qd,mS=ia&&ia.prototype,SS=!!ia&&hS(function(){mS.finally.call({then:function(){}},function(){})});lS({target:"Promise",proto:!0,real:!0,forced:SS},{finally:function(i){var e=vS(this,fS("Promise")),t=pS(i);return this.then(t?function(s){return ao(e,i()).then(function(){return s})}:i,t?function(s){return ao(e,i()).then(function(){throw s})}:i)}});var gS=xt,jd=gS,bS=jd,yS=bS("Promise","finally"),TS=yS,ES=TS,$S=ES,AS=$S,xs=AS,Jt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Jt||(Jt={}));var Kt=(i,e=0,t=Jt.OFFSET_P)=>{switch(t){case Jt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Jt.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:L(t)}return i},R=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)},ne;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(ne||(ne={}));const Ye={[ne.Q_144P]:{width:256,height:144},[ne.Q_240P]:{width:428,height:240},[ne.Q_360P]:{width:640,height:360},[ne.Q_480P]:{width:856,height:480},[ne.Q_720P]:{width:1280,height:720},[ne.Q_1080P]:{width:1920,height:1080},[ne.Q_1440P]:{width:2560,height:1440},[ne.Q_2160P]:{width:3840,height:2160},[ne.Q_4320P]:{width:7680,height:4320}},hs=(i,e)=>Ye[i].height>Ye[e].height,wS=(i,e)=>Ye[i].height>=Ye[e].height,Ei=(i,e)=>Ye[i].height<Ye[e].height,_S=(i,e)=>Ye[i].height<=Ye[e].height,kS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:Ei(e,t)?1:-1)[0],PS=Object.keys(Ye).sort((i,e)=>Ei(i,e)?-1:1),Bt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return PS.find(r=>{const a=Ye[r];return a.width>=s&&a.height>=t})},RS=i=>Ye[i].height,bs=i=>i===ne.INVARIANT;class ue{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,s=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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===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:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const IS=i=>{switch(i){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.HLS_LIVE:case T.DASH_LIVE:case T.DASH_LIVE_WEBM:case T.WEB_RTC_LIVE:return!0;default:return L(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const DS=5,CS=5,OS=500,no=7e3;class LS{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===v.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==v.PAUSED&&o.state===F.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case v.READY:{switch(s){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}case v.PLAYING:{switch(s){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}case v.PAUSED:{switch(s){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:L(s)}break}default:L(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(IS(e.format)),this.params.output.isAudioTracksExist$.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 se;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(Ge(OS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(G(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===F.Applying||Math.abs(o-a)>DS)&&r.next(o),a=o})),e.add(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(G(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<CS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,v.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:L(n)}}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=x(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));t(s,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(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:F.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s: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:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case T.MPEG:{const c=s[e];P(c);const l=kS(Object.keys(c));P(l);const h=c[l];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case T.HLS:case T.HLS_ONDEMAND:{const c=s[e];P(c),r=c.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 c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case T.HLS_LIVE:{const c=s[e];P(c),r=Kt(c.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 c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:O.VIDEO_PIPELINE,message:c,thrown:l}),l}case T.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return L(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 s=this.params.desiredState.seekState.getState();return s.state===F.Applying||s.state===F.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Iu(no).subscribe(()=>a(`timeout(${no})`)))});xs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===F.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:O.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function ce(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(c){try{d(s.next(c))}catch(l){n(l)}}function u(c){try{d(s.throw(c))}catch(l){n(l)}}function d(c){c.done?a(c.value):r(c.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function He(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,p){a.push([h,f,m,p])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(m){l(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,c):l(a[0][2],h)}function d(h){o("next",h)}function c(h){o("throw",h)}function l(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}class oo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[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 zd extends oo{constructor(){super(),this.listeners||oo.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 Wd=class{constructor(){Object.defineProperty(this,"signal",{value:new zd,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 s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Wd.prototype[Symbol.toStringTag]="AbortController",zd.prototype[Symbol.toStringTag]="AbortSignal");function Qd(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function xS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Qd({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,c){let l;c&&c.signal&&(l=c.signal,delete c.signal);const h=new t(d,c);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const c=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(c){let l;try{l=new DOMException("Aborted","AbortError")}catch(f){l=new Error("Aborted"),l.name="AbortError"}if(c.aborted)return Promise.reject(l);const h=new Promise((f,m)=>{c.addEventListener("abort",()=>m(l),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Ns=Qd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jd=Ns?xS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xt=Ns?Jd.fetch:window.fetch;Ns?Jd.Request:window.Request;const It=Ns?Wd:window.AbortController,mi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class $i{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return ce(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=mi(r.request);if(a>=s.from&&n<=s.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:s}=e,r=((t=this.dashJsRequestQueue.get(s.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(s.url);r&&a&&a.abortController.abort()}else for(const{abortController:s}of this.activeRequests.values())s.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(mi),r=s[0][0];let a=s[0][1];for(let h=1;h<s.length&&a<this.params.minDataSize;h++){const f=s[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(),u=new It,d=u.signal,c={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(c));const l=h=>{var f,m;throw(m=(f=this.params).onError)===null||m===void 0||m.call(f,{id:"BigRequestParsing",category:O.PARSER,message:"Error parsing response data",thrown:h}),h};return Xt(o,{signal:d}).then(h=>{var f,m,p;if(c.response=h,!h.ok||!h.body){this.onBigRequestError(c);return}const[S,g]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,g);const y=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;c.data=new ArrayBuffer(I);const w=new Uint8Array(c.data),A=({done:N,value:X})=>ce(this,void 0,void 0,function*(){N?this.onBigRequestProgress(c):X&&(w.set(X,c.loaded),c.loaded+=X.byteLength,this.onBigRequestProgress(c),yield y==null?void 0:y.read().then(A,$i.suppressStreamErrors).catch(l))});y==null||y.read().then(A,$i.suppressStreamErrors).catch(l)},$i.suppressAbort).catch(h=>this.onBigRequestError(c,h)),c}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,c,l,h,f,m;if(!this.activeRequests.has(e)||!a)return;const p=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of p){const{request:g}=S,[y,I]=mi(g),w=y>=t&&I<=t+r,A=t>=y&&t+r<I,N=a.slice(y-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=s-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(Y=>Y!==S)),(l=S.success)===null||l===void 0||l.call(S,N,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,U])=>`${Y}: ${U}`).join(`\r
|
|
7
|
+
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,X,[])}else A&&((m=S.progress)===null||m===void 0||m.call(S,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:O.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 c of d){const[l,h]=mi(c.request);(l>=t&&l<s||h>t&&h<=s)&&((u=c==null?void 0:c.error)===null||u===void 0||u.call(c,c.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:s}){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]=mi(o.request);(u>=t&&u<s||d>t&&d<=s)&&((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 ys{constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(ys.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;ys.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const NS=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new ys(r,e,s)}}),BS=(i,e)=>{const t=new $i(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return NS(n,t)}}},!0),()=>t.destroy()};var MS=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},US=i=>{const e=new b(1/0),t=new C,s=new b(void 0),r=new b(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=c=>{var l,h,f,m,p;const S=Ci(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((l=c.getResponseHeader("X-Playback-Duration"))!==null&&l!==void 0?l:"",10),w=parseInt((h=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=w!=null?w:I*1e3)!==null&&f!==void 0?f:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:wi.HTTP1,y=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(g),r.next(y)},d=c=>{c.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:c}=this,l=c.load.bind(c);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...p){return u(this),f(...p)},h.progress=function(...p){return d(this),m(...p)},o()}return l(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Zt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},VS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Zt}),!0),FS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Xe=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new se;return r&&d.add(r.subscribe(c=>{const l=i.getState();s(c,l)&&i.setState(c)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},a)),d},Mt=(i,e,t)=>Xe(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),lt=(i,e,t,s)=>Xe(e,()=>({muted:i.muted,volume:i.volume}),r=>{_(r)&&(i.muted=r.muted,i.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:s}),Tt=(i,e,t,s)=>Xe(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),HS=i=>["__",i.language,i.label].join("|"),GS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class tt{constructor(){this.available$=new C,this.current$=new b(void 0),this.error$=new C,this.subscription=new se,this.externalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:O.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Xe(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(Xe(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(Xe(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(G(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(x(G(e,"addtrack"),G(e,"removetrack"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),me((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(x(G(e,"change"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),me()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(G(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,c,l,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((l=(c=o.target)===null||c===void 0?void 0:c.cues)!==null&&l!==void 0?l:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(G(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;_(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(tt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:HS(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:s}}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(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))_(e)&&GS(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"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ht=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class Da{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 Kd=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const sa=3;class YS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<sa&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||sa))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var Xd=(i,e,t=sa)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const ft=i=>{const e=f=>G(i,f).pipe(Ct(void 0)),s=x(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(f=>G(i,f))).pipe($(f=>f.type==="ended"?i.readyState<2:i.readyState<3),me()),r=x(G(i,"progress"),G(i,"timeupdate")).pipe($(()=>Xd(i.buffered,i.currentTime))),a=Kd()?nt({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Ct(void 0)):e("playing"),n=G(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),o=G(i,"ratechange").pipe($(()=>i.playbackRate)),u=G(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var f;const m=i.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:O.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:(f=i.error)!==null&&f!==void 0?f:void 0}})),d=G(i,"timeupdate").pipe($(()=>i.currentTime)),c=new C,l=.3;let h;return d.subscribe(f=>{i.loop&&_(h)&&_(f)&&h>=i.duration-l&&f<=l&&c.next(h),h=f}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:G(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:n,playbackRateState$:o}},Ca=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var qS=et,jS=la,zS=ga,WS=Sa;qS({target:"Array",proto:!0},{at:function(e){var t=jS(this),s=zS(t),r=WS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var QS=jd,JS=QS("Array","at"),KS=JS,XS=KS,ZS=XS,eg=ZS,st=eg;let Oa=!1,rt={};const tg=i=>{Oa=i},ig=()=>{rt={}},sg=i=>{i(rt)},es=(i,e)=>{var t;Oa&&(rt.meta=(t=rt.meta)!==null&&t!==void 0?t:{},rt.meta[i]=e)};class Ke{constructor(e){this.name=e}next(e){var t,s;if(!Oa)return;rt.series=(t=rt.series)!==null&&t!==void 0?t:{};const r=(s=rt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),rt.series[this.name]=r}}const rg=new Ke("best_bitrate"),ag=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class ng{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const xi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var c,l,h,f;const m=s.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},S=p&&Bt(p),g=s.considerPlaybackRate&&_(o)?o:1,y=i.filter(V=>!bs(V.quality)).sort((V,B)=>hs(V.quality,B.quality)?-1:1),I=(l=st(y,-1))===null||l===void 0?void 0:l.quality,w=(h=st(y,0))===null||h===void 0?void 0:h.quality,A=K(r)||_(r.min)&&_(r.max)&&Ei(r.max,r.min)||_(r.min)&&w&&hs(r.min,w)||_(r.max)&&I&&Ei(r.max,I),N=g*ag(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=y.filter(V=>{const B=S?Ei(V.quality,S):!0,ie=_(t)&&isFinite(t)&&_(V.bitrate)?t-a>=V.bitrate*N:!0,le=s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!bs(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&hs(V.quality,u.quality),Se=A||(K(r.max)||_S(V.quality,r.max))&&(K(r.min)||wS(V.quality,r.min));return B&&ie&&!le&&Se})[0];Y&&Y.bitrate&&rg.next(Y.bitrate);const U=(f=Y!=null?Y:y[Math.ceil((y.length-1)/2)])!==null&&f!==void 0?f:i[0],Z=U&&d&&d.history[U.id]&&pe()-d.history[U.id]<=s.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!Z&&d.recordSelection(U),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(U),U};var Pe=i=>new URL(i).hostname;const og=300,Ts=(i,e=og)=>new Pi(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Ou(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(i),()=>a.disconnect()}),dg=5e3,Si={};var z;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const be=(i,e)=>new Pi(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class ug{constructor(e){this.subscription=new se,this.videoState=new ue(z.DOWNLOADING_LIB),this.textTracksManager=new tt,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new b(void 0),this.maxSeekBackTime$=new b(1/0),this.availableFrom$=new b(void 0),this.elementSize$=new b(void 0),this.liveOffset=new Da,this.syncPlayback=()=>{const t=this.videoState.getState(),s=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)!==v.PAUSED&&a.state===F.Requested&&t!==z.STOPPED&&s!==v.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case v.STOPPED:{switch(t){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:L(t)}break}case v.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:L(t)}break}case v.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:L(t)}break}case v.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,v.PAUSED);break;case z.STOPPED:this.prepare();break;default:L(t)}break}default:L(s)}},this.video=ht(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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(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:O.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},s=window.setTimeout(()=>t("timeout"),dg);xs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Si.MediaPlayer=r.MediaPlayer,Si.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),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?Ca(t.frameRate+""):void 0),!0)),(this.params.format===T.DASH_WEBM||this.params.format===T.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=BS(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&&FS(this.player),MS(this.player),this.params.tuning.requestQuick&&VS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=p=>{e.error$.next({id:"DashIFProvider",category:O.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,s));r(Ts(this.video),this.elementSize$),r(be(this.player,"error").pipe($(p=>{const S=typeof p.error=="object"?p.error.code:p.error,g=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(be(this.player,"playbackError").pipe($(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(j(({mediaType:p})=>p==="video"),$(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===p))===null||S===void 0?void 0:S.track}));a.pipe(j(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:p})=>p===z.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(Xe(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===g))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(K(p))return;const g=(S=this.videoTracks.find(({track:y})=>y.id===p))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(p=>p==null?void 0:p.id)),onError:s}))},s)),this.subscription.add(Xe(t.autoVideoTrackSwitching,()=>{var p,S,g;return(g=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(j(({mediaType:p})=>p==="video"),$(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var g,y;const I=this.player.getDashMetrics(),w=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:wi.HTTP1,N=(y={1:!0,0:!1}[w])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Pe(S))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(p),this.videoTracks=[];const y=this.player.getQualityFor("video");let I;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),N=Bt(w),X=w.bitrate/1e3,Y={width:w.width,height:w.height},U=this.frameRatesByFrameHeight[w.height];if(N){const Z={id:A,quality:N,bitrate:X,size:Y,fps:U};this.videoTracks.push({track:Z,bitrateInfo:w}),w.qualityIndex===y&&(I=Z)}}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(be(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),g=p.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 p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=xi(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:y})=>y===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(nt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(_))}).pipe(j(({isLive:p})=>p),$(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe($(({time:p})=>p!=null?p:0));r(nt({availableFrom:this.availableFrom$.pipe(j(_)),currentTime:n}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),r(n.pipe(j(()=>this.isLive$.getValue()===!1)),e.position$),r(be(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(be(this.player,"playbackEnded"),e.endedEvent$),r(be(this.player,"playbackProgress").pipe($(()=>Xd(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),R(t.playbackState,v.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),R(t.playbackState,v.PAUSED)}),r(be(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(Ts(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:c,connectionReused$:l}=US(this.player);r(c,this.params.output.httpConnectionType$),r(l,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ye()),e.firstBytesEvent$),r(be(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(nt({isLive:this.isLive$,isShort:e.duration$.pipe($(p=>p<60))}),({isLive:p,isShort:S})=>{const g=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(j(p=>p>this.params.tuning.insufficientBufferRuleMargin),ye()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(be(this.player,"manifestLoaded").pipe(ye()).subscribe(()=>{this.subscription.add(be(this.player,"playbackPlaying").pipe(ye(),Ct(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Mt(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m}=ft(this.video);this.subscription.add(lt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Tt(this.video,t.playbackRate,m,s))}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,v.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Kt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Jt.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(s){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ni=i=>{switch(i){case"mobile":return ne.Q_144P;case"lowest":return ne.Q_240P;case"low":return ne.Q_360P;case"sd":case"medium":return ne.Q_480P;case"hd":case"high":return ne.Q_720P;case"fullhd":case"full":return ne.Q_1080P;case"quadhd":case"quad":return ne.Q_1440P;case"ultrahd":case"ultra":return ne.Q_2160P}},Et=i=>ce(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return i.muted=!1,console.warn(s),!1}}return!0});function Ae(){return pe()}function Zd(i){return Ae()-i}function uo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.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 cg(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function fs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,c,l,h=!1,f="arraybuffer",m=7e3,p=2e3,S=()=>{if(u)return;P(c);const B=Zd(c);let ie;if(B<p){ie=p-B,setTimeout(S,ie);return}p*=2,p>m&&(p=m),n&&n.abort(),n=new r,N()};const g=B=>(a=B,V),y=B=>(l=B,V),I=()=>(f="json",V),w=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,l&&l(),t&&t()}},A=B=>(h=B,V),N=()=>{c=Ae(),n=new r,n.open("get",i);let B=0,ie,le=0;const Se=()=>(P(c),Math.max(c,Math.max(ie||0,le||0)));if(a&&n.addEventListener("progress",k=>{const H=Ae();a.updateChunk&&k.loaded>B&&(a.updateChunk(Se(),k.loaded-B),B=k.loaded,ie=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(Se(),H)}l&&l(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Ae(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),V},V={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,V),withRetryInterval:(B,ie)=>(_(B)&&(p=B),_(ie)&&(m=ie),V),withTimeout:B=>(o=B,V),withFinally:y,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return V}const lg=100,hg=2e3,fg=500;let pg=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,s){return{start:e,end:t,bytes:s}}_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-fg;if(t-e>hg){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=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;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/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(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>lg&&(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 vg{constructor(e,t,s,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=s,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 s=Ae(),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=Ae()-s,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=fs(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=Ae()}_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=Ae();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,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}`),s(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=s,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 ts=1e4,is=3,mg=300,Sg=2e3,gg=6e4,bg=10,yg=1,Tg=500;class Eg{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 pg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=uo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=uo(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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 s;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,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):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}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:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("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=()=>{cg(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 vg(is,ts,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,c=!1;const l=()=>{const w=a&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=fs(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(ts).withBitrateReporting(this.bitrateSwitcher).withRetryCount(is).withFinally(()=>{u=null}).send()},f=(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()},m=w=>{const A=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),s.playbackRate=w)},p=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const N=Ae()-1e4;let X=0;for(let U=0;U<this.bufferStates.length;U++){const Z=this.bufferStates[U];w=Math.min(w,Z.buf),Z.ts<N&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${w} drop=${X} jitter=${this.sourceJitter}`);let Y=w-yg;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?m(1.15):Y>1?m(1.1):Y>.3?m(1.05):m(1)}},g=w=>{let A;const N=()=>A&&A.start?A.start.length:0,X=k=>A.start[k]/1e3,Y=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,Z=(k,H)=>({chunkIdx:U(k),startTS:X(k),dur:Y(k),discontinuity:H}),V=()=>{let k=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=H;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(ve-=A.dur[ge],!(ve<=0));--ge);k=Math.min(ge,A.dur.length-1-oe),k=Math.max(k,0)}return Z(k,!0)},B=k=>{const H=N();if(!(H<=0)){if(_(k)){for(let oe=0;oe<H;oe++)if(X(oe)>k)return Z(oe)}return V()}},ie=k=>{const H=N(),oe=k?k.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(H<=0)){if(!k||ve<0||ve-H>bg)return t(`Resync: offset=${ve} bChunks=${H} chunk=`+JSON.stringify(k)),V();if(!(ve>=H))return Z(oe-A.fragIndex,!1)}},le=(k,H,oe)=>{d&&d.abort(),d=fs(this.urlResolver.resolve(k,!0,this.lowLatency),H,oe,()=>this._retryCallback()).withTimeout(ts).withRetryCount(is).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{le(w,oe=>{if(!l())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&p(ve);let ge=0;for(let Re=0;Re<A.dur.length;++Re)ge+=A.dur[Re];ge>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ge/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:ie}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{const{videoElement:A,logger:N}=this.params;let X=g(e.jidxUrl),Y,U,Z,V,B=0,ie,le,Se;const k=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(Tg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+ee,ke=Ae(),Le=Math.min(1e4,Ee-ke);B=ke;const $t=()=>{d||l()&&X.seek(()=>{l()&&(B=Ae(),H(),k())})};Le>0?ie=window.setTimeout(()=>{this.paused?k():$t()},Le):$t()},H=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,je(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(y(),this._initPlayerWith(e));return}Re(Ee)}else k()},oe=(ee,Ee)=>{if(!l()||!this.sourceBuffer)return;let ke,Le,$t;const ze=pt=>{window.setTimeout(()=>{l()&&oe(ee,Ee)},pt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),ze(100);else{const pt=Ae(),At=A.currentTime;!this.paused&&A.buffered.length>1&&le===At&&pt-Se>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),le!==At&&(le=At,Se=pt);const ai=this._getBufferSizeSec();if(ai>30)N(`Buffered ${ai} seconds; delaying appendBuffer`),ze(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:pt,buf:ai}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ut){if(Ut.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),$t=this.sourceBuffer.buffered.length,$t!==0&&(ke=this.sourceBuffer.buffered.start(0),Le=At,Le-ke>4&&this.sourceBuffer.remove(ke,Le-3)),ze(1e3);else throw Ut}}},ve=()=>{U&&Y&&(N([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Z)]),oe(U,function(){U=null,H()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Re=ee=>{l()&&f(ge(ee),(Ee,ke)=>{if(l()){if(ke/=1e3,U=Ee,Z=ee,n=ee.startTS,ke){const Le=Math.min(10,ee.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}ve()}},()=>this._handleNetworkError())},je=ee=>{l()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},ri=ee=>{l()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(l()){if(B=Ae(),!ee){k();return}V=ee,!K(w)||ee.startTS>w?Re(ee):(Z=ee,H())}},w),e.cachedHeader?ri(e.cachedHeader):h(e.headerUrl,ri,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){const{logger:t,playerCallback:s}=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),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=l=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),m=l/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,f)=>{const m=Ae();if(this.chunkRateEstimator.addInterval(h,m,f)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-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 l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Zd(n)<3e4)return;s(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{const f=a.updateChunk(l,h);return f&&d(),f},notifySwitch:l=>{const h=Ae();l<o&&(n=h),o=l}}}_fetchManifest(e,t,s){this.manifestRequest=fs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ts).withRetryCount(is).withRetryInterval(mg,Sg).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Et(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,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}`),s({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))},gg))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var W;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const $g=[W.PAUSED,W.PLAYING,W.READY],Ag=[W.PAUSED,W.PLAYING,W.READY];class wg{constructor(e){this.subscription=new se,this.videoState=new ue(W.STOPPED),this.representations$=new b([]),this.textTracksManager=new tt,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Da,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:O.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,c=[];for(const l of d){const h=(a=l.name)!==null&&a!==void 0?a:l.index.toString(10),f=(n=Ni(l.name))!==null&&n!==void 0?n:Bt(l.video),m=l.bitrate/1e3,p=Object.assign({},l.video);if(!f)continue;const S={id:h,quality:f,bitrate:m,size:p};c.push({track:S,representation:l})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:l})=>l)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,c=(u=this.representations$.getValue().find(({representation:l})=>l===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:d,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,c);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===v.STOPPED){a!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(W.STOPPED));return}if(!n){if(Ag.includes(a)){const c=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;_(c)&&this.setVideoTrack(c);const l=this.params.desiredState.autoVideoTrackSwitching.getTransition();l&&this.setAutoQuality(l.to)}if((u==null?void 0:u.to)!==v.PAUSED&&d.state===F.Requested&&$g.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(Kt(this.params.source.url));return;case W.MANIFEST_READY:this.videoState.startTransitionTo(W.READY),this.prepare();break;case W.READY:if(o===v.PAUSED)this.videoState.setState(W.PAUSED);else if(o===v.PLAYING){this.videoState.startTransitionTo(W.PLAYING);const c=u==null?void 0:u.from;c&&c===v.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)})}return;case W.PLAYING:o===v.PAUSED&&(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case W.PAUSED:o===v.PLAYING&&(this.videoState.startTransitionTo(W.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(W.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return L(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.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=ht(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=ft(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===W.READY&&this.videoState.setState(W.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===F.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(W.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(nt({zeroTime:this.zeroTime$.pipe(j(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Mt(this.video,this.params.desiredState.isLooped,t)).add(lt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Tt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&RS(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case W.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(v.STOPPED);break;case W.MANIFEST_READY:case W.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===v.READY&&this.params.desiredState.playbackState.setState(v.READY);break;case W.PAUSED:this.params.desiredState.playbackState.setState(v.PAUSED);break;case W.PLAYING:this.params.desiredState.playbackState.setState(v.PLAYING);break;default:return L(r.to)}},t)).add(x(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Eg({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,s,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=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!d&&_(u)?u:(a=xi(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,l=(n=o.find(({track:h})=>h.id===c))===null||n===void 0?void 0:n.representation;P(l,"Representations missing"),this.dash.startPlay(l,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.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,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(Kt(this.params.source.url,s))}}var eu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?wi.HTTP1:(e=s)!==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}},Rt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const _g=i=>{const e=document.createElement("a");return e.href=i,e.origin},kg=i=>{const e=document.createElement("a");return e.href=i,e.host};class tu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,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,s,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.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 c=Ci(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(l=>l.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(c))}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(c){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.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(kg(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 Es{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(s){if(s.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",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let c=0,l=0,h=0;const f=p=>{r(Es._str2ua(p.substr(u))),u=p.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Zt(m)),this._lastXhr=new tu(m,e.failoverHosts,p=>{this._lastXhr=void 0,f(p);const S=Date.now()-d;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),a==null||a()},p=>{if(p.length-u>o&&f(p),l===0){l=Date.now();return}h=p.length-c;const S=Date.now()-l;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,c=p.length,l=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},n,(p,S,g)=>this._params.onError(p,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(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=Es._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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 Pg{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)?)?$/,s=(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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Zt(s)),new tu(s,t,r=>{this.attachManifest(r,t,_g(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,c)=>{const l=d.attributes.getNamedItem(c);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var c,l,h,f,m,p,S,g,y,I,w,A,N,X,Y,U,Z,V,B;const ie=d.getElementsByTagName("SegmentBase")[0],le=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],k=Se&&n(Se,"range").split("-");if(!k||!le){const je=d.parentElement;if((je==null?void 0:je.getAttribute("contentType"))==="text"){const ri=(c=d.getAttribute("id"))!==null&&c!==void 0?c:void 0,ee=(s?s+"/":"")+((m=(f=(h=(l=d.getElementsByTagName("BaseURL"))===null||l===void 0?void 0:l[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ee=(p=je.getAttribute("lang"))!==null&&p!==void 0?p:void 0;ee&&u.push({id:ri,url:ee,language:Ee})}return}const H=.1,oe=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ve=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ge;const Re=(y=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&y!==void 0?y:void 0;ge=Re?Ca(Re):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:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(le[0]),indexTo:Number(le[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:(Y=(X=d.attributes.getNamedItem("mimeType"))===null||X===void 0?void 0:X.value)!==null&&Y!==void 0?Y:void 0,fps:ge,bufferSize:H*oe/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:(B=(V=d.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.value)!==null&&B!==void 0?B:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:c,url:l})=>{const h=document.createElement("track");h.setAttribute("src",l),d&&h.setAttribute("id",d),c&&h.setAttribute("srclang",c),this._video.appendChild(h)}),this._representations.sort((d,c)=>c.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 s=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 c=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<c;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},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 s=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 c=this._appendVector[String(d.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let l;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}l=f.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},l*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=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Es({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.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||K(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Q;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const Rg=[Q.PAUSED,Q.PLAYING];class Ig{constructor(e){this.videoState=new ue(Q.STOPPED),this.subscription=new se,this.representations$=new b([]),this.currentRepresentation$=new b(void 0),this.textTracksManager=new tt,this.elementSize$=new b(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var s,r,a;const n=[];for(const o of t){const u=(r=(s=o.name)!==null&&s!==void 0?s:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&Ni(o.name))!==null&&a!==void 0?a:Bt(o),c=o.bandwidth/1e3,l={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:c,size:l,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(Q.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.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(),s=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(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===v.STOPPED){t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.dash.destroy(),this.video.setAttribute("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(Q.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==v.PAUSED&&n.state===F.Requested&&Rg.includes(t)&&this.seek(n.position,n.forcePrecise),t){case Q.STOPPED:this.videoState.startTransitionTo(Q.MANIFEST_LOADED),this.prepare();return;case Q.MANIFEST_LOADED:this.videoState.startTransitionTo(Q.INITIAL_REPRESENTATION_SELECTED);return;case Q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Q.METADATA_LOADED:this.videoState.startTransitionTo(Q.READY),this.dash.updateRefsForCurrentTime();return;case Q.READY:r===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case Q.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(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:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=ht(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.isAudioTracksExist$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new YS(this.video),this.dash=new Pg({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,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:O.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,s=o=>{e.error$.next({id:"DashProvider",category:O.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=ft(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));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$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==F.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(lt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(Ts(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Q.READY&&this.videoState.setState(Q.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:O.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$,G(this.video,"progress")).pipe($(()=>{var o,u,d;const c=this.currentRepresentation$.getValue(),l=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(f))g=f;else{const y=Rt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(y/I,1);g=(u=xi(l.map(({track:A})=>A),{container:p,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=l.find(({representation:A})=>A===c))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=l.find(({track:y})=>y.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(nt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j(_))}).pipe(ye()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j(_),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Rt(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(Pe(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=eu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),Ct(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(j(_)).subscribe(this.handleRepresentationPlay,s)).add(x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 L(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}var Ne;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Ne||(Ne={}));var $s;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})($s||($s={}));var Be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Be||(Be={}));var te;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(te||(te={}));var ei;(function(i){i.MP4="mp4",i.WEBM="webm"})(ei||(ei={}));var ra=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Dg=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Cg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",co=Cg?Dg:window.requestIdleCallback;var Tr,Er;let iu=!1;try{iu=Kd()&&parseInt((Er=(Tr=navigator.userAgent.match(/Version\/(\d+)/))===null||Tr===void 0?void 0:Tr[1])!==null&&Er!==void 0?Er:"",10)<16}catch(i){console.error(i)}class Og{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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:O.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ce(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ce(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ce(this,void 0,void 0,function*(){return new Promise(t=>{let s;iu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"&&s==="remove"||this.error$.next({id:`BufferTaskQueue:${s}`,category:O.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:L(t)}}}var lo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const su=new TextDecoder("ascii"),ru=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=su.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,i.byteLength)-e,n=new DataView(i.buffer,i.byteOffset+e,a);return{id:r,size:t,contents:n}},Lg=i=>su.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",xg=(i,e,t)=>{const s=ru(i),r=[];let a=0;const n=()=>{const p=s.contents.getUint32(a);return a+=4,p};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),c=n(),l=n(),h=n()&4294967295;let f=c/d*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+l;for(let p=0;p<h;p++){const S=n(),g=S>>>31,y=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const w=I/d*1e3;r.push({status:te.NONE,time:{from:f,to:f+w},byte:{from:m,to:m+y-1}}),f+=w,m+=y}return r},Ng=i=>{let e=0,t=!1,s=!1;for(;e<=i.byteLength&&!t;){const r=new DataView(i.buffer,i.byteOffset+e);try{const a=ru(r);if(s||(s=a.id==="mdat"),e+a.size<=i.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=i.byteLength&&s?new DataView(i.buffer,i.byteOffset,e):null},Bg={validateData:Lg,parseInit:()=>null,getIndexRange:()=>{},parseSegments:xg,parseFeedableSegmentChunk:Ng};var E;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(D||(D={}));const ho={[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}},au=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=As(i,t),r=s in ho,a=r?ho[s].type:D.Binary,n=i.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(i.buffer,i.byteOffset+t+1,o-1),d=((n&255>>o)<<(o-1)*8)+As(u),c=t+o;let l;return c+d>i.byteLength?l=new DataView(i.buffer,i.byteOffset+c):l=new DataView(i.buffer,i.byteOffset+c,d),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:c,tagSize:c+d,value:l,valueSize:d}},As=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},at=(i,e)=>{switch(e){case D.SignedInteger:return i.getInt8(0);case D.UnsignedInteger:return As(i);case D.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(i);case D.UTF8:return new TextDecoder("utf-8").decode(i);case D.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case D.Master:return i;case D.Binary:return i;default:L(e)}},Bi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=au(s);if(!e(r))return;r.type===D.Master&&Bi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Mg=i=>{if(i.getUint32(0)!==E.EBML)return!1;let e,t,s;const r=au(i);return Bi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=at(o,n):a===E.DocType?t=at(o,n):a===E.DocTypeReadVersion&&(s=at(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},nu=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],Ug=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],Vg=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d;return Bi(i,({tag:c,type:l,value:h,valueSize:f})=>{if(c===E.SeekID){const m=at(h,l);d=As(m)}else c!==E.SeekPosition&&(d=void 0);return c===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):c===E.Info?a=!0:c===E.SeekHead?n=!0:c===E.TimestampScale?s=at(h,l):c===E.Duration?r=at(h,l):c===E.SeekPosition&&d===E.Cues?u=at(h,l):a&&n&&nu.includes(c)&&(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"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u}},Fg=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Hg=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Bi(i,({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=at(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=at(d,u));break;default:t&&nu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:c}=o,l=a[u+1];return{status:te.NONE,time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Gg=i=>{let e=0,t=!1;try{Bi(i,s=>s.tag===E.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Ug.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Yg={validateData:Mg,parseInit:Vg,getIndexRange:Fg,parseSegments:Hg,parseFeedableSegmentChunk:Gg};class fo{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.error$=new C,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new It,this.destroyAbortController=new It,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Fe(this.destroyAbortController.signal,function(d){return He(this,arguments,function*(){const c=this.representations.get(d);P(c,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Og(this.sourceBuffer),this.subscription.add(G(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:O.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(G(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:O.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,lo(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield M(this.loadInit(c,"high",!0));const l=this.initData.get(c.id),h=this.segments.get(c.id);if(P(l,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(l instanceof ArrayBuffer))return yield M(void 0);let f=0;for(const m of h)m.time.from-f>0&&this.gaps.push({representation:c.id,from:f,to:m.time.from}),f=m.time.to;_(c.duration)&&c.duration-f>0&&this.gaps.push({representation:c.id,from:f,to:c.duration}),yield yield M(this.sourceBufferTaskQueue.append(l,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=Fe(this.destroyAbortController.signal,function(d){return He(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const c=this.representations.get(d);P(c,`No such representation ${d}`);let l=this.initData.get(d);if(K(l)?yield yield M(this.loadInit(c,"high",!1)):l instanceof Promise&&(yield yield M(l)),l=this.initData.get(d),!l||!(l instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(l,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=s,s){case ei.MP4:this.containerParser=Bg;break;case ei.WEBM:this.containerParser=Yg;break;default:L(s)}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 It,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Rt(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&lo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Rt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const c=st(o,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&Rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=st(s,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s: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,s){const r=e.findIndex(({status:l,time:{from:h,to:f}},m)=>{const p=h<=s&&f>=s,S=h>s||p||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=s+g||f<=s+g;return(l===te.NONE||l===te.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!ra(this.sourceBuffer.buffered,s))&&S&&y});if(r===-1)return[];if(t!==Be.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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(n<=d||o<=c);l++){const h=a[l];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ce(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Be.BYTE_RANGE:{r=t.segmentReference.url,a={from:st(e,0).byte.from,to:st(e,-1).byte.to};break}case Be.TEMPLATE:{const d=st(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:L(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield Fe(u,function(){return He(this,arguments,function*(){const d=Ha(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,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,c)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,c,u)}catch(l){this.error$.next({id:"SegmentFeeding",category:O.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:u,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(d)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(s=Rt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:O.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=l=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),l.segment.status=te.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===te.FED&&m.time.from===l.segment.time.from&&m.time.to===l.segment.time.to&&(m.status=te.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const l of this.activeSegments){const{segment:h}=l,f=d===Be.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:c;if(l.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const S=f?h.byte.from-s:0,g=f?h.byte.to-s:e.byteLength,y=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&y&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(l);const w=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(l):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(l.loadedBytes=Math.min(m,r-S),l.loadedBytes>l.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),A=l.loadedBytes===m?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,l.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)l.fedBytes+=A.byteLength,l.fedBytes===m&&o(l);else{if(l.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.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 s=this.representations.get(e);s&&(this.initLoadIdleCallback=co(()=>xs(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ce(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Fe(this.destroyAbortController.signal,function(){return He(this,arguments,function*(){const o=Ha(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:O.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ce(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var c;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const l="size"in d?(c=d.size)!==null&&c!==void 0?c:0:d.byte.to-d.byte.from;r+=l};for(const d of this.segments.values())for(const c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===te.FED&&u(c)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===te.FED&&u(c)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(l)){a=c,n=l;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const l of c)l.time.from>e+d&&l.status===te.FED&&u(l)}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 s of t){let r={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.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=co(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:O.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),d=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Wt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Wt||(Wt={}));class qg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new It,this.subscription=new se,this.fetchManifest=Fe(this.abortAllController.signal,function(r){return He(this,arguments,function*(){let a=r;this.requestQuic&&(a=Zt(a));const n=yield yield M(Xt(a,{signal:this.abortAllController.signal}).catch(gi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Wt.HEADER:Wt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:c=!0}={}){var l,h,f,m;return He(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case Wt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Wt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:L(a)}this.requestQuic&&(p=Zt(p));let g=this.abortAllController.signal;if(d){const k=new It;if(this.subscription.add(x(G(this.abortAllController.signal,"abort"),G(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){gi(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){gi(H)}g=k.signal}const y=pe(),I=yield yield M(Xt(p,{priority:u,headers:S,signal:g}).catch(gi)),w=pe();if((l=this.throughputEstimator)===null||l===void 0||l.addRawRtt(w-y),!I)return yield M(null);if(!I.ok||!I.body)return yield M(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 yield M(I.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,pe()-w),o==null||o(new DataView(k),k.byteLength),yield M(k)}if(!o&&!c)return yield M(I.arrayBuffer());const[N,X]=I.body.tee(),Y=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let U=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),B=new DataView(Z);let ie=!1;const le=k=>{ie=!0,gi(k)},Se=Fe(g,function({done:k,value:H}){return He(this,arguments,function*(){if(U===0&&this.lastRequestFirstBytes$.next(pe()-y),g.aborted)return yield M(void 0);k?o==null||o(B,U):H&&(V.set(H,U),U+=H.byteLength,o==null||o(B,U),yield yield M(Y==null?void 0:Y.read().then(Se,le)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,le)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=Fe(this.abortAllController.signal,function(r,a,n){var o;return He(this,arguments,function*(){if(r.type!==Be.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let c=u,l=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(c=Math.min(f,u),l=Math.max(m,d))),c=Math.min(c,0);const p=yield yield M(this.fetch(r.url,{range:{from:c,to:l},priority:n,measureThroughput:!1}));if(!p)return yield M(null);const S=new DataView(p,u-c,d-c+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(p,y.from-c,y.to-y.from+1);else{const A=yield yield M(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!A)return yield M(null);I=new DataView(A)}const w=a.parseSegments(I,g,y);return yield M({dataView:new DataView(p),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=Fe(this.abortAllController.signal,function(r,a){return He(this,arguments,function*(){if(r.type!==Be.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=eu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ce(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:L(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const gi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},po=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},$r=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jg=(i,e)=>{var t,s,r,a,n,o,u,d,c,l,h,f,m,p,S,g,y,I,w,A,N,X,Y,U,Z,V,B,ie,le,Se,k,H,oe,ve,ge,Re,je;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},ke=ee.children[0],Le=ke.getElementsByTagName("Period")[0],$t=Le.children;let ze;const pt=ke.getAttribute("mediaPresentationDuration"),At=Le.getAttribute("duration");if(pt)ze=po(pt);else if(At){const We=po(At);_(We)&&(ze=We)}let ai=0;const Ut=(s=(t=ke.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],hu=Ut.includes($s.WEBM_AS_IN_FFMPEG)||Ut.includes($s.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const We of $t){const Mi=We.getAttribute("mimeType"),fu=We.getAttribute("codecs"),La=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:Mi==null?void 0:Mi.split("/")[0],pu=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],vu=We.querySelectorAll("Representation"),mu=We.querySelector("SegmentTemplate");if(La!=="text")for(const $e of vu){const ni=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Mi,xa=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:fu)!==null&&d!==void 0?d:"",Ui=(l=(c=$e.getAttribute("contentType"))!==null&&c!==void 0?c:ni==null?void 0:ni.split("/")[0])!==null&&l!==void 0?l:La,Su=(f=(h=We.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],gu=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Na=parseInt((p=$e.getAttribute("height"))!==null&&p!==void 0?p:"",10),Ba=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Ma=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",bu=(y=$e.getAttribute("quality"))!==null&&y!==void 0?y:void 0,yu=Ma?Ca(Ma):void 0,Tu=(I=$e.getAttribute("id"))!==null&&I!==void 0?I:(ai++).toString(10),Eu=Ui==="video"?`${Na}p`:Ui==="audio"?`${Ba}Kbps`:xa,$u=`${Tu}@${Eu}`,Au=(N=(A=(w=$e.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",Ua=new URL(Au,e).toString(),wu=[...Ut,...pu,...Su];let Ms;const _u=$e.querySelector("SegmentBase"),wt=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:mu;if(_u){const oi=(U=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&U!==void 0?U:"",[di,Vs]=oi.split("-").map(_t=>parseInt(_t,10)),ui={from:di,to:Vs},ci=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[Fs,Vi]=ci?ci.split("-").map(_t=>parseInt(_t,10)):[],li=ci?{from:Fs,to:Vi}:void 0;Ms={type:Be.BYTE_RANGE,url:Ua,initRange:ui,indexRange:li}}else if(wt){const oi={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(B=$e.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},di=parseInt((ie=wt.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),Vs=(le=wt.getAttribute("initialization"))!==null&&le!==void 0?le:"",ui=wt.getAttribute("media"),ci=(k=parseInt((Se=wt.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&k!==void 0?k:1,Fs=$r(Vs,oi);if(!ui)throw new ReferenceError("No media attribute in SegmentTemplate");const Vi=(H=wt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],li=[];if(Vi.length){let _t=ci,kt=0;for(const hi of Vi){const Vt=parseInt((oe=hi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,fi=parseInt((ve=hi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,pi=(Re=parseInt((ge=hi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Re!==void 0?Re:void 0;for(let Va=0;Va<fi+1;Va++){const ku=$r(ui,Object.assign(Object.assign({},oi),{segmentNumber:_t.toString(10),segmentTime:pi.toString(10)})),Pu=pi?pi/di:kt;kt+=Vt/di;const Ru=kt;_t++,li.push({time:{from:Pu,to:Ru},url:ku})}}}else if(_(ze)){const kt=parseInt((je=wt.getAttribute("duration"))!==null&&je!==void 0?je:"",10)/di*1e3,hi=Math.ceil(ze/kt);let Vt=0;for(let fi=1;fi<hi;fi++){const pi=$r(ui,Object.assign(Object.assign({},oi),{segmentNumber:fi.toString(10),segmentTime:Vt.toString(10)}));li.push({time:{from:Vt,to:Vt+kt},url:pi}),Vt+=kt}}Ms={type:Be.TEMPLATE,baseUrl:Ua,initUrl:Fs,segments:li}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ui||!ni)continue;const Us={video:Ne.VIDEO,audio:Ne.AUDIO,text:Ne.TEXT}[Ui];Us&&Ee[Us].push({id:$u,kind:Us,segmentReference:Ms,profiles:wu,duration:ze,bitrate:Ba,mime:ni,codecs:xa,width:gu,height:Na,fps:yu,quality:bu})}}return{duration:ze,container:hu,representations:Ee}},zg=["timeupdate","progress","play","seeked","stalled","waiting"];var xe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(xe||(xe={}));let Wg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new ue(xe.NONE),this.currentVideoRepresentation$=new b(void 0),this.error$=new C,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new It,this.initManifest=Fe(this.destroyController.signal,function(t,s){return He(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:O.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=jg(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:O.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,c,l;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((l=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||l===void 0?void 0:l.call(c,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Ci(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:O.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=Fe(this.destroyController.signal,function(t,s){return He(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(xe.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 fo(Ne.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new fo(Ne.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$,nt({allBuffersFull:a,someBufferEnded:n}).pipe(j(({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:O.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 yield M(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&&_(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(xe.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;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||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Du(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:O.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new qg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(xe.RUNNING),this.subscription.add(x(...zg.map(e=>G(this.element,e)),G(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:O.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(G(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(G(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ra(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ce(this,void 0,void 0,function*(){const s={[Ne.VIDEO]:this.videoBufferManager,[Ne.AUDIO]:this.audioBufferManager,[Ne.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,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((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),ra(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(xe.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const r of s.gaps)s.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 s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));const Qg=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ni(a):void 0)!==null&&n!==void 0?n:Bt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Jg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Kg=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=st(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:st(i,-1)};class Xg{constructor(e){this.subscription=new se,this.videoState=new ue(he.STOPPED),this.elementSize$=new b(void 0),this.textTracksManager=new tt,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ng,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===F.Requested&&(r==null?void 0:r.to)!==v.PAUSED&&t!==he.STOPPED&&s!==v.STOPPED&&this.seek(a.position,a.forcePrecise),s===v.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.player.stop(),this.video.setAttribute("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(he.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}switch(t){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:s===v.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY);return;case he.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case he.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(t)}}},this.params=e,this.video=ht(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Wg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=ft(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:O.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,c)=>this.subscription.add(d.subscribe(c,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(_),ye(),Ct(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Mt(this.video,t.isLooped,r)),this.subscription.add(lt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Tt(this.video,t.playbackRate,s.playbackRateState$,r)),a(Ts(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,v.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,v.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var c;if(d===xe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const l=this.player.getRepresentations();P(l,"Manifest not loaded or empty");const h=Array.from(l.audio).sort((p,S)=>S.bitrate-p.bitrate),f=Array.from(l.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const S=Jg(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of f){const S=Qg(p);if(S){this.videoTracks.push({track:S,representation:p});const g=!this.params.tuning.isAudioDisabled&&Kg(h,f,p);g&&this.audioRepresentations.set(p.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioTracksExist$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(c=this.audioRepresentations.get(m.id))===null||c===void 0?void 0:c.id)}else d===xe.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:O.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$,G(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!==xe.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation();if(l){this.player.switchRepresentation(Ne.VIDEO,l.id).catch(n);const h=this.audioRepresentations.get(l.id);h&&this.player.switchRepresentation(Ne.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),$(d=>{var c;return d&&((c=this.videoTracks.find(({representation:{id:l}})=>l===d))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===v.READY),me());this.subscription.add(x(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(x(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,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,c=this.params.output.currentVideoTrack$.getValue(),l=Rt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(l/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!o&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,c&&(a=(r=this.audioRepresentations.get(c.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),p=xi(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:m,forwardBufferHealth:f,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?p!=null?p:d:d!=null?d:p;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}prepare(){return ce(this,void 0,void 0,function*(){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.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}const Zg=5e3,it={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const ss=(i,e)=>new Pi(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class eb{constructor(e){this.subscription=new se,this.videoState=new ue(J.INITIALIZING),this.textTracksManager=new tt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==J.INITIALIZING)switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===F.Requested&&this.seek(a.position),s){case v.STOPPED:switch(t){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:L(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:L(t)}break;case v.PLAYING:switch(t){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:L(t)}break;case v.PAUSED:switch(t){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case J.PLAYING:this.pause();break;default:L(t)}break;default:L(s)}},this.video=ht(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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:O.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Zg);xs(import("hls.js/dist/hls.min.js").then(r=>{e||(it.Hls=r.default,it.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(it.Hls,"hls.js not loaded"),this.hls=new it.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(it.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:O.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ft(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,s));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$),this.subscription.add(Mt(this.video,e.isLooped,s)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ss(this.hls,it.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:O.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)===null||c===void 0?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),R(e.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),R(e.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(ss(this.hls,it.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((c,l)=>{var h,f;const m=l.name||l.height.toString(10),{width:p,height:S}=l,g=(f=Ni((h=l.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Bt({width:p,height:S});if(!g)return c;const y=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,I={id:m.toString(),quality:g,bitrate:l.bitrate/1e3,size:{width:p,height:S},fps:y};return this.trackLevels.set(m,{track:I,level:l}),c.push(I),c},[]))),t.availableVideoTracks$),a(ss(this.hls,it.Events.LEVEL_LOADING).pipe($(({url:d})=>Pe(d))),t.hostname$),this.subscription.add(Xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))===null||c===void 0?void 0:c.track},o=ss(this.hls,it.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Xe(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var c;if(K(d))return;const l=(c=this.trackLevels.get(d))===null||c===void 0?void 0:c.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,m=this.hls.levels[f];!m||l.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:s})),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$,Ce(["init"])).pipe(Ge(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ce(this,void 0,void 0,function*(){this.videoState.startTransitionTo(J.PLAYING),(yield Et(this.video))||(this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(J.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.setAttribute("src",""),this.video.load(),this.videoState.setState(J.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}}const vo="X-Playback-Duration";var mo=i=>ce(void 0,void 0,void 0,function*(){const e=yield Xt(i,{method:"HEAD"});return e.headers.has(vo)?parseInt(e.headers.get(vo),10):void 0});const tb=i=>{let e=null;if(i.QUALITY&&(e=Ni(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Bt({width:t,height:s})}return e!=null?e:null},ou=(i,e=i)=>ce(void 0,void 0,void 0,function*(){var t;const a=(yield(yield Xt(i)).text()).split(`
|
|
8
8
|
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const c=Ci(d[1].split(",").map(g=>g.split("="))),l=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,h=tb(c);let f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[g,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&y&&(p={width:g,height:y})}const S=new URL(a[++o],e).toString();h&&n.push({id:l,quality:h,url:S,bandwidth:f,size:p,fps:m})}return n});var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class ib{constructor(e){var t;this.subscription=new se,this.videoState=new ue(re.STOPPED),this.textTracksManager=new tt,this.manifests$=new b([]),this.liveOffset=new Da,this.manifestStartTime$=new b(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===v.STOPPED){r!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.setAttribute("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(re.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||u){const l=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(l),this.prepare(),c.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==v.PAUSED&&c.state===F.Requested){this.videoState.startTransitionTo(re.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case re.READY:a===v.READY?R(this.params.desiredState.playbackState,v.READY):a===v.PAUSED?(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.PAUSED)):a===v.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:a===v.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case re.PAUSED:a===v.PLAYING?(this.videoState.startTransitionTo(re.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)===v.PAUSED&&(R(this.params.desiredState.playbackState,v.PAUSED),this.liveOffset.pause());return;case re.CHANGING_MANIFEST:break;default:return L(r)}},this.params=e,this.video=ht(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:ne.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),ou(Kt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:O.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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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(c=>c.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:O.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));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$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const l=d.to;this.params.desiredState.videoTrack.setState(l);const h=this.manifests$.getValue().find(f=>f.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Pe(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===re.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===F.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const c=(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(c||void 0)},s)),this.subscription.add(nt({startTime:this.manifestStartTime$.pipe(j(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(K(e))return;const t=Kt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),mo(t).then(s=>{var r;if(!K(s))this.maxSeekBackTime$.next(s);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(K(a)||!isFinite(a))try{Xt(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();mo(d).then(c=>{K(c)||this.maxSeekBackTime$.next(c)})}})}catch(n){}}})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(de||(de={}));class sb{constructor(e){this.subscription=new se,this.videoState=new ue(de.STOPPED),this.textTracksManager=new tt,this.manifests$=new b([]),this.syncPlayback=()=>{const s=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===v.STOPPED){s!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.setAttribute("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(de.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n||o){const c=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:l}=this.video;this.prepare(),d.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:l*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==v.PAUSED&&d.state===F.Requested&&this.seek(d.position),s){case de.READY:r===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case de.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return L(s)}},this.params=e,this.video=ht(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ne.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.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),ou(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:O.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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(c=>c.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:O.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ft(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$),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const l=d.to;this.params.desiredState.videoTrack.setState(l);const h=this.manifests$.getValue().find(f=>f.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Pe(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===F.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();K(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var fe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(fe||(fe={}));class rb{constructor(e){this.subscription=new se,this.videoState=new ue(fe.STOPPED),this.trackUrls={},this.textTracksManager=new tt,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.STOPPED),this.video.setAttribute("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(fe.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==v.PAUSED&&o.state===F.Requested&&this.seek(o.position),t){case fe.READY:s===v.READY?R(this.params.desiredState.playbackState,v.READY):s===v.PAUSED?(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case fe.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(t)}},this.params=e,this.video=ht(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:O.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));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$),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.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()===fe.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const s=(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(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];P(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=Zt(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Pe(r))}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const So=["stun:videostun.mycdn.me:80"],ab=1e3,nb=3,Ar=()=>null;class ob{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ar,this.externalStopCallback=Ar,this.externalErrorCallback=Ar,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.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}}handleUpdateMessage(e){return ce(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ce(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:So}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ce(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ce(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield 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:O.WTF,message:e.message})}onPeerConnectionStream(e){return ce(this,void 0,void 0,function*(){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()))}}createOffer(){return ce(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))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),ab)}normalizeOptions(e={}){const t={stunServerList:So,maxRetryNumber:nb,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));class db{constructor(e){this.videoState=new ue(ae.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case ae.READY:s===v.PAUSED?(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case ae.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return L(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ht(e.container),this.liveStreamClient=new ob(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:O.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=ft(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));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$),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)===ae.READY&&this.videoState.setState(ae.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ae.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(v.STOPPED);break;case ae.READY:break;case ae.PAUSED:t.playbackState.setState(v.PAUSED);break;case ae.PLAYING:t.playbackState.setState(v.PLAYING);break;default:return L(n.to)}},s)).add(x(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ne.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,v.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ae.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:O.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class go{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 ub=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},wr,_r,kr,Pr,Rr,Ir,rs,Dr,as,Cr,ns,Or,os,Lr,ds,xr;const du=ub(),mt=document.createElement("video"),vt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((_r=(wr=window.SourceBuffer)===null||wr===void 0?void 0:wr.prototype)===null||_r===void 0?void 0:_r.appendBuffer)),hls:Boolean(((kr=mt.canPlayType)===null||kr===void 0?void 0:kr.call(mt,"application/x-mpegurl"))||((Pr=mt.canPlayType)===null||Pr===void 0?void 0:Pr.call(mt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Je={mp4:Boolean((Rr=mt.canPlayType)===null||Rr===void 0?void 0:Rr.call(mt,"video/mp4")),webm:Boolean((Ir=mt.canPlayType)===null||Ir===void 0?void 0:Ir.call(mt,"video/webm"))},St={h264:Boolean((Dr=(rs=window.MediaSource)===null||rs===void 0?void 0:rs.isTypeSupported)===null||Dr===void 0?void 0:Dr.call(rs,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Cr=(as=window.MediaSource)===null||as===void 0?void 0:as.isTypeSupported)===null||Cr===void 0?void 0:Cr.call(as,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Or=(ns=window.MediaSource)===null||ns===void 0?void 0:ns.isTypeSupported)===null||Or===void 0?void 0:Or.call(ns,'video/webm; codecs="vp9"')),aac:Boolean((Lr=(os=window.MediaSource)===null||os===void 0?void 0:os.isTypeSupported)===null||Lr===void 0?void 0:Lr.call(os,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((xr=(ds=window.MediaSource)===null||ds===void 0?void 0:ds.isTypeSupported)===null||xr===void 0?void 0:xr.call(ds,'audio/webm; codecs="opus"'))},bi=(St.h264||St.h265)&&St.aac,Bs=vt.hls&&Je.mp4,cb=Boolean(window.WebSocket),lb=()=>Object.keys(St).filter(i=>St[i]),hb=(i,e=!1)=>i.filter(t=>{switch(t){case T.DASH:return vt.mse&&Je.mp4&&bi;case T.DASH_SEP:return vt.mse&&Je.mp4&&bi;case T.DASH_WEBM:return vt.mse&&Je.webm&&St.vp9&&St.opus;case T.DASH_LIVE:return vt.mse&&Je.mp4&&bi;case T.DASH_ONDEMAND:return vt.mse&&Je.mp4&&bi;case T.HLS:case T.HLS_LIVE:case T.HLS_ONDEMAND:return Bs||e&&vt.mse&&Je.mp4&&bi;case T.MPEG:return Je.mp4;case T.DASH_LIVE_WEBM:return!1;case T.WEB_RTC_LIVE:return vt.webrtc&&cb&&St.h264&&(Je.mp4||Je.webm);default:return L(t)}}),fb=()=>du?[T.MPEG,T.DASH_WEBM,T.DASH_SEP,T.DASH,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND]:Bs?[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],pb=()=>du?[T.HLS_LIVE,T.WEB_RTC_LIVE,T.DASH_LIVE]:Bs?[T.WEB_RTC_LIVE,T.HLS_LIVE,T.DASH_LIVE]:[T.WEB_RTC_LIVE,T.DASH_LIVE,T.HLS_LIVE],bo=i=>i?[T.HLS_LIVE]:[T.DASH_WEBM,T.DASH_SEP,T.DASH_ONDEMAND,T.HLS,T.HLS_ONDEMAND,T.MPEG];var vb=i=>new Pi(e=>{const t=new se,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:c})=>`${d}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$,n=new C;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.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),i.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const yo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},mb={cacheDuration:12e4},Sb={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},gb={maxPausedTime:3e4},bb={maxPausedTime:3e4};class yb{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioTracksExist$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),currentBuffer$:new b(void 0),isBuffering$:new b(!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 b(void 0),liveTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),element$:new b(void 0)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=hb([...pb(),...fb()],this.params.tuning.useHlsJs).filter(n=>_(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,r=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new go(r);const a=[...bo(!0),...bo(!1)];this.chromecastFormatsIterator=new go(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(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:O.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,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,s=this.params.desiredState.seekState.getState(),r=s.state!==F.None;this.params.desiredState.seekState.setState({state:F.Requested,position:r?s.position:t,forcePrecise:r?s.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 Ie.SCREEN:return this.createScreenProvider(t);case Ie.CHROMECAST:return this.createChromecastProvider(t);default:return L(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,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 P(o),new Ig(Object.assign(Object.assign({},n),{source:o,config:mb}))}case T.DASH_SEP:case T.DASH_WEBM:case T.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new ug(Object.assign(Object.assign({},n),{source:o,format:e,config:bb})):new Xg(Object.assign(Object.assign({},n),{source:o}))}case T.HLS:case T.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Bs||!this.params.tuning.useHlsJs?new sb(Object.assign(Object.assign({},n),{source:o})):new eb(Object.assign(Object.assign({},n),{source:o}))}case T.HLS_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new ib(Object.assign(Object.assign({},n),{source:o,config:gb}))}case T.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new rb(Object.assign(Object.assign({},n),{source:o}))}case T.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new wg(Object.assign(Object.assign({},n),{source:o,config:Sb}))}case T.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new db({container:s,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 L(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new LS({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ie.CHROMECAST:Ie.SCREEN}chooseFormat(e){switch(e){case Ie.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ie.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return L(e)}}skipFormat(e){switch(e){case Ie.SCREEN:return this.screenFormatsIterator.next();case Ie.CHROMECAST:return this.chromecastFormatsIterator.next();default:return L(e)}}handleNoFormatsError(e){switch(e){case Ie.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case Ie.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return L(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=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 Object.assign(Object.assign({},e),{url:s(e.url)})}return Ci(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,s=0;return e.add(x(this.providerOutput.error$,vb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:yo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:O.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(j(({to:a})=>a===v.PLAYING),ye()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===Ie.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===O.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<yo.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Me;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Me||(Me={}));const uu=new Map;let Dt=Me.RUNTIME;const Nr=`vk-videoplayer-dummy-key-${Math.random()}`,Tb=()=>{try{localStorage.setItem(Nr,"test"),localStorage.removeItem(Nr),Dt=Me.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Nr),Dt=Me.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Dt=Me.RUNTIME;else throw e}else throw i}};Tb();const Eb=i=>{var e,t;switch(Dt){case Me.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Me.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Me.RUNTIME:return uu.get(i);default:L(Dt)}},To=(i,e)=>{switch(Dt){case Me.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Me.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Me.RUNTIME:return void uu.set(i,e);default:L(Dt)}},aa=(i,e,t)=>t*e+(1-t)*i,cu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,$b=(i,e,t,s)=>{let r=0,a=t;const n=cu(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class lu{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 b(e.initial),this.debounced$=new b(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ke(`raw_${s}`),this.smoothedSeries$=new Ke(`smoothed_${s}`),this.reportedSeries$=new Ke(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;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)&&(K(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 Ab extends lu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=aa(this.slow,e,this.params.emaAlphaSlow),this.fast=aa(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class wb extends lu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=cu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=aa(this.emaSmoothed,e,this.params.emaAlpha);const s=$b(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Eo{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Ab({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new wb({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const _b=5e3,$o="one_video_throughput",Ao="one_video_rtt",dt=window.navigator.connection,wo=()=>{const i=dt==null?void 0:dt.downlink;if(_(i)&&i!==10)return i*1e3},_o=()=>{const i=dt==null?void 0:dt.rtt;if(_(i)&&i!==3e3)return i},ko=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Ai{constructor(e){var t,s;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ai.load($o)||(e.useBrowserEstimation?wo():void 0)||_b,a=(s=(t=Ai.load(Ao))!==null&&t!==void 0?t:e.useBrowserEstimation?_o():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(ko(r,a,e.rttPenaltyRequestSize)),this.throughput=Eo.getSmoothedValue(r,-1,e),this.rtt=Eo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=wo();u&&this.throughput.next(u);const d=_o();_(d)&&this.rtt.next(d)};dt&&"onchange"in dt&&this.subscription.add(G(dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{To($o,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{To(Ao,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(nt({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>ko(n,o,e.rttPenaltyRequestSize)),j(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,s=pe();const r=new se;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(G(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(G(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(G(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),u=n-t,d=o-s;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 s=0;const r=pe();let a=0,n=pe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:c})=>ce(this,void 0,void 0,function*(){d?(this.addRawSpeed(s,pe()-r,1),this.concurrentDownloads.delete(e)):c&&(s+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,pe()-n,this.concurrentDownloads.size),a=0,n=pe()),yield t==null?void 0:t.read().then(u,o))});this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,s=1){if(Ai.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=Eb(e);if(_(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Po={throughputEstimator:{type:"TwoEma",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:.3,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},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}},kb=i=>{const e={};for(const t of Object.keys(Po)){const s=Po[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?e[t]=r:typeof s=="object"&&typeof r=="object"?e[t]=Object.assign(Object.assign({},s),r):e[t]=r!=null?r:s}return e};var Pb=({seekState:i,position$:e})=>x(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===F.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),j(_)),e.pipe(j(()=>i.getState().state===F.None))),Rb=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const Ro=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new Pi(a=>{let n;const o=i.transitionEnded$.pipe(j(f=>(f.from===v.PAUSED||f.from===v.STOPPED)&&f.to===v.PLAYING)),u=i.stateChangeEnded$.pipe(j(f=>f.from===v.PLAYING&&f.to===v.PAUSED)),d=e.stateChangeEnded$.pipe(j(({to:f})=>{var m,p;return f.state===F.Requested&&((p=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&p!==void 0?p:i.getState())===v.PLAYING})),c=e.stateChangeEnded$.pipe(j(({from:f,to:m})=>{var p,S;return f.state===F.Applying&&m.state===F.None&&((S=(p=i.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:i.getState())===v.PLAYING})),l=x(o,c).pipe($(()=>r.getValue()),j(_)),h=x(x(u,d,t),s).pipe($(()=>r.getValue()),j(_));return new se().add(l.subscribe(f=>{n=f})).add(h.subscribe(f=>{if(K(n)||n===f)return;const m={from:n,to:f};n=void 0,a.next(m)}))});class xb{constructor(e={}){if(this.subscription=new se,this.logger=new Cu,this.isPlaybackStarted=!1,this.desiredState={playbackState:new ue(v.STOPPED),seekState:new ue({state:F.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({})},this.info={playbackState$:new b(v.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioTracksExist$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),liveTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),chromecastState$:new b(we.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(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 b(void 0),enableDebugTelemetry$:new b(!1),dumpTelemetry:sg},this.initLogs(),this.tuning=kb(e),this.chromecastInitializer=new Bu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ai(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(l=>JSON.stringify(l,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:O.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=Rb(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new yb({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},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.initDebugTelemetry(),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()===v.STOPPED&&e.startTransitionTo(v.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==v.PLAYING&&e.startTransitionTo(v.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==v.PAUSED&&e.startTransitionTo(v.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==v.STOPPED&&e.startTransitionTo(v.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:F.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){return this.chromecastInitializer.castState$.getValue()===we.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===we.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.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 s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(s=>s.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(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===F.None?void 0:t.position;return _(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||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(j(({from:e})=>e===v.STOPPED),ye()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(()=>!this.isPlaybackStarted),j(e=>e.to===v.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case v.PAUSED:this.events.willPause$.next();break;case v.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===F.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},u),{state:F.Applying})):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:O.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===F.Applying&&(this.desiredState.seekState.setState({state:F.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,c)=>bs(d)?1:bs(c)?-1:hs(c,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const c of u)c.fps&&(d[c.quality]=c.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioTracksExist$.subscribe(this.info.isAudioTracksExist$)).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(me()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(me()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(me()).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),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),me()).subscribe(this.info.volume$)).add(Pb({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(x(e.providerOutput.endedEvent$.pipe(Ct(!0)),e.providerOutput.seekedEvent$.pipe(Ct(!1))).pipe(me()).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:O.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(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ye(),$(()=>pe()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(({to:u})=>u===v.PLAYING),ye()).subscribe(()=>s.next(!1)));let r=0;const a=x(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return u&&!d}),me());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 se;this.subscription.add(n);const o=x(G(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(j(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(me()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new b(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>d.next(c&&Math.floor(c/1e3)))),n.add(Ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:c,to:l})=>({start:c,end:l}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:c})=>({start:d,end:c}))).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,c;const l=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(c=u==null?void 0:u.size)===null||c===void 0?void 0:c.height},{width:l==null?void 0:l.videoWidth,height:l==null?void 0:l.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 se;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(j(s=>s.length>0),ye()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=xi(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),ig(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>tg(s)),this.providerContainer.current$.subscribe(({type:s})=>es("provider",s)),t.duration$.subscribe(s=>es("duration",s)),t.availableVideoTracks$.pipe(j(s=>!!s.length),ye()).subscribe(s=>es("tracks",s)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),t.position$.subscribe(new Ke("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),t.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(s=>this.subscription.add(s)),es("codecs",lb())}}const Nb=`${xu}@${Lu}`;export{we as ChromecastState,wi as HttpConnectionType,Ub as Observable,v as PlaybackState,xb as Player,Nb as SDK_VERSION,Vb as Subject,Fb as Subscription,Hb as ValueSubject,T as VideoFormat,ne as VideoQuality};
|