@vkontakte/videoplayer-core 2.0.82 → 2.0.83-dev.65744ed.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,8 +1,66 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.82
3
- * Mon, 17 Apr 2023 11:27:57 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-82/doc/
2
+ * @vkontakte/videoplayer-core v2.0.83-dev.65744ed.0
3
+ * Wed, 19 Apr 2023 17:05:19 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
5
5
  */
6
- import{ValueSubject as y,Subject as O,Subscription as se,isNonNullable as w,ErrorCategory as C,isNullable as K,fromEvent as U,assertNever as x,merge as L,tap as Wa,map as $,observableFrom as Oe,filterChanged as me,assertNonNullable as P,debounce as Ve,timeout as Gu,combine as dt,once as ye,mapTo as Ct,filter as j,now as pe,Observable as Ri,abortable as qe,getExponentialDelay as Qa,interval as Yu,Logger as qu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as My,Subject as Uy,Subscription as Fy,ValueSubject as Vy}from"@vkontakte/videoplayer-shared/es2015.esm.js";import ju from"lodash/debounce.js";const zu="2.0.82",Wu="es2015.esm.js";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var b;(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_CMAF="DASH_LIVE_CMAF",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.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var De;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(De||(De={}));var _e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(_e||(_e={}));var wi;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(wi||(wi={}));var H;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(H||(H={}));function ue(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(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.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 je(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){c(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Qu=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 Ju{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(_e.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new y(_e.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=w((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||Qu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.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(){w(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(U(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 x(r.sessionState)}})).add(L(U(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Wa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Oe([s.getCastState()])).pipe(me(),$(Ku),Wa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===_e.CONNECTED,o=w(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===_e.CONNECTED?w(this.connection$.getValue())?_e.CONNECTED:_e.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:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Ku=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _e.AVAILABLE;case cast.framework.CastState.CONNECTING:return _e.CONNECTING;case cast.framework.CastState.CONNECTED:return _e.CONNECTED;default:return x(i)}};var Ja=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},He=function(i){try{return!!i()}catch(e){return!0}},Xu=He,Rs=!Xu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Yo=Rs,qo=Function.prototype,Gr=qo.call,Zu=Yo&&qo.bind.bind(Gr,Gr),Ge=Yo?Zu:function(i){return function(){return Gr.apply(i,arguments)}},jo=Ge,el=jo({}.toString),tl=jo("".slice),Ii=function(i){return tl(el(i),8,-1)},il=Ge,sl=He,rl=Ii,js=Object,al=il("".split),nl=sl(function(){return!js("z").propertyIsEnumerable(0)})?function(i){return rl(i)=="String"?al(i,""):js(i)}:js,Di=function(i){return i==null},ol=Di,dl=TypeError,ha=function(i){if(ol(i))throw dl("Can't call method on "+i);return i},ul=nl,ll=ha,Ci=function(i){return ul(ll(i))},cl=function(){},si={},qi=function(i){return i&&i.Math==Math&&i},we=qi(typeof globalThis=="object"&&globalThis)||qi(typeof window=="object"&&window)||qi(typeof self=="object"&&self)||qi(typeof Ja=="object"&&Ja)||function(){return this}()||Function("return this")(),Yr=typeof document=="object"&&document.all,hl=typeof Yr=="undefined"&&Yr!==void 0,zo={all:Yr,IS_HTMLDDA:hl},Wo=zo,fl=Wo.all,Te=Wo.IS_HTMLDDA?function(i){return typeof i=="function"||i===fl}:function(i){return typeof i=="function"},pl=we,vl=Te,Ka=pl.WeakMap,ml=vl(Ka)&&/native code/.test(String(Ka)),Xa=Te,Qo=zo,Sl=Qo.all,ct=Qo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Xa(i)||i===Sl}:function(i){return typeof i=="object"?i!==null:Xa(i)},gl=He,ht=!gl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Lt={},bl=we,Za=ct,qr=bl.document,yl=Za(qr)&&Za(qr.createElement),fa=function(i){return yl?qr.createElement(i):{}},Tl=ht,El=He,$l=fa,Jo=!Tl&&!El(function(){return Object.defineProperty($l("div"),"a",{get:function(){return 7}}).a!=7}),Al=ht,_l=He,Ko=Al&&_l(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),wl=ct,kl=String,Pl=TypeError,ft=function(i){if(wl(i))return i;throw Pl(kl(i)+" is not an object")},Rl=Rs,ji=Function.prototype.call,Le=Rl?ji.bind(ji):function(){return ji.apply(ji,arguments)},pa={},zs=pa,Ws=we,Il=Te,en=function(i){return Il(i)?i:void 0},xt=function(i,e){return arguments.length<2?en(zs[i])||en(Ws[i]):zs[i]&&zs[i][e]||Ws[i]&&Ws[i][e]},Dl=Ge,Is=Dl({}.isPrototypeOf),Ds=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Xo=we,Qs=Ds,tn=Xo.process,sn=Xo.Deno,rn=tn&&tn.versions||sn&&sn.version,an=rn&&rn.v8,Ye,gs;an&&(Ye=an.split("."),gs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!gs&&Qs&&(Ye=Qs.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Qs.match(/Chrome\/(\d+)/),Ye&&(gs=+Ye[1])));var Zo=gs,nn=Zo,Cl=He,ed=!!Object.getOwnPropertySymbols&&!Cl(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&nn&&nn<41}),Ol=ed,td=Ol&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ll=xt,xl=Te,Nl=Is,Bl=td,Ml=Object,id=Bl?function(i){return typeof i=="symbol"}:function(i){var e=Ll("Symbol");return xl(e)&&Nl(e.prototype,Ml(i))},Ul=String,Cs=function(i){try{return Ul(i)}catch(e){return"Object"}},Fl=Te,Vl=Cs,Hl=TypeError,Nt=function(i){if(Fl(i))return i;throw Hl(Vl(i)+" is not a function")},Gl=Nt,Yl=Di,Os=function(i,e){var t=i[e];return Yl(t)?void 0:Gl(t)},Js=Le,Ks=Te,Xs=ct,ql=TypeError,jl=function(i,e){var t,s;if(e==="string"&&Ks(t=i.toString)&&!Xs(s=Js(t,i))||Ks(t=i.valueOf)&&!Xs(s=Js(t,i))||e!=="string"&&Ks(t=i.toString)&&!Xs(s=Js(t,i)))return s;throw ql("Can't convert object to primitive value")},bs={},zl={get exports(){return bs},set exports(i){bs=i}},sd=!0,on=we,Wl=Object.defineProperty,Ql=function(i,e){try{Wl(on,i,{value:e,configurable:!0,writable:!0})}catch(t){on[i]=e}return e},Jl=we,Kl=Ql,dn="__core-js_shared__",Xl=Jl[dn]||Kl(dn,{}),va=Xl,un=va;(zl.exports=function(i,e){return un[i]||(un[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 Zl=ha,ec=Object,Ls=function(i){return ec(Zl(i))},tc=Ge,ic=Ls,sc=tc({}.hasOwnProperty),tt=Object.hasOwn||function(e,t){return sc(ic(e),t)},rc=Ge,ac=0,nc=Math.random(),oc=rc(1 .toString),rd=function(i){return"Symbol("+(i===void 0?"":i)+")_"+oc(++ac+nc,36)},dc=we,uc=bs,ln=tt,lc=rd,cc=ed,hc=td,zt=dc.Symbol,Zs=uc("wks"),fc=hc?zt.for||zt:zt&&zt.withoutSetter||lc,ke=function(i){return ln(Zs,i)||(Zs[i]=cc&&ln(zt,i)?zt[i]:fc("Symbol."+i)),Zs[i]},pc=Le,cn=ct,hn=id,vc=Os,mc=jl,Sc=ke,gc=TypeError,bc=Sc("toPrimitive"),yc=function(i,e){if(!cn(i)||hn(i))return i;var t=vc(i,bc),s;if(t){if(e===void 0&&(e="default"),s=pc(t,i,e),!cn(s)||hn(s))return s;throw gc("Can't convert object to primitive value")}return e===void 0&&(e="number"),mc(i,e)},Tc=yc,Ec=id,ma=function(i){var e=Tc(i,"string");return Ec(e)?e:e+""},$c=ht,Ac=Jo,_c=Ko,zi=ft,fn=ma,wc=TypeError,er=Object.defineProperty,kc=Object.getOwnPropertyDescriptor,tr="enumerable",ir="configurable",sr="writable";Lt.f=$c?_c?function(e,t,s){if(zi(e),t=fn(t),zi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&sr in s&&!s[sr]){var r=kc(e,t);r&&r[sr]&&(e[t]=s.value,s={configurable:ir in s?s[ir]:r[ir],enumerable:tr in s?s[tr]:r[tr],writable:!1})}return er(e,t,s)}:er:function(e,t,s){if(zi(e),t=fn(t),zi(s),Ac)try{return er(e,t,s)}catch(r){}if("get"in s||"set"in s)throw wc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var xs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Pc=ht,Rc=Lt,Ic=xs,Oi=Pc?function(i,e,t){return Rc.f(i,e,Ic(1,t))}:function(i,e,t){return i[e]=t,i},Dc=bs,Cc=rd,pn=Dc("keys"),Sa=function(i){return pn[i]||(pn[i]=Cc(i))},ga={},Oc=ml,ad=we,Lc=ct,xc=Oi,rr=tt,ar=va,Nc=Sa,Bc=ga,vn="Object already initialized",jr=ad.TypeError,Mc=ad.WeakMap,ys,ki,Ts,Uc=function(i){return Ts(i)?ki(i):ys(i,{})},Fc=function(i){return function(e){var t;if(!Lc(e)||(t=ki(e)).type!==i)throw jr("Incompatible receiver, "+i+" required");return t}};if(Oc||ar.state){var Xe=ar.state||(ar.state=new Mc);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ys=function(i,e){if(Xe.has(i))throw jr(vn);return e.facade=i,Xe.set(i,e),e},ki=function(i){return Xe.get(i)||{}},Ts=function(i){return Xe.has(i)}}else{var Vt=Nc("state");Bc[Vt]=!0,ys=function(i,e){if(rr(i,Vt))throw jr(vn);return e.facade=i,xc(i,Vt,e),e},ki=function(i){return rr(i,Vt)?i[Vt]:{}},Ts=function(i){return rr(i,Vt)}}var nd={set:ys,get:ki,has:Ts,enforce:Uc,getterFor:Fc},Vc=Rs,od=Function.prototype,mn=od.apply,Sn=od.call,dd=typeof Reflect=="object"&&Reflect.apply||(Vc?Sn.bind(mn):function(){return Sn.apply(mn,arguments)}),Hc=Ii,Gc=Ge,ud=function(i){if(Hc(i)==="Function")return Gc(i)},ba={},ld={},cd={}.propertyIsEnumerable,hd=Object.getOwnPropertyDescriptor,Yc=hd&&!cd.call({1:2},1);ld.f=Yc?function(e){var t=hd(this,e);return!!t&&t.enumerable}:cd;var qc=ht,jc=Le,zc=ld,Wc=xs,Qc=Ci,Jc=ma,Kc=tt,Xc=Jo,gn=Object.getOwnPropertyDescriptor;ba.f=qc?gn:function(e,t){if(e=Qc(e),t=Jc(t),Xc)try{return gn(e,t)}catch(s){}if(Kc(e,t))return Wc(!jc(zc.f,e,t),e[t])};var Zc=He,eh=Te,th=/#|\.prototype\./,Li=function(i,e){var t=sh[ih(i)];return t==ah?!0:t==rh?!1:eh(e)?Zc(e):!!e},ih=Li.normalize=function(i){return String(i).replace(th,".").toLowerCase()},sh=Li.data={},rh=Li.NATIVE="N",ah=Li.POLYFILL="P",fd=Li,bn=ud,nh=Nt,oh=Rs,dh=bn(bn.bind),Ns=function(i,e){return nh(i),e===void 0?i:oh?dh(i,e):function(){return i.apply(e,arguments)}},Wi=we,uh=dd,lh=ud,ch=Te,hh=ba.f,fh=fd,Ht=pa,ph=Ns,Gt=Oi,yn=tt,vh=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 uh(i,this,arguments)};return e.prototype=i.prototype,e},We=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Wi:r?Wi[t]:(Wi[t]||{}).prototype,o=s?Ht:Ht[t]||Gt(Ht,t,{})[t],u=o.prototype,d,l,c,h,f,m,p,S,g;for(h in e)d=fh(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&yn(n,h),m=o[h],l&&(i.dontCallGetSet?(g=hh(n,h),p=g&&g.value):p=n[h]),f=l&&p?p:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?S=ph(f,Wi):i.wrap&&l?S=vh(f):a&&ch(f)?S=lh(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&Gt(S,"sham",!0),Gt(o,h,S),a&&(c=t+"Prototype",yn(Ht,c)||Gt(Ht,c,{}),Gt(Ht[c],h,f),i.real&&u&&(d||!u[h])&&Gt(u,h,f)))},zr=ht,mh=tt,pd=Function.prototype,Sh=zr&&Object.getOwnPropertyDescriptor,ya=mh(pd,"name"),gh=ya&&function(){}.name==="something",bh=ya&&(!zr||zr&&Sh(pd,"name").configurable),yh={EXISTS:ya,PROPER:gh,CONFIGURABLE:bh},vd={},Th=Math.ceil,Eh=Math.floor,$h=Math.trunc||function(e){var t=+e;return(t>0?Eh:Th)(t)},Ah=$h,Ta=function(i){var e=+i;return e!==e||e===0?0:Ah(e)},_h=Ta,wh=Math.max,kh=Math.min,Ph=function(i,e){var t=_h(i);return t<0?wh(t+e,0):kh(t,e)},Rh=Ta,Ih=Math.min,Dh=function(i){return i>0?Ih(Rh(i),9007199254740991):0},Ch=Dh,Ea=function(i){return Ch(i.length)},Oh=Ci,Lh=Ph,xh=Ea,Tn=function(i){return function(e,t,s){var r=Oh(e),a=xh(r),n=Lh(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}},Nh={includes:Tn(!0),indexOf:Tn(!1)},Bh=Ge,nr=tt,Mh=Ci,Uh=Nh.indexOf,Fh=ga,En=Bh([].push),Vh=function(i,e){var t=Mh(i),s=0,r=[],a;for(a in t)!nr(Fh,a)&&nr(t,a)&&En(r,a);for(;e.length>s;)nr(t,a=e[s++])&&(~Uh(r,a)||En(r,a));return r},md=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Hh=Vh,Gh=md,Yh=Object.keys||function(e){return Hh(e,Gh)},qh=ht,jh=Ko,zh=Lt,Wh=ft,Qh=Ci,Jh=Yh;vd.f=qh&&!jh?Object.defineProperties:function(e,t){Wh(e);for(var s=Qh(t),r=Jh(t),a=r.length,n=0,o;a>n;)zh.f(e,o=r[n++],s[o]);return e};var Kh=xt,Sd=Kh("document","documentElement"),Xh=ft,Zh=vd,$n=md,ef=ga,tf=Sd,sf=fa,rf=Sa,An=">",_n="<",Wr="prototype",Qr="script",gd=rf("IE_PROTO"),or=function(){},bd=function(i){return _n+Qr+An+i+_n+"/"+Qr+An},wn=function(i){i.write(bd("")),i.close();var e=i.parentWindow.Object;return i=null,e},af=function(){var i=sf("iframe"),e="java"+Qr+":",t;return i.style.display="none",tf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(bd("document.F=Object")),t.close(),t.F},Qi,fs=function(){try{Qi=new ActiveXObject("htmlfile")}catch(e){}fs=typeof document!="undefined"?document.domain&&Qi?wn(Qi):af():wn(Qi);for(var i=$n.length;i--;)delete fs[Wr][$n[i]];return fs()};ef[gd]=!0;var yd=Object.create||function(e,t){var s;return e!==null?(or[Wr]=Xh(e),s=new or,or[Wr]=null,s[gd]=e):s=fs(),t===void 0?s:Zh.f(s,t)},nf=He,of=!nf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),df=tt,uf=Te,lf=Ls,cf=Sa,hf=of,kn=cf("IE_PROTO"),Jr=Object,ff=Jr.prototype,Td=hf?Jr.getPrototypeOf:function(i){var e=lf(i);if(df(e,kn))return e[kn];var t=e.constructor;return uf(t)&&e instanceof t?t.prototype:e instanceof Jr?ff:null},pf=Oi,$a=function(i,e,t,s){return s&&s.enumerable?i[e]=t:pf(i,e,t),i},vf=He,mf=Te,Sf=ct,gf=yd,Pn=Td,bf=$a,yf=ke,Kr=yf("iterator"),Ed=!1,ut,dr,ur;[].keys&&(ur=[].keys(),"next"in ur?(dr=Pn(Pn(ur)),dr!==Object.prototype&&(ut=dr)):Ed=!0);var Tf=!Sf(ut)||vf(function(){var i={};return ut[Kr].call(i)!==i});Tf?ut={}:ut=gf(ut);mf(ut[Kr])||bf(ut,Kr,function(){return this});var $d={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:Ed},Ef=ke,$f=Ef("toStringTag"),Ad={};Ad[$f]="z";var Aa=String(Ad)==="[object z]",Af=Aa,_f=Te,ps=Ii,wf=ke,kf=wf("toStringTag"),Pf=Object,Rf=ps(function(){return arguments}())=="Arguments",If=function(i,e){try{return i[e]}catch(t){}},xi=Af?ps:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=If(e=Pf(i),kf))=="string"?t:Rf?ps(e):(s=ps(e))=="Object"&&_f(e.callee)?"Arguments":s},Df=Aa,Cf=xi,Of=Df?{}.toString:function(){return"[object "+Cf(this)+"]"},Lf=Aa,xf=Lt.f,Nf=Oi,Bf=tt,Mf=Of,Uf=ke,Rn=Uf("toStringTag"),_a=function(i,e,t,s){if(i){var r=t?i:i.prototype;Bf(r,Rn)||xf(r,Rn,{configurable:!0,value:e}),s&&!Lf&&Nf(r,"toString",Mf)}},Ff=$d.IteratorPrototype,Vf=yd,Hf=xs,Gf=_a,Yf=si,qf=function(){return this},jf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Vf(Ff,{next:Hf(+!s,t)}),Gf(i,r,!1,!0),Yf[r]=qf,i},zf=We,Wf=Le,_d=yh,Qf=jf,Jf=Td,Kf=_a,In=$a,Xf=ke,Dn=si,wd=$d,Zf=_d.PROPER;_d.CONFIGURABLE;wd.IteratorPrototype;var Ji=wd.BUGGY_SAFARI_ITERATORS,lr=Xf("iterator"),Cn="keys",Ki="values",On="entries",ep=function(){return this},tp=function(i,e,t,s,r,a,n){Qf(t,e,s);var o=function(g){if(g===r&&h)return h;if(!Ji&&g in l)return l[g];switch(g){case Cn:return function(){return new t(this,g)};case Ki:return function(){return new t(this,g)};case On:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[lr]||l["@@iterator"]||r&&l[r],h=!Ji&&c||o(r),f=e=="Array"&&l.entries||c,m,p,S;if(f&&(m=Jf(f.call(new i)),m!==Object.prototype&&m.next&&(Kf(m,u,!0,!0),Dn[u]=ep)),Zf&&r==Ki&&c&&c.name!==Ki&&(d=!0,h=function(){return Wf(c,this)}),r)if(p={values:o(Ki),keys:a?h:o(Cn),entries:o(On)},n)for(S in p)(Ji||d||!(S in l))&&In(l,S,p[S]);else zf({target:e,proto:!0,forced:Ji||d},p);return n&&l[lr]!==h&&In(l,lr,h,{name:r}),Dn[e]=h,p},ip=function(i,e){return{value:i,done:e}},sp=Ci,wa=cl,Ln=si,kd=nd,rp=Lt.f,ap=tp,Xi=ip,np=sd,op=ht,Pd="Array Iterator",dp=kd.set,up=kd.getterFor(Pd);ap(Array,"Array",function(i,e){dp(this,{type:Pd,target:sp(i),index:0,kind:e})},function(){var i=up(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Xi(void 0,!0)):t=="keys"?Xi(s,!1):t=="values"?Xi(e[s],!1):Xi([s,e[s]],!1)},"values");var xn=Ln.Arguments=Ln.Array;wa();wa();wa();if(!np&&op&&xn.name!=="values")try{rp(xn,"name",{value:"values"})}catch(i){}var lp=ke,cp=si,hp=lp("iterator"),fp=Array.prototype,pp=function(i){return i!==void 0&&(cp.Array===i||fp[hp]===i)},vp=xi,Nn=Os,mp=Di,Sp=si,gp=ke,bp=gp("iterator"),Rd=function(i){if(!mp(i))return Nn(i,bp)||Nn(i,"@@iterator")||Sp[vp(i)]},yp=Le,Tp=Nt,Ep=ft,$p=Cs,Ap=Rd,_p=TypeError,wp=function(i,e){var t=arguments.length<2?Ap(i):e;if(Tp(t))return Ep(yp(t,i));throw _p($p(i)+" is not iterable")},kp=Le,Bn=ft,Pp=Os,Rp=function(i,e,t){var s,r;Bn(i);try{if(s=Pp(i,"return"),!s){if(e==="throw")throw t;return t}s=kp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Bn(s),t},Ip=Ns,Dp=Le,Cp=ft,Op=Cs,Lp=pp,xp=Ea,Mn=Is,Np=wp,Bp=Rd,Un=Rp,Mp=TypeError,vs=function(i,e){this.stopped=i,this.result=e},Fn=vs.prototype,ka=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=Ip(e,s),d,l,c,h,f,m,p,S=function(T){return d&&Un(d,"normal",T),new vs(!0,T)},g=function(T){return r?(Cp(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=i.iterator;else if(n)d=i;else{if(l=Bp(i),!l)throw Mp(Op(i)+" is not iterable");if(Lp(l)){for(c=0,h=xp(i);h>c;c++)if(f=g(i[c]),f&&Mn(Fn,f))return f;return new vs(!1)}d=Np(i,l)}for(m=a?i.next:d.next;!(p=Dp(m,d)).done;){try{f=g(p.value)}catch(T){Un(d,"throw",T)}if(typeof f=="object"&&f&&Mn(Fn,f))return f}return new vs(!1)},Up=ma,Fp=Lt,Vp=xs,Hp=function(i,e,t){var s=Up(e);s in i?Fp.f(i,s,Vp(0,t)):i[s]=t},Gp=We,Yp=ka,qp=Hp;Gp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Yp(e,function(s,r){qp(t,s,r)},{AS_ENTRIES:!0}),t}});var jp=pa,zp=jp.Object.fromEntries,Wp={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},Qp=Wp,Jp=we,Kp=xi,Xp=Oi,Vn=si,Zp=ke,Hn=Zp("toStringTag");for(var cr in Qp){var Gn=Jp[cr],hr=Gn&&Gn.prototype;hr&&Kp(hr)!==Hn&&Xp(hr,Hn,cr),Vn[cr]=Vn.Array}var ev=zp,tv=ev,iv=tv,sv=iv,Ni=sv,rv=Ii,Bs=typeof process!="undefined"&&rv(process)=="process",av=xt,nv=Lt,ov=ke,dv=ht,Yn=ov("species"),uv=function(i){var e=av(i),t=nv.f;dv&&e&&!e[Yn]&&t(e,Yn,{configurable:!0,get:function(){return this}})},lv=Is,cv=TypeError,hv=function(i,e){if(lv(e,i))return i;throw cv("Incorrect invocation")},fv=Ge,pv=Te,Xr=va,vv=fv(Function.toString);pv(Xr.inspectSource)||(Xr.inspectSource=function(i){return vv(i)});var Id=Xr.inspectSource,mv=Ge,Sv=He,Dd=Te,gv=xi,bv=xt,yv=Id,Cd=function(){},Tv=[],Od=bv("Reflect","construct"),Pa=/^\s*(?:class|function)\b/,Ev=mv(Pa.exec),$v=!Pa.exec(Cd),Si=function(e){if(!Dd(e))return!1;try{return Od(Cd,Tv,e),!0}catch(t){return!1}},Ld=function(e){if(!Dd(e))return!1;switch(gv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return $v||!!Ev(Pa,yv(e))}catch(t){return!0}};Ld.sham=!0;var Av=!Od||Sv(function(){var i;return Si(Si.call)||!Si(Object)||!Si(function(){i=!0})||i})?Ld:Si,_v=Av,wv=Cs,kv=TypeError,Pv=function(i){if(_v(i))return i;throw kv(wv(i)+" is not a constructor")},qn=ft,Rv=Pv,Iv=Di,Dv=ke,Cv=Dv("species"),xd=function(i,e){var t=qn(i).constructor,s;return t===void 0||Iv(s=qn(t)[Cv])?e:Rv(s)},Ov=Ge,Lv=Ov([].slice),xv=TypeError,Nv=function(i,e){if(i<e)throw xv("Not enough arguments");return i},Bv=Ds,Nd=/(?:ipad|iphone|ipod).*applewebkit/i.test(Bv),Ce=we,Mv=dd,Uv=Ns,jn=Te,Fv=tt,Bd=He,zn=Sd,Vv=Lv,Wn=fa,Hv=Nv,Gv=Nd,Yv=Bs,Zr=Ce.setImmediate,ea=Ce.clearImmediate,qv=Ce.process,fr=Ce.Dispatch,jv=Ce.Function,Qn=Ce.MessageChannel,zv=Ce.String,pr=0,Ti={},Jn="onreadystatechange",Pi,Pt,vr,mr;Bd(function(){Pi=Ce.location});var Ra=function(i){if(Fv(Ti,i)){var e=Ti[i];delete Ti[i],e()}},Sr=function(i){return function(){Ra(i)}},Kn=function(i){Ra(i.data)},Xn=function(i){Ce.postMessage(zv(i),Pi.protocol+"//"+Pi.host)};(!Zr||!ea)&&(Zr=function(e){Hv(arguments.length,1);var t=jn(e)?e:jv(e),s=Vv(arguments,1);return Ti[++pr]=function(){Mv(t,void 0,s)},Pt(pr),pr},ea=function(e){delete Ti[e]},Yv?Pt=function(i){qv.nextTick(Sr(i))}:fr&&fr.now?Pt=function(i){fr.now(Sr(i))}:Qn&&!Gv?(vr=new Qn,mr=vr.port2,vr.port1.onmessage=Kn,Pt=Uv(mr.postMessage,mr)):Ce.addEventListener&&jn(Ce.postMessage)&&!Ce.importScripts&&Pi&&Pi.protocol!=="file:"&&!Bd(Xn)?(Pt=Xn,Ce.addEventListener("message",Kn,!1)):Jn in Wn("script")?Pt=function(i){zn.appendChild(Wn("script"))[Jn]=function(){zn.removeChild(this),Ra(i)}}:Pt=function(i){setTimeout(Sr(i),0)});var Md={set:Zr,clear:ea},Ud=function(){this.head=null,this.tail=null};Ud.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 Fd=Ud,Wv=Ds,Qv=/ipad|iphone|ipod/i.test(Wv)&&typeof Pebble!="undefined",Jv=Ds,Kv=/web0s(?!.*chrome)/i.test(Jv),Ot=we,Zn=Ns,Xv=ba.f,gr=Md.set,Zv=Fd,em=Nd,tm=Qv,im=Kv,br=Bs,eo=Ot.MutationObserver||Ot.WebKitMutationObserver,to=Ot.document,io=Ot.process,Zi=Ot.Promise,so=Xv(Ot,"queueMicrotask"),ta=so&&so.value,Yt,yr,Tr,es,ro;if(!ta){var ts=new Zv,is=function(){var i,e;for(br&&(i=io.domain)&&i.exit();e=ts.get();)try{e()}catch(t){throw ts.head&&Yt(),t}i&&i.enter()};!em&&!br&&!im&&eo&&to?(yr=!0,Tr=to.createTextNode(""),new eo(is).observe(Tr,{characterData:!0}),Yt=function(){Tr.data=yr=!yr}):!tm&&Zi&&Zi.resolve?(es=Zi.resolve(void 0),es.constructor=Zi,ro=Zn(es.then,es),Yt=function(){ro(is)}):br?Yt=function(){io.nextTick(is)}:(gr=Zn(gr,Ot),Yt=function(){gr(is)}),ta=function(i){ts.head||Yt(),ts.add(i)}}var sm=ta,rm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Ia=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},am=we,ri=am.Promise,Vd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",nm=Vd,om=Bs,dm=!nm&&!om&&typeof window=="object"&&typeof document=="object",um=we,Ei=ri,lm=Te,cm=fd,hm=Id,fm=ke,pm=dm,vm=Vd,Er=Zo,ao=Ei&&Ei.prototype,mm=fm("species"),ia=!1,Hd=lm(um.PromiseRejectionEvent),Sm=cm("Promise",function(){var i=hm(Ei),e=i!==String(Ei);if(!e&&Er===66||!(ao.catch&&ao.finally))return!0;if(!Er||Er<51||!/native code/.test(i)){var t=new Ei(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[mm]=s,ia=t.then(function(){})instanceof s,!ia)return!0}return!e&&(pm||vm)&&!Hd}),Bi={CONSTRUCTOR:Sm,REJECTION_EVENT:Hd,SUBCLASSING:ia},ai={},no=Nt,gm=TypeError,bm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw gm("Bad Promise constructor");e=s,t=r}),this.resolve=no(e),this.reject=no(t)};ai.f=function(i){return new bm(i)};var ym=We,Es=Bs,yt=we,Mi=Le,Tm=$a,Em=_a,$m=uv,Am=Nt,sa=Te,_m=ct,wm=hv,km=xd,Gd=Md.set,Da=sm,Pm=rm,Rm=Ia,Im=Fd,Yd=nd,ra=ri,Ca=Bi,qd=ai,Ms="Promise",jd=Ca.CONSTRUCTOR,Dm=Ca.REJECTION_EVENT;Ca.SUBCLASSING;var $r=Yd.getterFor(Ms),Cm=Yd.set,Om=ra&&ra.prototype,Wt=ra,Ar=Om,zd=yt.TypeError,aa=yt.document,Oa=yt.process,na=qd.f,Lm=na,xm=!!(aa&&aa.createEvent&&yt.dispatchEvent),Wd="unhandledrejection",Nm="rejectionhandled",oo=0,Qd=1,Bm=2,La=1,Jd=2,ss,uo,Mm,Kd=function(i){var e;return _m(i)&&sa(e=i.then)?e:!1},Xd=function(i,e){var t=e.value,s=e.state==Qd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===Jd&&Fm(e),e.rejection=La),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(zd("Promise-chain cycle")):(d=Kd(u))?Mi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Zd=function(i,e){i.notified||(i.notified=!0,Da(function(){for(var t=i.reactions,s;s=t.get();)Xd(s,i);i.notified=!1,e&&!i.rejection&&Um(i)}))},eu=function(i,e,t){var s,r;xm?(s=aa.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),yt.dispatchEvent(s)):s={promise:e,reason:t},!Dm&&(r=yt["on"+i])?r(s):i===Wd&&Pm("Unhandled promise rejection",t)},Um=function(i){Mi(Gd,yt,function(){var e=i.facade,t=i.value,s=lo(i),r;if(s&&(r=Rm(function(){Es?Oa.emit("unhandledRejection",t,e):eu(Wd,e,t)}),i.rejection=Es||lo(i)?Jd:La,r.error))throw r.value})},lo=function(i){return i.rejection!==La&&!i.parent},Fm=function(i){Mi(Gd,yt,function(){var e=i.facade;Es?Oa.emit("rejectionHandled",e):eu(Nm,e,i.value)})},Qt=function(i,e,t){return function(s){i(e,s,t)}},Kt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Bm,Zd(i,!0))},oa=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw zd("Promise can't be resolved itself");var s=Kd(e);s?Da(function(){var r={done:!1};try{Mi(s,e,Qt(oa,r,i),Qt(Kt,r,i))}catch(a){Kt(r,a,i)}}):(i.value=e,i.state=Qd,Zd(i,!1))}catch(r){Kt({done:!1},r,i)}}};jd&&(Wt=function(e){wm(this,Ar),Am(e),Mi(ss,this);var t=$r(this);try{e(Qt(oa,t),Qt(Kt,t))}catch(s){Kt(t,s)}},Ar=Wt.prototype,ss=function(e){Cm(this,{type:Ms,done:!1,notified:!1,parent:!1,reactions:new Im,rejection:!1,state:oo,value:void 0})},ss.prototype=Tm(Ar,"then",function(e,t){var s=$r(this),r=na(km(this,Wt));return s.parent=!0,r.ok=sa(e)?e:!0,r.fail=sa(t)&&t,r.domain=Es?Oa.domain:void 0,s.state==oo?s.reactions.add(r):Da(function(){Xd(r,s)}),r.promise}),uo=function(){var i=new ss,e=$r(i);this.promise=i,this.resolve=Qt(oa,e),this.reject=Qt(Kt,e)},qd.f=na=function(i){return i===Wt||i===Mm?new uo(i):Lm(i)});ym({global:!0,constructor:!0,wrap:!0,forced:jd},{Promise:Wt});Em(Wt,Ms,!1,!0);$m(Ms);var Vm=ke,tu=Vm("iterator"),iu=!1;try{var Hm=0,co={next:function(){return{done:!!Hm++}},return:function(){iu=!0}};co[tu]=function(){return this},Array.from(co,function(){throw 2})}catch(i){}var Gm=function(i,e){if(!e&&!iu)return!1;var t=!1;try{var s={};s[tu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Ym=ri,qm=Gm,jm=Bi.CONSTRUCTOR,su=jm||!qm(function(i){Ym.all(i).then(void 0,function(){})}),zm=We,Wm=Le,Qm=Nt,Jm=ai,Km=Ia,Xm=ka,Zm=su;zm({target:"Promise",stat:!0,forced:Zm},{all:function(e){var t=this,s=Jm.f(t),r=s.resolve,a=s.reject,n=Km(function(){var o=Qm(t.resolve),u=[],d=0,l=1;Xm(e,function(c){var h=d++,f=!1;l++,Wm(o,t,c).then(function(m){f||(f=!0,u[h]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),s.promise}});var eS=We,tS=Bi.CONSTRUCTOR,ho=ri;ho&&ho.prototype;eS({target:"Promise",proto:!0,forced:tS,real:!0},{catch:function(i){return this.then(void 0,i)}});var iS=We,sS=Le,rS=Nt,aS=ai,nS=Ia,oS=ka,dS=su;iS({target:"Promise",stat:!0,forced:dS},{race:function(e){var t=this,s=aS.f(t),r=s.reject,a=nS(function(){var n=rS(t.resolve);oS(e,function(o){sS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var uS=We,lS=Le,cS=ai,hS=Bi.CONSTRUCTOR;uS({target:"Promise",stat:!0,forced:hS},{reject:function(e){var t=cS.f(this);return lS(t.reject,void 0,e),t.promise}});var fS=ft,pS=ct,vS=ai,ru=function(i,e){if(fS(i),pS(e)&&e.constructor===i)return e;var t=vS.f(i),s=t.resolve;return s(e),t.promise},mS=We,SS=xt,gS=sd,bS=ri,yS=Bi.CONSTRUCTOR,TS=ru,ES=SS("Promise"),$S=!yS;mS({target:"Promise",stat:!0,forced:gS},{resolve:function(e){return TS($S&&this===ES?bS:this,e)}});var AS=We,da=ri,_S=He,wS=xt,kS=Te,PS=xd,fo=ru,RS=da&&da.prototype,IS=!!da&&_S(function(){RS.finally.call({then:function(){}},function(){})});AS({target:"Promise",proto:!0,real:!0,forced:IS},{finally:function(i){var e=PS(this,wS("Promise")),t=kS(i);return this.then(t?function(s){return fo(e,i()).then(function(){return s})}:i,t?function(s){return fo(e,i()).then(function(){throw s})}:i)}});var DS=xt,xa=DS,CS=xa,OS=CS("Promise","finally"),LS=OS,xS=LS,NS=xS,BS=NS,Us=BS,Xt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Xt||(Xt={}));var Zt=(i,e=0,t=Xt.OFFSET_P)=>{switch(t){case Xt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Xt.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:x(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 ze={[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}},ms=(i,e)=>ze[i].height>ze[e].height,MS=(i,e)=>ze[i].height>=ze[e].height,$i=(i,e)=>ze[i].height<ze[e].height,US=(i,e)=>ze[i].height<=ze[e].height,FS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:$i(e,t)?1:-1)[0],VS=Object.keys(ze).sort((i,e)=>$i(i,e)?-1:1),Bt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return VS.find(r=>{const a=ze[r];return a.width>=s&&a.height>=t})},HS=i=>ze[i].height,$s=i=>i===ne.INVARIANT;class le{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=L(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=L(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||w(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 GS=i=>{switch(i){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return x(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const YS=5,qS=5,jS=500,po=7e3;class zS{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new le(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===H.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:x(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:x(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:x(s)}break}default:x(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(GS(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new se;this.subscription.add(e),this.subscription.add(L(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 O;e.add(r.pipe(Ve(jS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(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===H.Applying||Math.abs(o-a)>YS)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(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<qS&&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:x(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=L(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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:H.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 b.MPEG:{const l=s[e];P(l);const c=FS(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=s[e];P(l),r=Zt(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(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 w(u)&&(o.metadata.title=u),w(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===H.Applying||s.state===H.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(Gu(po).subscribe(()=>a(`timeout(${po})`)))});Us(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.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:C.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class vo{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 au extends vo{constructor(){super(),this.listeners||vo.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 nu=class{constructor(){Object.defineProperty(this,"signal",{value:new au,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&&(nu.prototype[Symbol.toStringTag]="AbortController",au.prototype[Symbol.toStringTag]="AbortSignal");function ou(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 WS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!ou({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,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Fs=ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),du=Fs?WS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ei=Fs?du.fetch:window.fetch;Fs?du.Request:window.Request;const It=Fs?nu:window.AbortController,gi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Ai{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return ue(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]=gi(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(gi),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,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var f,m;throw(m=(f=this.params).onError)===null||m===void 0||m.call(f,{id:"BigRequestParsing",category:C.PARSER,message:"Error parsing response data",thrown:h}),h};return ei(o,{signal:d}).then(h=>{var f,m,p;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,g);const T=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;l.data=new ArrayBuffer(I);const _=new Uint8Array(l.data),A=({done:N,value:X})=>ue(this,void 0,void 0,function*(){N?this.onBigRequestProgress(l):X&&(_.set(X,l.loaded),l.loaded+=X.byteLength,this.onBigRequestProgress(l),yield T==null?void 0:T.read().then(A,Ai.suppressStreamErrors).catch(c))});T==null||T.read().then(A,Ai.suppressStreamErrors).catch(c)},Ai.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,l,c,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,[T,I]=gi(g),_=T>=t&&I<=t+r,A=t>=T&&t+r<I,N=a.slice(T-t,Math.min(I-t+1,r));if((_||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),_){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(Y=>Y!==S)),(c=S.success)===null||c===void 0||c.call(S,N,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,F])=>`${Y}: ${F}`).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:C.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=gi(l.request);(c>=t&&c<s||h>t&&h<=s)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to: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]=gi(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 As{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(As.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;As.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const QS=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new As(r,e,s)}}),JS=(i,e)=>{const t=new Ai(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return QS(n,t)}}},!0),()=>t.destroy()};var KS=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)},XS=i=>{const e=new y(1/0),t=new O,s=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,p;const S=Ni(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),_=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=_!=null?_:I*1e3)!==null&&f!==void 0?f:NaN;w(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:wi.HTTP1,T=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(g),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);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 c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ti=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},ZS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ti}),!0),eg=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 et=(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(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},Mt=(i,e,t)=>et(e,()=>i.loop,s=>{w(s)&&(i.loop=s)},{onError:t}),pt=(i,e,t,s)=>et(e,()=>({muted:i.muted,volume:i.volume}),r=>{w(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)=>et(e,()=>i.playbackRate,r=>{w(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),tg=i=>["__",i.language,i.label].join("|"),ig=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class it{constructor(){this.available$=new O,this.current$=new y(void 0),this.error$=new O,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:C.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(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{w(a)&&this.setExternal(a)},{equal:(a,n)=>w(a)&&w(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(et(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(et(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(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(L(U(e,"addtrack"),U(e,"removetrack"),Oe(["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(L(U(e,"change"),Oe(["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(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,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((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(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;w(t.align)&&(r.align=t.align),w(t.position)&&(r.position=t.position),w(t.size)&&(r.size=t.size),w(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(it.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:tg(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))w(e)&&ig(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 vt=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 Na{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 uu=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const ua=3;class sg{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<ua&&(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||ua))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 lu=(i,e,t=ua)=>{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 rg=50,ag=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,mt=i=>{const e=m=>U(i,m).pipe(Ct(void 0)),s=L(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>U(i,m))).pipe($(m=>m.type==="ended"?i.readyState<2:i.readyState<3),me()),r=L(U(i,"progress"),U(i,"timeupdate")).pipe($(()=>lu(i.buffered,i.currentTime))),a=uu()?dt({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Ct(void 0)):e("playing"),n=U(i,"playing").pipe(Ve(rg),$(()=>ag(i))),o=U(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe($(()=>i.playbackRate)),d=U(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var m;const p=i.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),l=U(i,"timeupdate").pipe($(()=>i.currentTime)),c=new O,h=.3;let f;return l.subscribe(m=>{i.loop&&w(f)&&w(m)&&f>=i.duration-h&&m<=h&&c.next(f),f=m}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},Ba=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var ng=We,og=Ls,dg=Ea,ug=Ta;ng({target:"Array",proto:!0},{at:function(e){var t=og(this),s=dg(t),r=ug(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var lg=xa,cg=lg("Array","at"),hg=cg,fg=hg,pg=fg,vg=pg,at=vg;let Ma=!1,nt={};const mg=i=>{Ma=i},Sg=()=>{nt={}},gg=i=>{i(nt)},rs=(i,e)=>{var t;Ma&&(nt.meta=(t=nt.meta)!==null&&t!==void 0?t:{},nt.meta[i]=e)};class Ze{constructor(e){this.name=e}next(e){var t,s;if(!Ma)return;nt.series=(t=nt.series)!==null&&t!==void 0?t:{};const r=(s=nt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),nt.series[this.name]=r}}const bg=new Ze("best_bitrate"),yg=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class Tg{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ui=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l: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&&w(o)?o:1,T=i.filter(V=>!$s(V.quality)).sort((V,B)=>ms(V.quality,B.quality)?-1:1),I=(c=at(T,-1))===null||c===void 0?void 0:c.quality,_=(h=at(T,0))===null||h===void 0?void 0:h.quality,A=K(r)||w(r.min)&&w(r.max)&&$i(r.max,r.min)||w(r.min)&&_&&ms(r.min,_)||w(r.max)&&I&&$i(r.max,I),N=g*yg(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=T.filter(V=>{const B=S?$i(V.quality,S):!0,ie=w(t)&&isFinite(t)&&w(V.bitrate)?t-a>=V.bitrate*N:!0,ce=s.lazyQualitySwitch&&w(s.minBufferToSwitchUp)&&u&&!$s(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&ms(V.quality,u.quality),Se=A||(K(r.max)||US(V.quality,r.max))&&(K(r.min)||MS(V.quality,r.min));return B&&ie&&!ce&&Se})[0];Y&&Y.bitrate&&bg.next(Y.bitrate);const F=(f=Y!=null?Y:T[Math.ceil((T.length-1)/2)])!==null&&f!==void 0?f:i[0],Z=F&&d&&d.history[F.id]&&pe()-d.history[F.id]<=s.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!Z&&d.recordSelection(F),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(F),F};var Re=i=>new URL(i).hostname;const Eg=300,_s=(i,e=Eg)=>new Ri(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(ju(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),w(u)&&w(d)&&t.next({width:u,height:d})},e));return a.observe(i),()=>a.disconnect()}),$g=5e3,bi={};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 Ri(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class mo{constructor(e){this.subscription=new se,this.videoState=new le(z.DOWNLOADING_LIB),this.textTracksManager=new it,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new Na,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===H.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:x(t)}break}case v.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:x(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:x(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:x(t)}break}default:x(s)}},this.video=vt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(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:C.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"),$g);Us(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(bi.MediaPlayer=r.MediaPlayer,bi.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(bi.MediaPlayer,"dashjs not loaded"),P(bi.Debug,"dashjs not loaded"),this.player=bi.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?Ba(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=JS(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&&eg(this.player),KS(this.player),this.params.tuning.requestQuick&&ZS(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:C.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,s));r(_s(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(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:p})=>p===z.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(et(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:T})=>T.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:T})=>T.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(et(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,T;const I=this.player.getDashMetrics(),_=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:wi.HTTP1,N=(T={1:!0,0:!1}[_])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Re(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 T=this.player.getQualityFor("video");let I;for(const _ of this.player.getBitrateInfoListFor("video")){const A=_.qualityIndex.toString(10),N=Bt(_),X=_.bitrate/1e3,Y={width:_.width,height:_.height},F=this.frameRatesByFrameHeight[_.height];if(N){const Z={id:A,quality:N,bitrate:X,size:Y,fps:F};this.videoTracks.push({track:Z,bitrateInfo:_}),_.qualityIndex===T&&(I=Z)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:_})=>_)),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(L(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=Ui(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(dt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(w))}).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(dt({availableFrom:this.availableFrom$.pipe(j(w)),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($(()=>lu(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(_s(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=XS(this.player);r(l,this.params.output.httpConnectionType$),r(c,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(dt({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}=mt(this.video);this.subscription.add(pt(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=Zt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Xt.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 Fi=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=>ue(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 cu(i){return Ae()-i}function So(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 Ag(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Ss(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,p=2e3,S=()=>{if(u)return;P(l);const B=cu(l);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),T=B=>(c=B,V),I=()=>(f="json",V),_=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,c&&c(),t&&t()}},A=B=>(h=B,V),N=()=>{l=Ae(),n=new r,n.open("get",i);let B=0,ie,ce=0;const Se=()=>(P(l),Math.max(l,Math.max(ie||0,ce||0)));if(a&&n.addEventListener("progress",k=>{const G=Ae();a.updateChunk&&k.loaded>B&&(a.updateChunk(Se(),k.loaded-B),B=k.loaded,ie=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>_())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const G=n.response.byteLength-B;G&&a.updateChunk&&a.updateChunk(Se(),G)}c&&c(),n&&e(n.response)}else _()}),n.addEventListener("error",()=>{_()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=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)=>(w(B)&&(p=B),w(ie)&&(m=ie),V),withTimeout:B=>(o=B,V),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}const _g=100,wg=2e3,kg=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-kg;if(t-e>wg){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>_g&&(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 Rg{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=Ss(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 as=1e4,ns=3,Ig=300,Dg=2e3,Cg=6e4,Og=10,Lg=1,xg=500;class Ng{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=So(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=So(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||w(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=()=>{Ag(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 Rg(ns,as,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,l=!1;const c=()=>{const _=a&&(!l||l===this.rep);return _||t("Not running!"),_},h=(_,A,N)=>{u&&u.abort(),u=Ss(this.urlResolver.resolve(_,!1),A,N,()=>this._retryCallback()).withTimeout(as).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ns).withFinally(()=>{u=null}).send()},f=(_,A,N)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(_,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=_=>{const A=s.playbackRate;s.playbackRate!==_&&(t(`Playback rate switch: ${A}=>${_}`),s.playbackRate=_)},p=_=>{this.lowLatency=_,t(`lowLatency changed to ${_}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let _=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const N=Ae()-1e4;let X=0;for(let F=0;F<this.bufferStates.length;F++){const Z=this.bufferStates[F];_=Math.min(_,Z.buf),Z.ts<N&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${_} drop=${X} jitter=${this.sourceJitter}`);let Y=_-Lg;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=_=>{let A;const N=()=>A&&A.start?A.start.length:0,X=k=>A.start[k]/1e3,Y=k=>A.dur[k]/1e3,F=k=>A.fragIndex+k,Z=(k,G)=>({chunkIdx:F(k),startTS:X(k),dur:Y(k),discontinuity:G}),V=()=>{let k=0;if(A&&A.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=G;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 G=N();if(!(G<=0)){if(w(k)){for(let oe=0;oe<G;oe++)if(X(oe)>k)return Z(oe)}return V()}},ie=k=>{const G=N(),oe=k?k.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(G<=0)){if(!k||ve<0||ve-G>Og)return t(`Resync: offset=${ve} bChunks=${G} chunk=`+JSON.stringify(k)),V();if(!(ve>=G))return Z(oe-A.fragIndex,!1)}},ce=(k,G,oe)=>{d&&d.abort(),d=Ss(this.urlResolver.resolve(k,!0,this.lowLatency),G,oe,()=>this._retryCallback()).withTimeout(as).withRetryCount(ns).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,G)=>{ce(_,oe=>{if(!c())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&p(ve);let ge=0;for(let Ie=0;Ie<A.dur.length;++Ie)ge+=A.dur[Ie];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(G))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:_=>{const{videoElement:A,logger:N}=this.params;let X=g(e.jidxUrl),Y,F,Z,V,B=0,ie,ce,Se;const k=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(xg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+ee,Pe=Ae(),xe=Math.min(1e4,Ee-Pe);B=Pe;const $t=()=>{d||c()&&X.seek(()=>{c()&&(B=Ae(),G(),k())})};xe>0?ie=window.setTimeout(()=>{this.paused?k():$t()},xe):$t()},G=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,Qe(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}Ie(Ee)}else k()},oe=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let Pe,xe,$t;const Je=St=>{window.setTimeout(()=>{c()&&oe(ee,Ee)},St)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Je(100);else{const St=Ae(),At=A.currentTime;!this.paused&&A.buffered.length>1&&ce===At&&St-Se>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),ce!==At&&(ce=At,Se=St);const oi=this._getBufferSizeSec();if(oi>30)N(`Buffered ${oi} seconds; delaying appendBuffer`),Je(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:oi}),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&&(Pe=this.sourceBuffer.buffered.start(0),xe=At,xe-Pe>4&&this.sourceBuffer.remove(Pe,xe-3)),Je(1e3);else throw Ut}}},ve=()=>{F&&Y&&(N([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Z)]),oe(F,function(){F=null,G()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ie=ee=>{c()&&f(ge(ee),(Ee,Pe)=>{if(c()){if(Pe/=1e3,F=Ee,Z=ee,n=ee.startTS,Pe){const xe=Math.min(10,ee.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ve()}},()=>this._handleNetworkError())},Qe=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},ni=ee=>{c()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(c()){if(B=Ae(),!ee){k();return}V=ee,!K(_)||ee.startTS>_?Ie(ee):(Z=ee,G())}},_),e.cachedHeader?ni(e.cachedHeader):h(e.headerUrl,ni,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),w(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 w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/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(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},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 c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&cu(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Ae();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Ss(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(as).withRetryCount(ns).withRetryInterval(Ig,Dg).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))},Cg))}_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 Bg=[W.PAUSED,W.PLAYING,W.READY],Mg=[W.PAUSED,W.PLAYING,W.READY];class Ug{constructor(e){this.subscription=new se,this.videoState=new le(W.STOPPED),this.representations$=new y([]),this.textTracksManager=new it,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Na,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:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Fi(c.name))!==null&&n!==void 0?n:Bt(c.video),m=c.bitrate/1e3,p=Object.assign({},c.video);if(!f)continue;const S={id:h,quality:f,bitrate:m,size:p};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),w(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===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(Mg.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;w(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==v.PAUSED&&d.state===H.Requested&&Bg.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(Zt(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 l=u==null?void 0:u.from;l&&l===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 x(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};L(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=vt(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=mt(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===H.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(dt({zeroTime:this.zeroTime$.pipe(j(w)),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(pt(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&&HS(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 x(r.to)}},t)).add(L(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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 Ng({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(),l=!d&&w(u)?u:(a=Ui(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const 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(Zt(this.params.source.url,s))}}var hu=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 Fg=i=>{const e=document.createElement("a");return e.href=i,e.origin},Vg=i=>{const e=document.createElement("a");return e.href=i,e.host};class fu{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 l=Ni(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var 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(Vg(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 ws{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 l=0,c=0,h=0;const f=p=>{r(ws._str2ua(p.substr(u))),u=p.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ti(m)),this._lastXhr=new fu(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),c===0){c=Date.now();return}h=p.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=p.length,c=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=ws._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 Hg{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=ti(s)),new fu(s,t,r=>{this.attachManifest(r,t,Fg(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,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,m,p,S,g,T,I,_,A,N,X,Y,F,Z,V,B;const ie=d.getElementsByTagName("SegmentBase")[0],ce=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],k=Se&&n(Se,"range").split("-");if(!k||!ce){const Qe=d.parentElement;if((Qe==null?void 0:Qe.getAttribute("contentType"))==="text"){const ni=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(s?s+"/":"")+((m=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ee=(p=Qe.getAttribute("lang"))!==null&&p!==void 0?p:void 0;ee&&u.push({id:ni,url:ee,language:Ee})}return}const G=.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 Ie=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ge=Ie?Ba(Ie):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((_=d.attributes.getNamedItem("height"))===null||_===void 0?void 0:_.value),bandwidth:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(ce[0]),indexTo:Number(ce[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:G*oe/8,bufferLength:G,name:(Z=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.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:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const 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 l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;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 c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-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 l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ws({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 Gg=[Q.PAUSED,Q.PLAYING];class Yg{constructor(e){this.videoState=new le(Q.STOPPED),this.subscription=new se,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new it,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new O,responseHeaders$:new O,manifestReady$:new O,representationPlay$:new O,error$:new O},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&&Fi(o.name))!==null&&a!==void 0?a:Bt(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:f,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(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===H.Requested&&Gg.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 x(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),L(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=vt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new sg(this.video),this.dash=new Hg({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:C.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:C.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=mt(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$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==H.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(pt(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(_s(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:C.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(L(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$,U(this.video,"progress")).pipe($(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=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&&w(f))g=f;else{const T=Rt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,_=Math.min(T/I,1);g=(u=Ui(c.map(({track:A})=>A),{container:p,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:_,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return w(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(dt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j(w))}).pipe(ye()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j(w),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(Re(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=hu(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(w)).subscribe(this.handleRepresentationPlay,s)).add(L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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 x(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 Me;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Me||(Me={}));var ks;(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"})(ks||(ks={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));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 ii;(function(i){i.MP4="mp4",i.WEBM="webm"})(ii||(ii={}));var la=(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 qg=(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)},jg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",go=jg?qg:window.requestIdleCallback;var _r,wr;let pu=!1;try{pu=uu()&&parseInt((wr=(_r=navigator.userAgent.match(/Version\/(\d+)/))===null||_r===void 0?void 0:_r[1])!==null&&wr!==void 0?wr:"",10)<16}catch(i){console.error(i)}class zg{constructor(e){this.bufferFull$=new O,this.error$=new O,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:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(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 ue(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 ue(this,void 0,void 0,function*(){return new Promise(t=>{let s;pu&&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:C.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:x(t)}}}var bo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const vu=new TextDecoder("ascii"),mu=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=vu.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}},Wg=i=>vu.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Qg=(i,e,t)=>{const s=mu(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(),l=n(),c=n(),h=n()&4294967295;let f=l/d*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+c;for(let p=0;p<h;p++){const S=n(),g=S>>>31,T=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const _=I/d*1e3;r.push({status:te.NONE,time:{from:f,to:f+_},byte:{from:m,to:m+T-1}}),f+=_,m+=T}return r},Jg=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=mu(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},Kg={validateData:Wg,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Qg,parseFeedableSegmentChunk:Jg};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 yo={[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}},Su=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=Ps(i,t),r=s in yo,a=r?yo[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,l=Ps(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ps=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(i,e)=>{switch(e){case D.SignedInteger:return i.getInt8(0);case D.UnsignedInteger:return Ps(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:x(e)}},Vi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Su(s);if(!e(r))return;r.type===D.Master&&Vi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Xg=i=>{if(i.getUint32(0)!==E.EBML)return!1;let e,t,s;const r=Su(i);return Vi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=ot(o,n):a===E.DocType?t=ot(o,n):a===E.DocTypeReadVersion&&(s=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},gu=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],Zg=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],eb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d;return Vi(i,({tag:l,type:c,value:h,valueSize:f})=>{if(l===E.SeekID){const m=ot(h,c);d=Ps(m)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?s=ot(h,c):l===E.Duration?r=ot(h,c):l===E.SeekPosition&&d===E.Cues?u=ot(h,c):a&&n&&gu.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),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}},tb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ib=(i,e)=>{let t=!1,s=!1;const r=o=>w(o.time)&&w(o.position),a=[];let n;return Vi(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=ot(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=ot(d,u));break;default:t&&gu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},sb=i=>{let e=0,t=!1;try{Vi(i,s=>s.tag===E.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Zg.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},rb={validateData:Xg,parseInit:eb,getIndexRange:tb,parseSegments:ib,parseFeedableSegmentChunk:sb};class To{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new O,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=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new zg(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.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,bo(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(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield M(void 0);let f=0;for(const m of h)m.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:m.time.from}),f=m.time.to;w(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield yield M(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(K(c)?yield yield M(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield M(c)),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal));const h=this.getCurrentPosition();w(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 ii.MP4:this.containerParser=Kg;break;case ii.WEBM:this.containerParser=rb;break;default:x(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 l=Rt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&bo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Rt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=at(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&Rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=at(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:c,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),T=this.preloadOnly&&h<=s+g||f<=s+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&S&&T&&this.sourceBuffer&&!la(this.sourceBuffer.buffered,s))&&S&&T});if(r===-1)return[];if(t!==Ue.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ue.BYTE_RANGE:{r=t.segmentReference.url,a={from:at(e,0).byte.from,to:at(e,-1).byte.to};break}case Ue.TEMPLATE:{const d=at(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:x(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 qe(u,function(){return je(this,arguments,function*(){const d=Qa(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&w(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:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),c.segment.status=te.FED,"size"in c.segment&&(c.segment.size=c.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===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=te.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Ue.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:l;if(c.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,T=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&T&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const _=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(_,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(m,r-S),c.loadedBytes>c.feedingBytes)){const _=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===m?_:this.containerParser.parseFeedableSegmentChunk(_);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)c.fedBytes+=A.byteLength,c.fedBytes===m&&o(c);else{if(c.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=go(()=>Us(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?qe(this.destroyAbortController.signal,function(){return je(this,arguments,function*(){const o=Qa(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,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ue(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 l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;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 l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const 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=go(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:C.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(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Jt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Jt||(Jt={}));class ab{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new It,this.subscription=new se,this.fetchManifest=qe(this.abortAllController.signal,function(r){return je(this,arguments,function*(){let a=r;this.requestQuic&&(a=ti(a));const n=yield yield M(ei(a,{signal:this.abortAllController.signal}).catch(yi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=qe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Jt.HEADER:Jt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,m;return je(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case Jt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Jt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:x(a)}this.requestQuic&&(p=ti(p));let g=this.abortAllController.signal;if(d){const k=new It;if(this.subscription.add(L(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{k.abort()}catch(G){yi(G)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(G){yi(G)}g=k.signal}const T=pe(),I=yield yield M(ei(p,{priority:u,headers:S,signal:g}).catch(yi)),_=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(_-T),!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()-_),o==null||o(new DataView(k),k.byteLength),yield M(k)}if(!o&&!l)return yield M(I.arrayBuffer());const[N,X]=I.body.tee(),Y=N.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let F=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),B=new DataView(Z);let ie=!1;const ce=k=>{ie=!0,yi(k)},Se=qe(g,function({done:k,value:G}){return je(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(pe()-T),g.aborted)return yield M(void 0);k?o==null||o(B,F):G&&(V.set(G,F),F+=G.byteLength,o==null||o(B,F),yield yield M(Y==null?void 0:Y.read().then(Se,ce)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,ce)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=qe(this.abortAllController.signal,function(r,a,n){var o;return je(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const p=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!p)return yield M(null);const S=new DataView(p,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!T)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(p,T.from-l,T.to-T.from+1);else{const A=yield yield M(this.fetch(r.url,{range:T,priority:n,measureThroughput:!1}));if(!A)return yield M(null);I=new DataView(A)}const _=a.parseSegments(I,g,T);return yield M({dataView:new DataView(p),segments:_})})}.bind(this)),this.fetchTemplateRepresentation=qe(this.abortAllController.signal,function(r,a){return je(this,arguments,function*(){if(r.type!==Ue.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}=hu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:x(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const yi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var nb=ct,ob=Ii,db=ke,ub=db("match"),lb=function(i){var e;return nb(i)&&((e=i[ub])!==void 0?!!e:ob(i)=="RegExp")},cb=xi,hb=String,fb=function(i){if(cb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return hb(i)},pb=ft,vb=function(){var i=pb(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},mb=Le,Sb=tt,gb=Is,bb=vb,Eo=RegExp.prototype,yb=function(i){var e=i.flags;return e===void 0&&!("flags"in Eo)&&!Sb(i,"flags")&&gb(Eo,i)?mb(bb,i):e},Ua=Ge,Tb=Ls,Eb=Math.floor,kr=Ua("".charAt),$b=Ua("".replace),Pr=Ua("".slice),Ab=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,_b=/\$([$&'`]|\d{1,2})/g,wb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=_b;return r!==void 0&&(r=Tb(r),u=Ab),$b(a,u,function(d,l){var c;switch(kr(l,0)){case"$":return"$";case"&":return i;case"`":return Pr(e,0,t);case"'":return Pr(e,n);case"<":c=r[Pr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Eb(h/10);return f===0?d:f<=o?s[f-1]===void 0?kr(l,1):s[f-1]+kr(l,1):d}c=s[h-1]}return c===void 0?"":c})},kb=We,Pb=Le,Fa=Ge,$o=ha,Rb=Te,Ib=Di,Db=lb,qt=fb,Cb=Os,Ob=yb,Lb=wb,xb=ke,Nb=xb("replace"),Bb=TypeError,bu=Fa("".indexOf),Mb=Fa("".replace),Ao=Fa("".slice),Ub=Math.max,_o=function(i,e,t){return t>i.length?-1:e===""?t:bu(i,e,t)};kb({target:"String",proto:!0},{replaceAll:function(e,t){var s=$o(this),r,a,n,o,u,d,l,c,h,f=0,m=0,p="";if(!Ib(e)){if(r=Db(e),r&&(a=qt($o(Ob(e))),!~bu(a,"g")))throw Bb("`.replaceAll` does not allow non-global regexes");if(n=Cb(e,Nb),n)return Pb(n,e,s,t);if(r)return Mb(qt(s),e,t)}for(o=qt(s),u=qt(e),d=Rb(t),d||(t=qt(t)),l=u.length,c=Ub(1,l),f=_o(o,u,0);f!==-1;)h=d?qt(t(u,f,o)):Lb(u,o,f,[],void 0,t),p+=Ao(o,m,f)+h,m=f+l,f=_o(o,u,f+c);return m<o.length&&(p+=Ao(o,m)),p}});var Fb=xa,Vb=Fb("String","replaceAll"),Hb=Vb,Gb=Hb,Yb=Gb,qb=Yb,wo=qb;const ko=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},Rr=(i,e)=>{let t=i;t=wo(t,"$$","$");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=wo(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jb=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,m,p,S,g,T,I,_,A,N,X,Y,F,Z,V,B,ie,ce,Se,k,G,oe,ve,ge,Ie,Qe;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},Pe=ee.children[0],xe=Pe.getElementsByTagName("Period")[0],$t=xe.children;let Je;const St=Pe.getAttribute("mediaPresentationDuration"),At=xe.getAttribute("duration");if(St)Je=ko(St);else if(At){const Ke=ko(At);w(Ke)&&(Je=Ke)}let oi=0;const Ut=(s=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],_u=Ut.includes(ks.WEBM_AS_IN_FFMPEG)||Ut.includes(ks.WEBM_AS_IN_SPEC)?ii.WEBM:ii.MP4;for(const Ke of $t){const Hi=Ke.getAttribute("mimeType"),wu=Ke.getAttribute("codecs"),Va=(r=Ke.getAttribute("contentType"))!==null&&r!==void 0?r:Hi==null?void 0:Hi.split("/")[0],ku=(n=(a=Ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Pu=Ke.querySelectorAll("Representation"),Ru=Ke.querySelector("SegmentTemplate");if(Va!=="text")for(const $e of Pu){const di=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Hi,Ha=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:wu)!==null&&d!==void 0?d:"",Gi=(c=(l=$e.getAttribute("contentType"))!==null&&l!==void 0?l:di==null?void 0:di.split("/")[0])!==null&&c!==void 0?c:Va,Iu=(f=(h=Ke.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],Du=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Ga=parseInt((p=$e.getAttribute("height"))!==null&&p!==void 0?p:"",10),Ya=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,qa=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Cu=(T=$e.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Ou=qa?Ba(qa):void 0,Lu=(I=$e.getAttribute("id"))!==null&&I!==void 0?I:(oi++).toString(10),xu=Gi==="video"?`${Ga}p`:Gi==="audio"?`${Ya}Kbps`:Ha,Nu=`${Lu}@${xu}`,Bu=(N=(A=(_=$e.querySelector("BaseURL"))===null||_===void 0?void 0:_.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",ja=new URL(Bu,e).toString(),Mu=[...Ut,...ku,...Iu];let Hs;const Uu=$e.querySelector("SegmentBase"),_t=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:Ru;if(Uu){const ui=(F=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&F!==void 0?F:"",[li,Ys]=ui.split("-").map(wt=>parseInt(wt,10)),ci={from:li,to:Ys},hi=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[qs,Yi]=hi?hi.split("-").map(wt=>parseInt(wt,10)):[],fi=hi?{from:qs,to:Yi}:void 0;Hs={type:Ue.BYTE_RANGE,url:ja,initRange:ci,indexRange:fi}}else if(_t){const ui={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(B=$e.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},li=parseInt((ie=_t.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),Ys=(ce=_t.getAttribute("initialization"))!==null&&ce!==void 0?ce:"",ci=_t.getAttribute("media"),hi=(k=parseInt((Se=_t.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&k!==void 0?k:1,qs=Rr(Ys,ui);if(!ci)throw new ReferenceError("No media attribute in SegmentTemplate");const Yi=(G=_t.querySelectorAll("SegmentTimeline S"))!==null&&G!==void 0?G:[],fi=[];if(Yi.length){let wt=hi,kt=0;for(const pi of Yi){const Ft=parseInt((oe=pi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,vi=parseInt((ve=pi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,mi=(Ie=parseInt((ge=pi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Ie!==void 0?Ie:void 0;for(let za=0;za<vi+1;za++){const Fu=Rr(ci,Object.assign(Object.assign({},ui),{segmentNumber:wt.toString(10),segmentTime:mi.toString(10)})),Vu=mi?mi/li:kt;kt+=Ft/li;const Hu=kt;wt++,fi.push({time:{from:Vu,to:Hu},url:Fu})}}}else if(w(Je)){const kt=parseInt((Qe=_t.getAttribute("duration"))!==null&&Qe!==void 0?Qe:"",10)/li*1e3,pi=Math.ceil(Je/kt);let Ft=0;for(let vi=1;vi<pi;vi++){const mi=Rr(ci,Object.assign(Object.assign({},ui),{segmentNumber:vi.toString(10),segmentTime:Ft.toString(10)}));fi.push({time:{from:Ft,to:Ft+kt},url:mi}),Ft+=kt}}Hs={type:Ue.TEMPLATE,baseUrl:ja,initUrl:qs,segments:fi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Gi||!di)continue;const Gs={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Gi];Gs&&Ee[Gs].push({id:Nu,kind:Gs,segmentReference:Hs,profiles:Mu,duration:Je,bitrate:Ya,mime:di,codecs:Ha,width:Du,height:Ga,fps:Ou,quality:Cu})}}return{duration:Je,container:_u,representations:Ee}},zb=["timeupdate","progress","play","seeked","stalled","waiting"];var Be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Be||(Be={}));let Wb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new le(Be.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new O,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new It,this.initManifest=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Be.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=jb(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Ni(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(Be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(Be.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 To(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],w(s)&&(this.audioBufferManager=new To(Me.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=L(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=L(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(L(this.forceEnded$,dt({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:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(L(...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)}))),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Be.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=Yu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ab({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Be.RUNNING),this.subscription.add(L(...zb.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&la(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ue(this,void 0,void 0,function*(){const s={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.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),la(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(Be.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 Qb=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Fi(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}},Jb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Kb=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=at(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:at(i,-1)};class Xb{constructor(e){this.subscription=new se,this.videoState=new le(he.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new it,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Tg,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===H.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 x(t)}}},this.params=e,this.video=vt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Wb({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=mt(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:C.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,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(s.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(w),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(pt(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(_s(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 l;if(d===Be.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((p,S)=>S.bitrate-p.bitrate),f=Array.from(c.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const S=Jb(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of f){const S=Qb(p);if(S){this.videoTracks.push({track:S,representation:p});const g=!this.params.tuning.isAudioDisabled&&Kb(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.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(l=this.audioRepresentations.get(m.id))===null||l===void 0?void 0:l.id)}else d===Be.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(L(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Be.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Me.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),$(d=>{var l;return d&&((l=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===v.READY),me());this.subscription.add(L(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(L(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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,l=this.params.output.currentVideoTrack$.getValue(),c=Rt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),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,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),p=Ui(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:l,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 ue(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 Zb=5e3,st={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const os=(i,e)=>new Ri(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class ey{constructor(e){this.subscription=new se,this.videoState=new le(J.INITIALIZING),this.textTracksManager=new it,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===H.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:x(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:x(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:x(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:x(t)}break;default:x(s)}},this.video=vt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(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:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Zb);Us(import("hls.js/dist/hls.min.js").then(r=>{e||(st.Hls=r.default,st.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(st.Hls,"hls.js not loaded"),this.hls=new st.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(st.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=mt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,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$),a(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Mt(this.video,e.isLooped,s)),this.subscription.add(pt(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(os(this.hls,st.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(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(os(this.hls,st.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:p,height:S}=c,g=(f=Fi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Bt({width:p,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(m,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(os(this.hls,st.Events.LEVEL_LOADING).pipe($(({url:d})=>Re(d))),t.hostname$),this.subscription.add(et(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 l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=os(this.hls,st.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(w)).subscribe(t.currentVideoTrack$,s),this.subscription.add(et(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(K(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.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=L(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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 ue(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 Po="X-Playback-Duration";var Ro=i=>ue(void 0,void 0,void 0,function*(){const e=yield ei(i,{method:"HEAD"});return e.headers.has(Po)?parseInt(e.headers.get(Po),10):void 0});const ty=i=>{let e=null;if(i.QUALITY&&(e=Fi(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},yu=(i,e=i)=>ue(void 0,void 0,void 0,function*(){var t;const a=(yield(yield ei(i)).text()).split(`
8
- `),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=Ni(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=ty(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let p;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(p={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,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 iy{constructor(e){var t;this.subscription=new se,this.videoState=new le(re.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),this.liveOffset=new Na,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===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 l=this.params.desiredState.seekState.getState();if(r===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==v.PAUSED&&l.state===H.Requested){this.videoState.startTransitionTo(re.READY),this.seek(l.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 x(r)}},this.params=e,this.video=vt(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]),yu(Zt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching: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(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=mt(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(pt(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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===re.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===H.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},s)),this.subscription.add(dt({startTime:this.manifestStartTime$.pipe(j(w)),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:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Oe(["init"])).pipe(Ve(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=Zt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Ro(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{ei(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();Ro(d).then(l=>{K(l)||this.maxSeekBackTime$.next(l)})}})}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 sy{constructor(e){this.subscription=new se,this.videoState=new le(de.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),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 l=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==v.PAUSED&&d.state===H.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 x(s)}},this.params=e,this.video=vt(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.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),yu(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.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(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(pt(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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===H.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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 ry{constructor(e){this.subscription=new se,this.videoState=new le(fe.STOPPED),this.trackUrls={},this.textTracksManager=new it,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===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==v.PAUSED&&o.state===H.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 x(t)}},this.params=e,this.video=vt(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.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=mt(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Mt(this.video,t.isLooped,s)),this.subscription.add(pt(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&&w(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=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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=ti(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Re(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 Io=["stun:videostun.mycdn.me:80"],ay=1e3,ny=3,Ir=()=>null;class oy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ir,this.externalStopCallback=Ir,this.externalErrorCallback=Ir,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 ue(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 ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Io}]};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 ue(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 ue(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:C.WTF,message:e.message})}onPeerConnectionStream(e){return ue(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 ue(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),ay)}normalizeOptions(e={}){const t={stunServerList:Io,maxRetryNumber:ny,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 dy{constructor(e){this.videoState=new le(ae.STOPPED),this.maxSeekBackTime$=new y(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 x(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=vt(e.container),this.liveStreamClient=new oy(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:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};L(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=mt(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===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(pt(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 x(n.to)}},s)).add(L(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality: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:C.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 Do{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 uy=()=>{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")},Dr,Cr,Or,Lr,xr,Nr,ds,Br,us,Mr,ls,Ur,cs,Fr,hs,Vr;const Tu=uy(),gt=document.createElement("video"),rt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Cr=(Dr=window.SourceBuffer)===null||Dr===void 0?void 0:Dr.prototype)===null||Cr===void 0?void 0:Cr.appendBuffer)),hls:Boolean(((Or=gt.canPlayType)===null||Or===void 0?void 0:Or.call(gt,"application/x-mpegurl"))||((Lr=gt.canPlayType)===null||Lr===void 0?void 0:Lr.call(gt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Ne={mp4:Boolean((xr=gt.canPlayType)===null||xr===void 0?void 0:xr.call(gt,"video/mp4")),webm:Boolean((Nr=gt.canPlayType)===null||Nr===void 0?void 0:Nr.call(gt,"video/webm")),cmaf:!0},bt={h264:Boolean((Br=(ds=window.MediaSource)===null||ds===void 0?void 0:ds.isTypeSupported)===null||Br===void 0?void 0:Br.call(ds,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Mr=(us=window.MediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||Mr===void 0?void 0:Mr.call(us,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Ur=(ls=window.MediaSource)===null||ls===void 0?void 0:ls.isTypeSupported)===null||Ur===void 0?void 0:Ur.call(ls,'video/webm; codecs="vp9"')),aac:Boolean((Fr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||Fr===void 0?void 0:Fr.call(cs,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Vr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||Vr===void 0?void 0:Vr.call(hs,'audio/webm; codecs="opus"'))},jt=(bt.h264||bt.h265)&&bt.aac,Vs=rt.hls&&Ne.mp4,ly=Boolean(window.WebSocket),cy=()=>Object.keys(bt).filter(i=>bt[i]),hy=(i,e=!1)=>i.filter(t=>{switch(t){case b.DASH:return rt.mse&&Ne.mp4&&jt;case b.DASH_SEP:return rt.mse&&Ne.mp4&&jt;case b.DASH_WEBM:return rt.mse&&Ne.webm&&bt.vp9&&bt.opus;case b.DASH_LIVE:return rt.mse&&Ne.mp4&&jt;case b.DASH_LIVE_CMAF:return rt.mse&&Ne.mp4&&jt&&Ne.cmaf;case b.DASH_ONDEMAND:return rt.mse&&Ne.mp4&&jt;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return Vs||e&&rt.mse&&Ne.mp4&&jt;case b.MPEG:return Ne.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return rt.webrtc&&ly&&bt.h264&&(Ne.mp4||Ne.webm);default:return x(t)}}),fy=()=>Tu?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:Vs?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],py=()=>Tu?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:Vs?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],Co=i=>i?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var vy=i=>new Ri(e=>{const t=new se,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$,n=new O;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 Oo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},my={cacheDuration:12e4},Sy={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},gy={maxPausedTime:3e4},Lo={maxPausedTime:3e4};class by{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),element$:new y(void 0)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=hy([...py(),...fy()],this.params.tuning.useHlsJs).filter(n=>w(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 Do(r);const a=[...Co(!0),...Co(!1)];this.chromecastFormatsIterator=new Do(a.filter(n=>w(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:C.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!==H.None;this.params.desiredState.seekState.setState({state:H.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 De.SCREEN:return this.createScreenProvider(t);case De.CHROMECAST:return this.createChromecastProvider(t);default:return x(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 b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new Yg(Object.assign(Object.assign({},n),{source:o,config:my}))}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new mo(Object.assign(Object.assign({},n),{source:o,format:e,config:Lo})):new Xb(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new mo(Object.assign(Object.assign({},n),{source:o,format:e,config:Lo}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Vs||!this.params.tuning.useHlsJs?new sy(Object.assign(Object.assign({},n),{source:o})):new ey(Object.assign(Object.assign({},n),{source:o}))}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new iy(Object.assign(Object.assign({},n),{source:o,config:gy}))}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new ry(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Ug(Object.assign(Object.assign({},n),{source:o,config:Sy}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new dy({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(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 zS({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()?De.CHROMECAST:De.SCREEN}chooseFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case De.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return x(e)}}skipFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.next();case De.CHROMECAST:return this.chromecastFormatsIterator.next();default:return x(e)}}handleNoFormatsError(e){switch(e){case De.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case De.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return x(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 Ni(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,s=0;return e.add(L(this.providerOutput.error$,vy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Oo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:C.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===De.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===C.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Oo.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 Fe;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Fe||(Fe={}));const Eu=new Map;let Dt=Fe.RUNTIME;const Hr=`vk-videoplayer-dummy-key-${Math.random()}`,yy=()=>{try{localStorage.setItem(Hr,"test"),localStorage.removeItem(Hr),Dt=Fe.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Hr),Dt=Fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Dt=Fe.RUNTIME;else throw e}else throw i}};yy();const Ty=i=>{var e,t;switch(Dt){case Fe.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Fe.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Fe.RUNTIME:return Eu.get(i);default:x(Dt)}},xo=(i,e)=>{switch(Dt){case Fe.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.RUNTIME:return void Eu.set(i,e);default:x(Dt)}},ca=(i,e,t)=>t*e+(1-t)*i,$u=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Ey=(i,e,t,s)=>{let r=0,a=t;const n=$u(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 Au{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ze(`raw_${s}`),this.smoothedSeries$=new Ze(`smoothed_${s}`),this.reportedSeries$=new Ze(`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 $y extends Au{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ca(this.slow,e,this.params.emaAlphaSlow),this.fast=ca(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ay extends Au{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=$u(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ca(this.emaSmoothed,e,this.params.emaAlpha);const s=Ey(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class No{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new $y({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Ay({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const _y=5e3,Bo="one_video_throughput",Mo="one_video_rtt",lt=window.navigator.connection,Uo=()=>{const i=lt==null?void 0:lt.downlink;if(w(i)&&i!==10)return i*1e3},Fo=()=>{const i=lt==null?void 0:lt.rtt;if(w(i)&&i!==3e3)return i},Vo=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class _i{constructor(e){var t,s;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=_i.load(Bo)||(e.useBrowserEstimation?Uo():void 0)||_y,a=(s=(t=_i.load(Mo))!==null&&t!==void 0?t:e.useBrowserEstimation?Fo():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(Vo(r,a,e.rttPenaltyRequestSize)),this.throughput=No.getSmoothedValue(r,-1,e),this.rtt=No.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Uo();u&&this.throughput.next(u);const d=Fo();w(d)&&this.rtt.next(d)};lt&&"onchange"in lt&&this.subscription.add(U(lt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{xo(Bo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{xo(Mo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dt({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Vo(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(U(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(U(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:l})=>ue(this,void 0,void 0,function*(){d?(this.addRawSpeed(s,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.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(_i.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=Ty(e);if(w(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Ho={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},wy=i=>{const e={};for(const t of Object.keys(Ho)){const s=Ho[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 ky=({seekState:i,position$:e})=>L(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===H.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),j(w)),e.pipe(j(()=>i.getState().state===H.None))),Py=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const Go=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new Ri(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===H.Requested&&((p=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&p!==void 0?p:i.getState())===v.PLAYING})),l=e.stateChangeEnded$.pipe(j(({from:f,to:m})=>{var p,S;return f.state===H.Applying&&m.state===H.None&&((S=(p=i.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:i.getState())===v.PLAYING})),c=L(o,l).pipe($(()=>r.getValue()),j(w)),h=L(L(u,d,t),s).pipe($(()=>r.getValue()),j(w));return new se().add(c.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 Ly{constructor(e={}){if(this.subscription=new se,this.logger=new qu,this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(v.STOPPED),seekState:new le({state:H.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({})},this.info={playbackState$:new y(v.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),chromecastState$:new y(_e.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new O,started$:new O,willPause$:new O,willResume$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:gg},this.initLogs(),this.tuning=wy(e),this.chromecastInitializer=new Ju({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _i(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(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(s)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=Py(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new by({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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===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:H.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===_e.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===_e.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const 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===H.None?void 0:t.position;return w(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(L(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===H.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},u),{state:H.Applying})):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===H.Applying&&(this.desiredState.seekState.setState({state:H.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,l)=>$s(d)?1:$s(l)?-1:ms(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(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(ky({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(L(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:C.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 y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!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=L(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=L(U(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 y(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(Go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(L(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new 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=Ui(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(L(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),Sg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>mg(s)),this.providerContainer.current$.subscribe(({type:s})=>rs("provider",s)),t.duration$.subscribe(s=>rs("duration",s)),t.availableVideoTracks$.pipe(j(s=>!!s.length),ye()).subscribe(s=>rs("tracks",s)),this.events.fatalError$.subscribe(new Ze("fatalError")),this.events.managedError$.subscribe(new Ze("managedError")),t.position$.subscribe(new Ze("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new Ze("quality")),this.info.currentBuffer$.subscribe(new Ze("buffer")),t.isBuffering$.subscribe(new Ze("isBuffering"))].forEach(s=>this.subscription.add(s)),rs("codecs",cy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)}))});this.subscription.add(L(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===v.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const xy=`${Wu}@${zu}`;export{_e as ChromecastState,wi as HttpConnectionType,My as Observable,v as PlaybackState,Ly as Player,xy as SDK_VERSION,Uy as Subject,Fy as Subscription,Vy as ValueSubject,b as VideoFormat,ne as VideoQuality};
6
+ import{ValueSubject as b,Subject as x,Subscription as se,isNonNullable as _,ErrorCategory as C,isNullable as K,fromEvent as U,assertNever as O,merge as L,tap as sn,map as $,observableFrom as xe,filterChanged as me,assertNonNullable as P,debounce as Ve,timeout as Ku,combine as ut,once as ye,mapTo as Lt,filter as j,now as pe,Observable as Oi,abortable as qe,getExponentialDelay as rn,interval as Xu,Logger as Zu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as ST,Subject as gT,Subscription as bT,ValueSubject as yT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import el from"lodash/debounce.js";const tl="2.0.83-dev.65744ed.0",il="es2015.esm.js";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var y;(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_CMAF="DASH_LIVE_CMAF",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.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var De;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(De||(De={}));var _e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(_e||(_e={}));var Ci;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(Ci||(Ci={}));var H;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(H||(H={}));function le(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(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.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 je(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(p){return new Promise(function(m,f){a.push([h,p,m,f])>1||o(h,p)})})}function o(h,p){try{u(s[h](p))}catch(m){c(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,p){h(p),a.shift(),a.length&&o(a[0][0],a[0][1])}}var sl=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 rl{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(_e.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new b(_e.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||sl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.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(U(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 O(r.sessionState)}})).add(L(U(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(sn(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),xe([s.getCastState()])).pipe(me(),$(al),sn(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===_e.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===_e.CONNECTED?_(this.connection$.getValue())?_e.CONNECTED:_e.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:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const al=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _e.AVAILABLE;case cast.framework.CastState.CONNECTING:return _e.CONNECTING;case cast.framework.CastState.CONNECTED:return _e.CONNECTED;default:return O(i)}};var an=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},He=function(i){try{return!!i()}catch(e){return!0}},nl=He,Bs=!nl(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Zo=Bs,ed=Function.prototype,Kr=ed.call,ol=Zo&&ed.bind.bind(Kr,Kr),Ge=Zo?ol:function(i){return function(){return Kr.apply(i,arguments)}},td=Ge,dl=td({}.toString),ul=td("".slice),Bi=function(i){return ul(dl(i),8,-1)},ll=Ge,cl=He,hl=Bi,er=Object,fl=ll("".split),pl=cl(function(){return!er("z").propertyIsEnumerable(0)})?function(i){return hl(i)=="String"?fl(i,""):er(i)}:er,Ni=function(i){return i==null},vl=Ni,ml=TypeError,ya=function(i){if(vl(i))throw ml("Can't call method on "+i);return i},Sl=pl,gl=ya,Mi=function(i){return Sl(gl(i))},bl=function(){},oi={},Ki=function(i){return i&&i.Math==Math&&i},we=Ki(typeof globalThis=="object"&&globalThis)||Ki(typeof window=="object"&&window)||Ki(typeof self=="object"&&self)||Ki(typeof an=="object"&&an)||function(){return this}()||Function("return this")(),Xr=typeof document=="object"&&document.all,yl=typeof Xr=="undefined"&&Xr!==void 0,id={all:Xr,IS_HTMLDDA:yl},sd=id,Tl=sd.all,Te=sd.IS_HTMLDDA?function(i){return typeof i=="function"||i===Tl}:function(i){return typeof i=="function"},El=we,$l=Te,nn=El.WeakMap,Al=$l(nn)&&/native code/.test(String(nn)),on=Te,rd=id,_l=rd.all,ht=rd.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:on(i)||i===_l}:function(i){return typeof i=="object"?i!==null:on(i)},wl=He,ft=!wl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Bt={},Rl=we,dn=ht,Zr=Rl.document,Pl=dn(Zr)&&dn(Zr.createElement),Ta=function(i){return Pl?Zr.createElement(i):{}},kl=ft,Il=He,Dl=Ta,ad=!kl&&!Il(function(){return Object.defineProperty(Dl("div"),"a",{get:function(){return 7}}).a!=7}),Cl=ft,xl=He,nd=Cl&&xl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Ll=ht,Ol=String,Bl=TypeError,pt=function(i){if(Ll(i))return i;throw Bl(Ol(i)+" is not an object")},Nl=Bs,Xi=Function.prototype.call,Le=Nl?Xi.bind(Xi):function(){return Xi.apply(Xi,arguments)},Ea={},tr=Ea,ir=we,Ml=Te,un=function(i){return Ml(i)?i:void 0},Nt=function(i,e){return arguments.length<2?un(tr[i])||un(ir[i]):tr[i]&&tr[i][e]||ir[i]&&ir[i][e]},Ul=Ge,Ns=Ul({}.isPrototypeOf),Ms=typeof navigator!="undefined"&&String(navigator.userAgent)||"",od=we,sr=Ms,ln=od.process,cn=od.Deno,hn=ln&&ln.versions||cn&&cn.version,fn=hn&&hn.v8,Ye,As;fn&&(Ye=fn.split("."),As=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!As&&sr&&(Ye=sr.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=sr.match(/Chrome\/(\d+)/),Ye&&(As=+Ye[1])));var dd=As,pn=dd,Fl=He,ud=!!Object.getOwnPropertySymbols&&!Fl(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&pn&&pn<41}),Vl=ud,ld=Vl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Hl=Nt,Gl=Te,Yl=Ns,ql=ld,jl=Object,cd=ql?function(i){return typeof i=="symbol"}:function(i){var e=Hl("Symbol");return Gl(e)&&Yl(e.prototype,jl(i))},zl=String,Us=function(i){try{return zl(i)}catch(e){return"Object"}},Wl=Te,Ql=Us,Jl=TypeError,Mt=function(i){if(Wl(i))return i;throw Jl(Ql(i)+" is not a function")},Kl=Mt,Xl=Ni,Fs=function(i,e){var t=i[e];return Xl(t)?void 0:Kl(t)},rr=Le,ar=Te,nr=ht,Zl=TypeError,ec=function(i,e){var t,s;if(e==="string"&&ar(t=i.toString)&&!nr(s=rr(t,i))||ar(t=i.valueOf)&&!nr(s=rr(t,i))||e!=="string"&&ar(t=i.toString)&&!nr(s=rr(t,i)))return s;throw Zl("Can't convert object to primitive value")},_s={},tc={get exports(){return _s},set exports(i){_s=i}},hd=!0,vn=we,ic=Object.defineProperty,sc=function(i,e){try{ic(vn,i,{value:e,configurable:!0,writable:!0})}catch(t){vn[i]=e}return e},rc=we,ac=sc,mn="__core-js_shared__",nc=rc[mn]||ac(mn,{}),$a=nc,Sn=$a;(tc.exports=function(i,e){return Sn[i]||(Sn[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 oc=ya,dc=Object,Vs=function(i){return dc(oc(i))},uc=Ge,lc=Vs,cc=uc({}.hasOwnProperty),it=Object.hasOwn||function(e,t){return cc(lc(e),t)},hc=Ge,fc=0,pc=Math.random(),vc=hc(1 .toString),fd=function(i){return"Symbol("+(i===void 0?"":i)+")_"+vc(++fc+pc,36)},mc=we,Sc=_s,gn=it,gc=fd,bc=ud,yc=ld,Jt=mc.Symbol,or=Sc("wks"),Tc=yc?Jt.for||Jt:Jt&&Jt.withoutSetter||gc,Re=function(i){return gn(or,i)||(or[i]=bc&&gn(Jt,i)?Jt[i]:Tc("Symbol."+i)),or[i]},Ec=Le,bn=ht,yn=cd,$c=Fs,Ac=ec,_c=Re,wc=TypeError,Rc=_c("toPrimitive"),Pc=function(i,e){if(!bn(i)||yn(i))return i;var t=$c(i,Rc),s;if(t){if(e===void 0&&(e="default"),s=Ec(t,i,e),!bn(s)||yn(s))return s;throw wc("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ac(i,e)},kc=Pc,Ic=cd,Aa=function(i){var e=kc(i,"string");return Ic(e)?e:e+""},Dc=ft,Cc=ad,xc=nd,Zi=pt,Tn=Aa,Lc=TypeError,dr=Object.defineProperty,Oc=Object.getOwnPropertyDescriptor,ur="enumerable",lr="configurable",cr="writable";Bt.f=Dc?xc?function(e,t,s){if(Zi(e),t=Tn(t),Zi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&cr in s&&!s[cr]){var r=Oc(e,t);r&&r[cr]&&(e[t]=s.value,s={configurable:lr in s?s[lr]:r[lr],enumerable:ur in s?s[ur]:r[ur],writable:!1})}return dr(e,t,s)}:dr:function(e,t,s){if(Zi(e),t=Tn(t),Zi(s),Cc)try{return dr(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Lc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Hs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Bc=ft,Nc=Bt,Mc=Hs,Ui=Bc?function(i,e,t){return Nc.f(i,e,Mc(1,t))}:function(i,e,t){return i[e]=t,i},Uc=_s,Fc=fd,En=Uc("keys"),_a=function(i){return En[i]||(En[i]=Fc(i))},wa={},Vc=Al,pd=we,Hc=ht,Gc=Ui,hr=it,fr=$a,Yc=_a,qc=wa,$n="Object already initialized",ea=pd.TypeError,jc=pd.WeakMap,ws,xi,Rs,zc=function(i){return Rs(i)?xi(i):ws(i,{})},Wc=function(i){return function(e){var t;if(!Hc(e)||(t=xi(e)).type!==i)throw ea("Incompatible receiver, "+i+" required");return t}};if(Vc||fr.state){var Xe=fr.state||(fr.state=new jc);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ws=function(i,e){if(Xe.has(i))throw ea($n);return e.facade=i,Xe.set(i,e),e},xi=function(i){return Xe.get(i)||{}},Rs=function(i){return Xe.has(i)}}else{var Gt=Yc("state");qc[Gt]=!0,ws=function(i,e){if(hr(i,Gt))throw ea($n);return e.facade=i,Gc(i,Gt,e),e},xi=function(i){return hr(i,Gt)?i[Gt]:{}},Rs=function(i){return hr(i,Gt)}}var vd={set:ws,get:xi,has:Rs,enforce:zc,getterFor:Wc},Qc=Bs,md=Function.prototype,An=md.apply,_n=md.call,Sd=typeof Reflect=="object"&&Reflect.apply||(Qc?_n.bind(An):function(){return _n.apply(An,arguments)}),Jc=Bi,Kc=Ge,gd=function(i){if(Jc(i)==="Function")return Kc(i)},Ra={},bd={},yd={}.propertyIsEnumerable,Td=Object.getOwnPropertyDescriptor,Xc=Td&&!yd.call({1:2},1);bd.f=Xc?function(e){var t=Td(this,e);return!!t&&t.enumerable}:yd;var Zc=ft,eh=Le,th=bd,ih=Hs,sh=Mi,rh=Aa,ah=it,nh=ad,wn=Object.getOwnPropertyDescriptor;Ra.f=Zc?wn:function(e,t){if(e=sh(e),t=rh(t),nh)try{return wn(e,t)}catch(s){}if(ah(e,t))return ih(!eh(th.f,e,t),e[t])};var oh=He,dh=Te,uh=/#|\.prototype\./,Fi=function(i,e){var t=ch[lh(i)];return t==fh?!0:t==hh?!1:dh(e)?oh(e):!!e},lh=Fi.normalize=function(i){return String(i).replace(uh,".").toLowerCase()},ch=Fi.data={},hh=Fi.NATIVE="N",fh=Fi.POLYFILL="P",Ed=Fi,Rn=gd,ph=Mt,vh=Bs,mh=Rn(Rn.bind),Gs=function(i,e){return ph(i),e===void 0?i:vh?mh(i,e):function(){return i.apply(e,arguments)}},es=we,Sh=Sd,gh=gd,bh=Te,yh=Ra.f,Th=Ed,Yt=Ea,Eh=Gs,qt=Ui,Pn=it,$h=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 Sh(i,this,arguments)};return e.prototype=i.prototype,e},We=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?es:r?es[t]:(es[t]||{}).prototype,o=s?Yt:Yt[t]||qt(Yt,t,{})[t],u=o.prototype,d,l,c,h,p,m,f,S,g;for(h in e)d=Th(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Pn(n,h),m=o[h],l&&(i.dontCallGetSet?(g=yh(n,h),f=g&&g.value):f=n[h]),p=l&&f?f:e[h],!(l&&typeof m==typeof p)&&(i.bind&&l?S=Eh(p,es):i.wrap&&l?S=$h(p):a&&bh(p)?S=gh(p):S=p,(i.sham||p&&p.sham||m&&m.sham)&&qt(S,"sham",!0),qt(o,h,S),a&&(c=t+"Prototype",Pn(Yt,c)||qt(Yt,c,{}),qt(Yt[c],h,p),i.real&&u&&(d||!u[h])&&qt(u,h,p)))},ta=ft,Ah=it,$d=Function.prototype,_h=ta&&Object.getOwnPropertyDescriptor,Pa=Ah($d,"name"),wh=Pa&&function(){}.name==="something",Rh=Pa&&(!ta||ta&&_h($d,"name").configurable),Ph={EXISTS:Pa,PROPER:wh,CONFIGURABLE:Rh},Ad={},kh=Math.ceil,Ih=Math.floor,Dh=Math.trunc||function(e){var t=+e;return(t>0?Ih:kh)(t)},Ch=Dh,ka=function(i){var e=+i;return e!==e||e===0?0:Ch(e)},xh=ka,Lh=Math.max,Oh=Math.min,Bh=function(i,e){var t=xh(i);return t<0?Lh(t+e,0):Oh(t,e)},Nh=ka,Mh=Math.min,Uh=function(i){return i>0?Mh(Nh(i),9007199254740991):0},Fh=Uh,Ia=function(i){return Fh(i.length)},Vh=Mi,Hh=Bh,Gh=Ia,kn=function(i){return function(e,t,s){var r=Vh(e),a=Gh(r),n=Hh(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}},Yh={includes:kn(!0),indexOf:kn(!1)},qh=Ge,pr=it,jh=Mi,zh=Yh.indexOf,Wh=wa,In=qh([].push),Qh=function(i,e){var t=jh(i),s=0,r=[],a;for(a in t)!pr(Wh,a)&&pr(t,a)&&In(r,a);for(;e.length>s;)pr(t,a=e[s++])&&(~zh(r,a)||In(r,a));return r},_d=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Jh=Qh,Kh=_d,Xh=Object.keys||function(e){return Jh(e,Kh)},Zh=ft,ef=nd,tf=Bt,sf=pt,rf=Mi,af=Xh;Ad.f=Zh&&!ef?Object.defineProperties:function(e,t){sf(e);for(var s=rf(t),r=af(t),a=r.length,n=0,o;a>n;)tf.f(e,o=r[n++],s[o]);return e};var nf=Nt,wd=nf("document","documentElement"),of=pt,df=Ad,Dn=_d,uf=wa,lf=wd,cf=Ta,hf=_a,Cn=">",xn="<",ia="prototype",sa="script",Rd=hf("IE_PROTO"),vr=function(){},Pd=function(i){return xn+sa+Cn+i+xn+"/"+sa+Cn},Ln=function(i){i.write(Pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},ff=function(){var i=cf("iframe"),e="java"+sa+":",t;return i.style.display="none",lf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Pd("document.F=Object")),t.close(),t.F},ts,bs=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}bs=typeof document!="undefined"?document.domain&&ts?Ln(ts):ff():Ln(ts);for(var i=Dn.length;i--;)delete bs[ia][Dn[i]];return bs()};uf[Rd]=!0;var kd=Object.create||function(e,t){var s;return e!==null?(vr[ia]=of(e),s=new vr,vr[ia]=null,s[Rd]=e):s=bs(),t===void 0?s:df.f(s,t)},pf=He,vf=!pf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),mf=it,Sf=Te,gf=Vs,bf=_a,yf=vf,On=bf("IE_PROTO"),ra=Object,Tf=ra.prototype,Id=yf?ra.getPrototypeOf:function(i){var e=gf(i);if(mf(e,On))return e[On];var t=e.constructor;return Sf(t)&&e instanceof t?t.prototype:e instanceof ra?Tf:null},Ef=Ui,Da=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Ef(i,e,t),i},$f=He,Af=Te,_f=ht,wf=kd,Bn=Id,Rf=Da,Pf=Re,aa=Pf("iterator"),Dd=!1,lt,mr,Sr;[].keys&&(Sr=[].keys(),"next"in Sr?(mr=Bn(Bn(Sr)),mr!==Object.prototype&&(lt=mr)):Dd=!0);var kf=!_f(lt)||$f(function(){var i={};return lt[aa].call(i)!==i});kf?lt={}:lt=wf(lt);Af(lt[aa])||Rf(lt,aa,function(){return this});var Cd={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Dd},If=Re,Df=If("toStringTag"),xd={};xd[Df]="z";var Ca=String(xd)==="[object z]",Cf=Ca,xf=Te,ys=Bi,Lf=Re,Of=Lf("toStringTag"),Bf=Object,Nf=ys(function(){return arguments}())=="Arguments",Mf=function(i,e){try{return i[e]}catch(t){}},Vi=Cf?ys:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Mf(e=Bf(i),Of))=="string"?t:Nf?ys(e):(s=ys(e))=="Object"&&xf(e.callee)?"Arguments":s},Uf=Ca,Ff=Vi,Vf=Uf?{}.toString:function(){return"[object "+Ff(this)+"]"},Hf=Ca,Gf=Bt.f,Yf=Ui,qf=it,jf=Vf,zf=Re,Nn=zf("toStringTag"),xa=function(i,e,t,s){if(i){var r=t?i:i.prototype;qf(r,Nn)||Gf(r,Nn,{configurable:!0,value:e}),s&&!Hf&&Yf(r,"toString",jf)}},Wf=Cd.IteratorPrototype,Qf=kd,Jf=Hs,Kf=xa,Xf=oi,Zf=function(){return this},ep=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Qf(Wf,{next:Jf(+!s,t)}),Kf(i,r,!1,!0),Xf[r]=Zf,i},tp=We,ip=Le,Ld=Ph,sp=ep,rp=Id,ap=xa,Mn=Da,np=Re,Un=oi,Od=Cd,op=Ld.PROPER;Ld.CONFIGURABLE;Od.IteratorPrototype;var is=Od.BUGGY_SAFARI_ITERATORS,gr=np("iterator"),Fn="keys",ss="values",Vn="entries",dp=function(){return this},up=function(i,e,t,s,r,a,n){sp(t,e,s);var o=function(g){if(g===r&&h)return h;if(!is&&g in l)return l[g];switch(g){case Fn:return function(){return new t(this,g)};case ss:return function(){return new t(this,g)};case Vn:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[gr]||l["@@iterator"]||r&&l[r],h=!is&&c||o(r),p=e=="Array"&&l.entries||c,m,f,S;if(p&&(m=rp(p.call(new i)),m!==Object.prototype&&m.next&&(ap(m,u,!0,!0),Un[u]=dp)),op&&r==ss&&c&&c.name!==ss&&(d=!0,h=function(){return ip(c,this)}),r)if(f={values:o(ss),keys:a?h:o(Fn),entries:o(Vn)},n)for(S in f)(is||d||!(S in l))&&Mn(l,S,f[S]);else tp({target:e,proto:!0,forced:is||d},f);return n&&l[gr]!==h&&Mn(l,gr,h,{name:r}),Un[e]=h,f},lp=function(i,e){return{value:i,done:e}},cp=Mi,La=bl,Hn=oi,Bd=vd,hp=Bt.f,fp=up,rs=lp,pp=hd,vp=ft,Nd="Array Iterator",mp=Bd.set,Sp=Bd.getterFor(Nd);fp(Array,"Array",function(i,e){mp(this,{type:Nd,target:cp(i),index:0,kind:e})},function(){var i=Sp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,rs(void 0,!0)):t=="keys"?rs(s,!1):t=="values"?rs(e[s],!1):rs([s,e[s]],!1)},"values");var Gn=Hn.Arguments=Hn.Array;La();La();La();if(!pp&&vp&&Gn.name!=="values")try{hp(Gn,"name",{value:"values"})}catch(i){}var gp=Re,bp=oi,yp=gp("iterator"),Tp=Array.prototype,Ep=function(i){return i!==void 0&&(bp.Array===i||Tp[yp]===i)},$p=Vi,Yn=Fs,Ap=Ni,_p=oi,wp=Re,Rp=wp("iterator"),Md=function(i){if(!Ap(i))return Yn(i,Rp)||Yn(i,"@@iterator")||_p[$p(i)]},Pp=Le,kp=Mt,Ip=pt,Dp=Us,Cp=Md,xp=TypeError,Lp=function(i,e){var t=arguments.length<2?Cp(i):e;if(kp(t))return Ip(Pp(t,i));throw xp(Dp(i)+" is not iterable")},Op=Le,qn=pt,Bp=Fs,Np=function(i,e,t){var s,r;qn(i);try{if(s=Bp(i,"return"),!s){if(e==="throw")throw t;return t}s=Op(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return qn(s),t},Mp=Gs,Up=Le,Fp=pt,Vp=Us,Hp=Ep,Gp=Ia,jn=Ns,Yp=Lp,qp=Md,zn=Np,jp=TypeError,Ts=function(i,e){this.stopped=i,this.result=e},Wn=Ts.prototype,Oa=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=Mp(e,s),d,l,c,h,p,m,f,S=function(E){return d&&zn(d,"normal",E),new Ts(!0,E)},g=function(E){return r?(Fp(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(a)d=i.iterator;else if(n)d=i;else{if(l=qp(i),!l)throw jp(Vp(i)+" is not iterable");if(Hp(l)){for(c=0,h=Gp(i);h>c;c++)if(p=g(i[c]),p&&jn(Wn,p))return p;return new Ts(!1)}d=Yp(i,l)}for(m=a?i.next:d.next;!(f=Up(m,d)).done;){try{p=g(f.value)}catch(E){zn(d,"throw",E)}if(typeof p=="object"&&p&&jn(Wn,p))return p}return new Ts(!1)},zp=Aa,Wp=Bt,Qp=Hs,Jp=function(i,e,t){var s=zp(e);s in i?Wp.f(i,s,Qp(0,t)):i[s]=t},Kp=We,Xp=Oa,Zp=Jp;Kp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Xp(e,function(s,r){Zp(t,s,r)},{AS_ENTRIES:!0}),t}});var ev=Ea,tv=ev.Object.fromEntries,iv={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},sv=iv,rv=we,av=Vi,nv=Ui,Qn=oi,ov=Re,Jn=ov("toStringTag");for(var br in sv){var Kn=rv[br],yr=Kn&&Kn.prototype;yr&&av(yr)!==Jn&&nv(yr,Jn,br),Qn[br]=Qn.Array}var dv=tv,uv=dv,lv=uv,cv=lv,Hi=cv,hv=Bi,Ys=typeof process!="undefined"&&hv(process)=="process",fv=Nt,pv=Bt,vv=Re,mv=ft,Xn=vv("species"),Sv=function(i){var e=fv(i),t=pv.f;mv&&e&&!e[Xn]&&t(e,Xn,{configurable:!0,get:function(){return this}})},gv=Ns,bv=TypeError,yv=function(i,e){if(gv(e,i))return i;throw bv("Incorrect invocation")},Tv=Ge,Ev=Te,na=$a,$v=Tv(Function.toString);Ev(na.inspectSource)||(na.inspectSource=function(i){return $v(i)});var Ud=na.inspectSource,Av=Ge,_v=He,Fd=Te,wv=Vi,Rv=Nt,Pv=Ud,Vd=function(){},kv=[],Hd=Rv("Reflect","construct"),Ba=/^\s*(?:class|function)\b/,Iv=Av(Ba.exec),Dv=!Ba.exec(Vd),Ei=function(e){if(!Fd(e))return!1;try{return Hd(Vd,kv,e),!0}catch(t){return!1}},Gd=function(e){if(!Fd(e))return!1;switch(wv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Dv||!!Iv(Ba,Pv(e))}catch(t){return!0}};Gd.sham=!0;var Cv=!Hd||_v(function(){var i;return Ei(Ei.call)||!Ei(Object)||!Ei(function(){i=!0})||i})?Gd:Ei,xv=Cv,Lv=Us,Ov=TypeError,Bv=function(i){if(xv(i))return i;throw Ov(Lv(i)+" is not a constructor")},Zn=pt,Nv=Bv,Mv=Ni,Uv=Re,Fv=Uv("species"),Yd=function(i,e){var t=Zn(i).constructor,s;return t===void 0||Mv(s=Zn(t)[Fv])?e:Nv(s)},Vv=Ge,Hv=Vv([].slice),Gv=TypeError,Yv=function(i,e){if(i<e)throw Gv("Not enough arguments");return i},qv=Ms,qd=/(?:ipad|iphone|ipod).*applewebkit/i.test(qv),Ce=we,jv=Sd,zv=Gs,eo=Te,Wv=it,jd=He,to=wd,Qv=Hv,io=Ta,Jv=Yv,Kv=qd,Xv=Ys,oa=Ce.setImmediate,da=Ce.clearImmediate,Zv=Ce.process,Tr=Ce.Dispatch,em=Ce.Function,so=Ce.MessageChannel,tm=Ce.String,Er=0,Ri={},ro="onreadystatechange",Li,kt,$r,Ar;jd(function(){Li=Ce.location});var Na=function(i){if(Wv(Ri,i)){var e=Ri[i];delete Ri[i],e()}},_r=function(i){return function(){Na(i)}},ao=function(i){Na(i.data)},no=function(i){Ce.postMessage(tm(i),Li.protocol+"//"+Li.host)};(!oa||!da)&&(oa=function(e){Jv(arguments.length,1);var t=eo(e)?e:em(e),s=Qv(arguments,1);return Ri[++Er]=function(){jv(t,void 0,s)},kt(Er),Er},da=function(e){delete Ri[e]},Xv?kt=function(i){Zv.nextTick(_r(i))}:Tr&&Tr.now?kt=function(i){Tr.now(_r(i))}:so&&!Kv?($r=new so,Ar=$r.port2,$r.port1.onmessage=ao,kt=zv(Ar.postMessage,Ar)):Ce.addEventListener&&eo(Ce.postMessage)&&!Ce.importScripts&&Li&&Li.protocol!=="file:"&&!jd(no)?(kt=no,Ce.addEventListener("message",ao,!1)):ro in io("script")?kt=function(i){to.appendChild(io("script"))[ro]=function(){to.removeChild(this),Na(i)}}:kt=function(i){setTimeout(_r(i),0)});var zd={set:oa,clear:da},Wd=function(){this.head=null,this.tail=null};Wd.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 Qd=Wd,im=Ms,sm=/ipad|iphone|ipod/i.test(im)&&typeof Pebble!="undefined",rm=Ms,am=/web0s(?!.*chrome)/i.test(rm),Ot=we,oo=Gs,nm=Ra.f,wr=zd.set,om=Qd,dm=qd,um=sm,lm=am,Rr=Ys,uo=Ot.MutationObserver||Ot.WebKitMutationObserver,lo=Ot.document,co=Ot.process,as=Ot.Promise,ho=nm(Ot,"queueMicrotask"),ua=ho&&ho.value,jt,Pr,kr,ns,fo;if(!ua){var os=new om,ds=function(){var i,e;for(Rr&&(i=co.domain)&&i.exit();e=os.get();)try{e()}catch(t){throw os.head&&jt(),t}i&&i.enter()};!dm&&!Rr&&!lm&&uo&&lo?(Pr=!0,kr=lo.createTextNode(""),new uo(ds).observe(kr,{characterData:!0}),jt=function(){kr.data=Pr=!Pr}):!um&&as&&as.resolve?(ns=as.resolve(void 0),ns.constructor=as,fo=oo(ns.then,ns),jt=function(){fo(ds)}):Rr?jt=function(){co.nextTick(ds)}:(wr=oo(wr,Ot),jt=function(){wr(ds)}),ua=function(i){os.head||jt(),os.add(i)}}var cm=ua,hm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Ma=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},fm=we,di=fm.Promise,Jd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",pm=Jd,vm=Ys,mm=!pm&&!vm&&typeof window=="object"&&typeof document=="object",Sm=we,Pi=di,gm=Te,bm=Ed,ym=Ud,Tm=Re,Em=mm,$m=Jd,Ir=dd,po=Pi&&Pi.prototype,Am=Tm("species"),la=!1,Kd=gm(Sm.PromiseRejectionEvent),_m=bm("Promise",function(){var i=ym(Pi),e=i!==String(Pi);if(!e&&Ir===66||!(po.catch&&po.finally))return!0;if(!Ir||Ir<51||!/native code/.test(i)){var t=new Pi(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Am]=s,la=t.then(function(){})instanceof s,!la)return!0}return!e&&(Em||$m)&&!Kd}),Gi={CONSTRUCTOR:_m,REJECTION_EVENT:Kd,SUBCLASSING:la},ui={},vo=Mt,wm=TypeError,Rm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw wm("Bad Promise constructor");e=s,t=r}),this.resolve=vo(e),this.reject=vo(t)};ui.f=function(i){return new Rm(i)};var Pm=We,Ps=Ys,Tt=we,Yi=Le,km=Da,Im=xa,Dm=Sv,Cm=Mt,ca=Te,xm=ht,Lm=yv,Om=Yd,Xd=zd.set,Ua=cm,Bm=hm,Nm=Ma,Mm=Qd,Zd=vd,ha=di,Fa=Gi,eu=ui,qs="Promise",tu=Fa.CONSTRUCTOR,Um=Fa.REJECTION_EVENT;Fa.SUBCLASSING;var Dr=Zd.getterFor(qs),Fm=Zd.set,Vm=ha&&ha.prototype,Kt=ha,Cr=Vm,iu=Tt.TypeError,fa=Tt.document,Va=Tt.process,pa=eu.f,Hm=pa,Gm=!!(fa&&fa.createEvent&&Tt.dispatchEvent),su="unhandledrejection",Ym="rejectionhandled",mo=0,ru=1,qm=2,Ha=1,au=2,us,So,jm,nu=function(i){var e;return xm(i)&&ca(e=i.then)?e:!1},ou=function(i,e){var t=e.value,s=e.state==ru,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===au&&Wm(e),e.rejection=Ha),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(iu("Promise-chain cycle")):(d=nu(u))?Yi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},du=function(i,e){i.notified||(i.notified=!0,Ua(function(){for(var t=i.reactions,s;s=t.get();)ou(s,i);i.notified=!1,e&&!i.rejection&&zm(i)}))},uu=function(i,e,t){var s,r;Gm?(s=fa.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Tt.dispatchEvent(s)):s={promise:e,reason:t},!Um&&(r=Tt["on"+i])?r(s):i===su&&Bm("Unhandled promise rejection",t)},zm=function(i){Yi(Xd,Tt,function(){var e=i.facade,t=i.value,s=go(i),r;if(s&&(r=Nm(function(){Ps?Va.emit("unhandledRejection",t,e):uu(su,e,t)}),i.rejection=Ps||go(i)?au:Ha,r.error))throw r.value})},go=function(i){return i.rejection!==Ha&&!i.parent},Wm=function(i){Yi(Xd,Tt,function(){var e=i.facade;Ps?Va.emit("rejectionHandled",e):uu(Ym,e,i.value)})},Xt=function(i,e,t){return function(s){i(e,s,t)}},ei=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=qm,du(i,!0))},va=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw iu("Promise can't be resolved itself");var s=nu(e);s?Ua(function(){var r={done:!1};try{Yi(s,e,Xt(va,r,i),Xt(ei,r,i))}catch(a){ei(r,a,i)}}):(i.value=e,i.state=ru,du(i,!1))}catch(r){ei({done:!1},r,i)}}};tu&&(Kt=function(e){Lm(this,Cr),Cm(e),Yi(us,this);var t=Dr(this);try{e(Xt(va,t),Xt(ei,t))}catch(s){ei(t,s)}},Cr=Kt.prototype,us=function(e){Fm(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new Mm,rejection:!1,state:mo,value:void 0})},us.prototype=km(Cr,"then",function(e,t){var s=Dr(this),r=pa(Om(this,Kt));return s.parent=!0,r.ok=ca(e)?e:!0,r.fail=ca(t)&&t,r.domain=Ps?Va.domain:void 0,s.state==mo?s.reactions.add(r):Ua(function(){ou(r,s)}),r.promise}),So=function(){var i=new us,e=Dr(i);this.promise=i,this.resolve=Xt(va,e),this.reject=Xt(ei,e)},eu.f=pa=function(i){return i===Kt||i===jm?new So(i):Hm(i)});Pm({global:!0,constructor:!0,wrap:!0,forced:tu},{Promise:Kt});Im(Kt,qs,!1,!0);Dm(qs);var Qm=Re,lu=Qm("iterator"),cu=!1;try{var Jm=0,bo={next:function(){return{done:!!Jm++}},return:function(){cu=!0}};bo[lu]=function(){return this},Array.from(bo,function(){throw 2})}catch(i){}var Km=function(i,e){if(!e&&!cu)return!1;var t=!1;try{var s={};s[lu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Xm=di,Zm=Km,eS=Gi.CONSTRUCTOR,hu=eS||!Zm(function(i){Xm.all(i).then(void 0,function(){})}),tS=We,iS=Le,sS=Mt,rS=ui,aS=Ma,nS=Oa,oS=hu;tS({target:"Promise",stat:!0,forced:oS},{all:function(e){var t=this,s=rS.f(t),r=s.resolve,a=s.reject,n=aS(function(){var o=sS(t.resolve),u=[],d=0,l=1;nS(e,function(c){var h=d++,p=!1;l++,iS(o,t,c).then(function(m){p||(p=!0,u[h]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),s.promise}});var dS=We,uS=Gi.CONSTRUCTOR,yo=di;yo&&yo.prototype;dS({target:"Promise",proto:!0,forced:uS,real:!0},{catch:function(i){return this.then(void 0,i)}});var lS=We,cS=Le,hS=Mt,fS=ui,pS=Ma,vS=Oa,mS=hu;lS({target:"Promise",stat:!0,forced:mS},{race:function(e){var t=this,s=fS.f(t),r=s.reject,a=pS(function(){var n=hS(t.resolve);vS(e,function(o){cS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var SS=We,gS=Le,bS=ui,yS=Gi.CONSTRUCTOR;SS({target:"Promise",stat:!0,forced:yS},{reject:function(e){var t=bS.f(this);return gS(t.reject,void 0,e),t.promise}});var TS=pt,ES=ht,$S=ui,fu=function(i,e){if(TS(i),ES(e)&&e.constructor===i)return e;var t=$S.f(i),s=t.resolve;return s(e),t.promise},AS=We,_S=Nt,wS=hd,RS=di,PS=Gi.CONSTRUCTOR,kS=fu,IS=_S("Promise"),DS=!PS;AS({target:"Promise",stat:!0,forced:wS},{resolve:function(e){return kS(DS&&this===IS?RS:this,e)}});var CS=We,ma=di,xS=He,LS=Nt,OS=Te,BS=Yd,To=fu,NS=ma&&ma.prototype,MS=!!ma&&xS(function(){NS.finally.call({then:function(){}},function(){})});CS({target:"Promise",proto:!0,real:!0,forced:MS},{finally:function(i){var e=BS(this,LS("Promise")),t=OS(i);return this.then(t?function(s){return To(e,i()).then(function(){return s})}:i,t?function(s){return To(e,i()).then(function(){throw s})}:i)}});var US=Nt,Ga=US,FS=Ga,VS=FS("Promise","finally"),HS=VS,GS=HS,YS=GS,qS=YS,js=qS,ti;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ti||(ti={}));var ii=(i,e=0,t=ti.OFFSET_P)=>{switch(t){case ti.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ti.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:O(t)}return i},k=(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 ze={[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}},Es=(i,e)=>ze[i].height>ze[e].height,jS=(i,e)=>ze[i].height>=ze[e].height,ki=(i,e)=>ze[i].height<ze[e].height,zS=(i,e)=>ze[i].height<=ze[e].height,WS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:ki(e,t)?1:-1)[0],QS=Object.keys(ze).sort((i,e)=>ki(i,e)?-1:1),Ut=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return QS.find(r=>{const a=ze[r];return a.width>=s&&a.height>=t})},JS=i=>ze[i].height,ks=i=>i===ne.INVARIANT;class ue{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=L(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=L(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 KS=i=>{switch(i){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return O(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const XS=5,ZS=5,eg=500,Eo=7e3;class tg{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===H.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:O(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:O(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:O(s)}break}default:O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(KS(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new se;this.subscription.add(e),this.subscription.add(L(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 x;e.add(r.pipe(Ve(eg)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(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===H.Applying||Math.abs(o-a)>XS)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(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<ZS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:O(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=L(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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),k(this.params.desiredState.playbackState,v.PAUSED)):(this.videoState.setState(q.PLAYING),k(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:H.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),k(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),k(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&&k(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 y.MPEG:{const l=s[e];P(l);const c=WS(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=s[e];P(l),r=ii(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===H.Applying||s.state===H.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(Ku(Eo).subscribe(()=>a(`timeout(${Eo})`)))});js(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.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:C.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class $o{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 pu extends $o{constructor(){super(),this.listeners||$o.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 vu=class{constructor(){Object.defineProperty(this,"signal",{value:new pu,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&&(vu.prototype[Symbol.toStringTag]="AbortController",pu.prototype[Symbol.toStringTag]="AbortSignal");function mu(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 ig(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!mu({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,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((p,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const zs=mu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Su=zs?ig({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,si=zs?Su.fetch:window.fetch;zs?Su.Request:window.Request;const Ct=zs?vu:window.AbortController,$i=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Ii{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 le(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]=$i(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($i),r=s[0][0];let a=s[0][1];for(let h=1;h<s.length&&a<this.params.minDataSize;h++){const p=s[h][1];p-r<=2*this.params.minDataSize&&(a=Math.max(a,p))}r===0?a=Math.max(a,r+this.params.minInitSize):a=Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${r}-${a}`);const o=n.toString(),u=new Ct,d=u.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var p,m;throw(m=(p=this.params).onError)===null||m===void 0||m.call(p,{id:"BigRequestParsing",category:C.PARSER,message:"Error parsing response data",thrown:h}),h};return si(o,{signal:d}).then(h=>{var p,m,f;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,g);const E=S.getReader(),D=parseInt((f=h.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||a-r+1;l.data=new ArrayBuffer(D);const w=new Uint8Array(l.data),A=({done:B,value:X})=>le(this,void 0,void 0,function*(){B?this.onBigRequestProgress(l):X&&(w.set(X,l.loaded),l.loaded+=X.byteLength,this.onBigRequestProgress(l),yield E==null?void 0:E.read().then(A,Ii.suppressStreamErrors).catch(c))});E==null||E.read().then(A,Ii.suppressStreamErrors).catch(c)},Ii.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,l,c,h,p,m;if(!this.activeRequests.has(e)||!a)return;const f=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of f){const{request:g}=S,[E,D]=$i(g),w=E>=t&&D<=t+r,A=t>=E&&t+r<D,B=a.slice(E-t,Math.min(D-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=B.byteLength,g.bytesTotal=s-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(Y=>Y!==S)),(c=S.success)===null||c===void 0||c.call(S,B,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,F])=>`${Y}: ${F}`).join(`\r
7
+ `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(p=n==null?void 0:n.status)!==null&&p!==void 0?p:200,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:C.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=$i(l.request);(c>=t&&c<s||h>t&&h<=s)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to: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]=$i(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 Is{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(Is.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;Is.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const sg=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new Is(r,e,s)}}),rg=(i,e)=>{const t=new Ii(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return sg(n,t)}}},!0),()=>t.destroy()};var ag=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)},ng=i=>{const e=new b(1/0),t=new x,s=new b(void 0),r=new b(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,p,m,f;const S=Hi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(D=>D.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const D=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),w=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(p=w!=null?w:D*1e3)!==null&&p!==void 0?p:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:Ci.HTTP1,E=(f={1:!0,0:!1}[S["x-reused"]])!==null&&f!==void 0?f:void 0;s.next(g),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const p=h.onload,m=h.progress;h.onload=function(...f){return u(this),p(...f)},h.progress=function(...f){return d(this),m(...f)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ri=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},og=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ri}),!0),dg=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 tt=(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(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},Ft=(i,e,t)=>tt(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),vt=(i,e,t,s)=>tt(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}),Et=(i,e,t,s)=>tt(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),ug=i=>["__",i.language,i.label].join("|"),lg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class st{constructor(){this.available$=new x,this.current$=new b(void 0),this.error$=new x,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:C.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(tt(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(tt(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(tt(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(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(L(U(e,"addtrack"),U(e,"removetrack"),xe(["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(L(U(e,"change"),xe(["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(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const p=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;p&&p.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(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(st.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:ug(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)&&lg(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 mt=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 Ya{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 gu=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Sa=3;class cg{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 bu=(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 hg=50,fg=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,St=i=>{const e=m=>U(i,m).pipe(Lt(void 0)),s=L(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>U(i,m))).pipe($(m=>m.type==="ended"?i.readyState<2:i.readyState<3),me()),r=L(U(i,"progress"),U(i,"timeupdate")).pipe($(()=>bu(i.buffered,i.currentTime))),a=gu()?ut({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Lt(void 0)):e("playing"),n=U(i,"playing").pipe(Ve(hg),$(()=>fg(i))),o=U(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe($(()=>i.playbackRate)),d=U(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var m;const f=i.error;return{id:f?`MediaError#${f.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:f?f.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),l=U(i,"timeupdate").pipe($(()=>i.currentTime)),c=new x,h=.3;let p;return l.subscribe(m=>{i.loop&&_(p)&&_(m)&&p>=i.duration-h&&m<=h&&c.next(p),p=m}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},qa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var pg=We,vg=Vs,mg=Ia,Sg=ka;pg({target:"Array",proto:!0},{at:function(e){var t=vg(this),s=mg(t),r=Sg(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var gg=Ga,bg=gg("Array","at"),yg=bg,Tg=yg,Eg=Tg,$g=Eg,ot=$g;let ja=!1,dt={};const Ag=i=>{ja=i},_g=()=>{dt={}},wg=i=>{i(dt)},ls=(i,e)=>{var t;ja&&(dt.meta=(t=dt.meta)!==null&&t!==void 0?t:{},dt.meta[i]=e)};class Ze{constructor(e){this.name=e}next(e){var t,s;if(!ja)return;dt.series=(t=dt.series)!==null&&t!==void 0?t:{};const r=(s=dt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),dt.series[this.name]=r}}const Rg=new Ze("best_bitrate"),Pg=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class kg{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const qi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,p;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,f=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},S=f&&Ut(f),g=s.considerPlaybackRate&&_(o)?o:1,E=i.filter(V=>!ks(V.quality)).sort((V,N)=>Es(V.quality,N.quality)?-1:1),D=(c=ot(E,-1))===null||c===void 0?void 0:c.quality,w=(h=ot(E,0))===null||h===void 0?void 0:h.quality,A=K(r)||_(r.min)&&_(r.max)&&ki(r.max,r.min)||_(r.min)&&w&&Es(r.min,w)||_(r.max)&&D&&ki(r.max,D),B=g*Pg(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=E.filter(V=>{const N=S?ki(V.quality,S):!0,ie=_(t)&&isFinite(t)&&_(V.bitrate)?t-a>=V.bitrate*B:!0,ce=s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!ks(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Es(V.quality,u.quality),Se=A||(K(r.max)||zS(V.quality,r.max))&&(K(r.min)||jS(V.quality,r.min));return N&&ie&&!ce&&Se})[0];Y&&Y.bitrate&&Rg.next(Y.bitrate);const F=(p=Y!=null?Y:E[Math.ceil((E.length-1)/2)])!==null&&p!==void 0?p:i[0],Z=F&&d&&d.history[F.id]&&pe()-d.history[F.id]<=s.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!Z&&d.recordSelection(F),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(F),F};var ke=i=>new URL(i).hostname;const Ig=300,Ds=(i,e=Ig)=>new Oi(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(el(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,Ai={};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 Oi(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class Ao{constructor(e){this.subscription=new se,this.videoState=new ue(z.DOWNLOADING_LIB),this.textTracksManager=new st,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 Ya,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===H.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:O(t)}break}case v.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:O(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:O(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),k(this.params.desiredState.playbackState,v.PAUSED);break;case z.STOPPED:this.prepare();break;default:O(t)}break}default:O(s)}},this.video=mt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(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:C.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);js(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Ai.MediaPlayer=r.MediaPlayer,Ai.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(Ai.MediaPlayer,"dashjs not loaded"),P(Ai.Debug,"dashjs not loaded"),this.player=Ai.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?qa(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=rg(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&&dg(this.player),ag(this.player),this.params.tuning.requestQuick&&og(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=f=>{e.error$.next({id:"DashIFProvider",category:C.WTF,message:"DashIFProvider internal logic error",thrown:f})},r=(f,S)=>this.subscription.add(f.subscribe(S,s));r(Ds(this.video),this.elementSize$),r(be(this.player,"error").pipe($(f=>{const S=typeof f.error=="object"?f.error.code:f.error,g=typeof f.error=="object"?f.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(be(this.player,"playbackError").pipe($(f=>({id:"DashJSPlayback",message:f.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(j(({mediaType:f})=>f==="video"),$(({newQuality:f})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===f))===null||S===void 0?void 0:S.track}));a.pipe(j(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:f})=>f===z.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(tt(t.videoTrack,()=>{var f,S;const g=this.player.getQualityFor("video");return(S=(f=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===g))===null||f===void 0?void 0:f.track)===null||S===void 0?void 0:S.id},f=>{var S;if(K(f))return;const g=(S=this.videoTracks.find(({track:E})=>E.id===f))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(f=>f==null?void 0:f.id)),onError:s}))},s)),this.subscription.add(tt(t.autoVideoTrackSwitching,()=>{var f,S,g;return(g=(S=(f=this.player.getSettings().streaming)===null||f===void 0?void 0:f.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},f=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:f}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(j(({mediaType:f})=>f==="video"),$(({state:f})=>f==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:f,request:{url:S}})=>{var g,E;const D=this.player.getDashMetrics(),w=D.getLatestFragmentRequestHeaderValueByID(f,"X-Reused"),A=(g=D.getLatestFragmentRequestHeaderValueByID(f,"X-Delivery-Type"))!==null&&g!==void 0?g:Ci.HTTP1,B=(E={1:!0,0:!1}[w])!==null&&E!==void 0?E:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(ke(S))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:f,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(f),this.videoTracks=[];const E=this.player.getQualityFor("video");let D;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),B=Ut(w),X=w.bitrate/1e3,Y={width:w.width,height:w.height},F=this.frameRatesByFrameHeight[w.height];if(B){const Z={id:A,quality:B,bitrate:X,size:Y,fps:F};this.videoTracks.push({track:Z,bitrateInfo:w}),w.qualityIndex===E&&(D=Z)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:w})=>w)),D&&e.currentVideoTrack$.next(D),this.videoState.setState(z.STREAM_INITIALIZED),this.videoState.startTransitionTo(z.READY)}),r(be(this.player,"fragmentLoadingCompleted"),({request:f})=>{if(!f.requestEndDate||!f.firstByteDate||!f.bytesLoaded)return;const S=f.requestEndDate.getTime()-f.firstByteDate.getTime(),g=f.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(L(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const f=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=qi(this.videoTracks.map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:f,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:E})=>E===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(ut({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(_))}).pipe(j(({isLive:f})=>f),$(({maxSeekBackTime:f})=>-f/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe($(({time:f})=>f!=null?f:0));r(ut({availableFrom:this.availableFrom$.pipe(j(_)),currentTime:n}),({availableFrom:f,currentTime:S})=>this.params.output.liveTime$.next(f+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($(()=>bu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),k(t.playbackState,v.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,v.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),k(t.playbackState,v.PAUSED)}),r(be(this.player,"canPlay"),()=>{var f;((f=this.videoState.getTransition())===null||f===void 0?void 0:f.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(Ds(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=ng(this.player);r(l,this.params.output.httpConnectionType$),r(c,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(ut({isLive:this.isLive$,isShort:e.duration$.pipe($(f=>f<60))}),({isLive:f,isShort:S})=>{const g=!f&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(j(f=>f>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(),Lt(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Ft(this.video,t.isLooped,s));const{volumeState$:h,looped$:p,playbackRateState$:m}=St(this.video);this.subscription.add(vt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Et(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),k(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=ii(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ti.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 ji=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}},$t=i=>le(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 yu(i){return Ae()-i}function _o(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 $s(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,p="arraybuffer",m=7e3,f=2e3,S=()=>{if(u)return;P(l);const N=yu(l);let ie;if(N<f){ie=f-N,setTimeout(S,ie);return}f*=2,f>m&&(f=m),n&&n.abort(),n=new r,B()};const g=N=>(a=N,V),E=N=>(c=N,V),D=()=>(p="json",V),w=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,c&&c(),t&&t()}},A=N=>(h=N,V),B=()=>{l=Ae(),n=new r,n.open("get",i);let N=0,ie,ce=0;const Se=()=>(P(l),Math.max(l,Math.max(ie||0,ce||0)));if(a&&n.addEventListener("progress",R=>{const G=Ae();a.updateChunk&&R.loaded>N&&(a.updateChunk(Se(),R.loaded-N),N=R.loaded,ie=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&a){const G=n.response.byteLength-N;G&&a.updateChunk&&a.updateChunk(Se(),G)}c&&c(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const R=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=Ae(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=p,n.send(),V},V={withBitrateReporting:g,withParallel:A,withJSONResponse:D,withRetryCount:N=>(d=N,V),withRetryInterval:(N,ie)=>(_(N)&&(f=N),_(ie)&&(m=ie),V),withTimeout:N=>(o=N,V),withFinally:E,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}const xg=100,Lg=2e3,Og=500;let Bg=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-Og;if(t-e>Lg){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>xg&&(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 Ng{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=$s(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 cs=1e4,hs=3,Mg=300,Ug=2e3,Fg=6e4,Vg=10,Hg=1,Gg=500;class Yg{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 Bg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=_o(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=_o(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 Ng(hs,cs,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,l=!1;const c=()=>{const w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,A,B)=>{u&&u.abort(),u=$s(this.urlResolver.resolve(w,!1),A,B,()=>this._retryCallback()).withTimeout(cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(hs).withFinally(()=>{u=null}).send()},p=(w,A,B)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{const A=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),s.playbackRate=w)},f=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 B=Ae()-1e4;let X=0;for(let F=0;F<this.bufferStates.length;F++){const Z=this.bufferStates[F];w=Math.min(w,Z.buf),Z.ts<B&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${w} drop=${X} jitter=${this.sourceJitter}`);let Y=w-Hg;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 B=()=>A&&A.start?A.start.length:0,X=R=>A.start[R]/1e3,Y=R=>A.dur[R]/1e3,F=R=>A.fragIndex+R,Z=(R,G)=>({chunkIdx:F(R),startTS:X(R),dur:Y(R),discontinuity:G}),V=()=>{let R=0;if(A&&A.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=G;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(ve-=A.dur[ge],!(ve<=0));--ge);R=Math.min(ge,A.dur.length-1-oe),R=Math.max(R,0)}return Z(R,!0)},N=R=>{const G=B();if(!(G<=0)){if(_(R)){for(let oe=0;oe<G;oe++)if(X(oe)>R)return Z(oe)}return V()}},ie=R=>{const G=B(),oe=R?R.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(G<=0)){if(!R||ve<0||ve-G>Vg)return t(`Resync: offset=${ve} bChunks=${G} chunk=`+JSON.stringify(R)),V();if(!(ve>=G))return Z(oe-A.fragIndex,!1)}},ce=(R,G,oe)=>{d&&d.abort(),d=$s(this.urlResolver.resolve(R,!0,this.lowLatency),G,oe,()=>this._retryCallback()).withTimeout(cs).withRetryCount(hs).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(R,G)=>{ce(w,oe=>{if(!c())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&f(ve);let ge=0;for(let Ie=0;Ie<A.dur.length;++Ie)ge+=A.dur[Ie];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,R(N(G))},()=>this._handleNetworkError())},nextChunk:ie}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:A,logger:B}=this.params;let X=g(e.jidxUrl),Y,F,Z,V,N=0,ie,ce,Se;const R=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(Gg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=N+ee,Pe=Ae(),Oe=Math.min(1e4,Ee-Pe);N=Pe;const At=()=>{d||c()&&X.seek(()=>{c()&&(N=Ae(),G(),R())})};Oe>0?ie=window.setTimeout(()=>{this.paused?R():At()},Oe):At()},G=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,Qe(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}Ie(Ee)}else R()},oe=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let Pe,Oe,At;const Je=gt=>{window.setTimeout(()=>{c()&&oe(ee,Ee)},gt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Je(100);else{const gt=Ae(),_t=A.currentTime;!this.paused&&A.buffered.length>1&&ce===_t&&gt-Se>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),ce!==_t&&(ce=_t,Se=gt);const hi=this._getBufferSizeSec();if(hi>30)B(`Buffered ${hi} seconds; delaying appendBuffer`),Je(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:gt,buf:hi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Vt){if(Vt.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),At=this.sourceBuffer.buffered.length,At!==0&&(Pe=this.sourceBuffer.buffered.start(0),Oe=_t,Oe-Pe>4&&this.sourceBuffer.remove(Pe,Oe-3)),Je(1e3);else throw Vt}}},ve=()=>{F&&Y&&(B([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Z)]),oe(F,function(){F=null,G()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ie=ee=>{c()&&p(ge(ee),(Ee,Pe)=>{if(c()){if(Pe/=1e3,F=Ee,Z=ee,n=ee.startTS,Pe){const Oe=Math.min(10,ee.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}ve()}},()=>this._handleNetworkError())},Qe=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},ci=ee=>{c()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(c()){if(N=Ae(),!ee){R();return}V=ee,!K(w)||ee.startTS>w?Ie(ee):(Z=ee,G())}},w),e.cachedHeader?ci(e.cachedHeader):h(e.headerUrl,ci,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_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=c=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),m=c/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,p)=>{const m=Ae();if(this.chunkRateEstimator.addInterval(h,m,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,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 c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&yu(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const p=a.updateChunk(c,h);return p&&d(),p},notifySwitch:c=>{const h=Ae();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=$s(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(cs).withRetryCount(hs).withRetryInterval(Mg,Ug).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;$t(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))},Fg))}_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 qg=[W.PAUSED,W.PLAYING,W.READY],jg=[W.PAUSED,W.PLAYING,W.READY];class zg{constructor(e){this.subscription=new se,this.videoState=new ue(W.STOPPED),this.representations$=new b([]),this.textTracksManager=new st,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Ya,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:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),p=(n=ji(c.name))!==null&&n!==void 0?n:Ut(c.video),m=c.bitrate/1e3,f=Object.assign({},c.video);if(!p)continue;const S={id:h,quality:p,bitrate:m,size:f};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===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(jg.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;_(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==v.PAUSED&&d.state===H.Requested&&qg.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(ii(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 l=u==null?void 0:u.from;l&&l===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 O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};L(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=mt(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=St(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===H.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(ut({zeroTime:this.zeroTime$.pipe(j(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ft(this.video,this.params.desiredState.isLooped,t)).add(vt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Et(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&&JS(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 O(r.to)}},t)).add(L(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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 Yg({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(),l=!d&&_(u)?u:(a=qi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const 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(ii(this.params.source.url,s))}}var Tu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?Ci.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}},Dt=(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 Wg=i=>{const e=document.createElement("a");return e.href=i,e.origin},Qg=i=>{const e=document.createElement("a");return e.href=i,e.host};class Eu{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 l=Hi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var 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(Qg(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 Cs{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 l=0,c=0,h=0;const p=f=>{r(Cs._str2ua(f.substr(u))),u=f.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ri(m)),this._lastXhr=new Eu(m,e.failoverHosts,f=>{this._lastXhr=void 0,p(f);const S=Date.now()-d;this._params.onBandwidthChange({size:f.length,duration:S,speed:8*f.length/(S/1e3)}),this._onDashCallback("loading",{size:f.length,done:!0}),a==null||a()},f=>{if(f.length-u>o&&p(f),c===0){c=Date.now();return}h=f.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=f.length,c=Date.now()),this._onDashCallback("loading",{size:f.length,done:!1})},n,(f,S,g)=>this._params.onError(f,S,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(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=Cs._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 Jg{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=ri(s)),new Eu(s,t,r=>{this.attachManifest(r,t,Wg(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,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,p,m,f,S,g,E,D,w,A,B,X,Y,F,Z,V,N;const ie=d.getElementsByTagName("SegmentBase")[0],ce=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],R=Se&&n(Se,"range").split("-");if(!R||!ce){const Qe=d.parentElement;if((Qe==null?void 0:Qe.getAttribute("contentType"))==="text"){const ci=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(s?s+"/":"")+((m=(p=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),Ee=(f=Qe.getAttribute("lang"))!==null&&f!==void 0?f:void 0;ee&&u.push({id:ci,url:ee,language:Ee})}return}const G=.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 Ie=(E=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&E!==void 0?E:void 0;ge=Ie?qa(Ie):void 0,o.push({width:Number((D=d.attributes.getNamedItem("width"))===null||D===void 0?void 0:D.value),height:Number((w=d.attributes.getNamedItem("height"))===null||w===void 0?void 0:w.value),bandwidth:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(ce[0]),indexTo:Number(ce[1]),initFrom:Number(R[0]),initTo:Number(R[1]),codecs:(B=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&B!==void 0?B: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:G*oe/8,bufferLength:G,name:(Z=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Z!==void 0?Z:void 0,id:(N=(V=d.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.value)!==null&&N!==void 0?N:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const 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 l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const p=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:p-1}),d=p,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-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 p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}c=p.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Cs({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 Kg=[Q.PAUSED,Q.PLAYING];class Xg{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 st,this.elementSize$=new b(void 0),this.dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x},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&&ji(o.name))!==null&&a!==void 0?a:Ut(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const p={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:p,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(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),k(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==v.PAUSED&&n.state===H.Requested&&Kg.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?k(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(Q.PAUSED),k(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&&k(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&&k(this.params.desiredState.playbackState,v.PAUSED);return;default:return O(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),L(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=mt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new cg(this.video),this.dash=new Jg({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:C.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:C.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=St(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$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==H.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(Ft(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(Ds(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),k(this.params.desiredState.playbackState,v.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),k(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:C.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(L(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$,U(this.video,"progress")).pipe($(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(p))g=p;else{const E=Dt(this.video.buffered,this.video.currentTime*1e3),D=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(E/D,1);g=(u=qi(c.map(({track:A})=>A),{container:f,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=c.find(({track:E})=>E.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(ut({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=Dt(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(ke(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=Tu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),Lt(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(L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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 O(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),k(this.params.desiredState.playbackState,v.PAUSED,!0))})}}var Me;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Me||(Me={}));var xs;(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"})(xs||(xs={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));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 ai;(function(i){i.MP4="mp4",i.WEBM="webm"})(ai||(ai={}));var Ls;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Ls||(Ls={}));var ga=(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 Zg=(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)},eb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",wo=eb?Zg:window.requestIdleCallback;var xr,Lr;let $u=!1;try{$u=gu()&&parseInt((Lr=(xr=navigator.userAgent.match(/Version\/(\d+)/))===null||xr===void 0?void 0:xr[1])!==null&&Lr!==void 0?Lr:"",10)<16}catch(i){console.error(i)}class tb{constructor(e){this.bufferFull$=new x,this.error$=new x,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:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return le(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 le(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 le(this,void 0,void 0,function*(){return new Promise(t=>{let s;$u&&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:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:O(t)}}}var Ro=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class rt{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Au extends rt{}class ib extends rt{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class sb extends rt{parseChildrenBoxes(){return li(this.content)}}class rb extends rt{constructor(e){super(e),this.data=this.content}}class zi extends rt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class ab extends zi{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class nb extends rt{parseChildrenBoxes(){return li(this.content)}}class ob extends rt{parseChildrenBoxes(){return li(this.content)}}var It;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(It||(It={}));class db extends zi{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=It.MONOSCOPIC;break;case 1:this.stereoMode=It.TOP_BOTTOM;break;case 2:this.stereoMode=It.LEFT_RIGHT;break;case 3:this.stereoMode=It.STEREO_CUSTOM;break;case 4:this.stereoMode=It.RIGHT_LEFT;break}this.cursor+=1}}class ub extends zi{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class lb extends zi{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class cb extends rt{parseChildrenBoxes(){return li(this.content)}}class hb extends zi{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class fb extends rt{parseChildrenBoxes(){return li(this.content)}}class pb extends rt{parseChildrenBoxes(){return li(this.content)}}const vb={ftyp:ib,moov:sb,mdat:rb,sidx:ab,trak:nb,mdia:cb,tkhd:hb,minf:fb,sv3d:ob,st3d:db,prhd:ub,proj:pb,equi:lb,unknown:Au};class mb{createBox(e,t){const s=vb[e];return s?new s(t):new Au(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ws.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Ws=new mb;function wi(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const a=t.decode(new DataView(i.buffer,s,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+o>i.byteLength?null:Ws.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function Sb(i,e){const t=[];let s=i.byteOffset;for(;s<i.byteLength;){const r=wi(new DataView(i.buffer,s,i.byteLength),e);if(r)t.push(r),s+=r.source.byteOffset+r.source.byteLength;else break}return t}function li(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Ws.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const gb=new TextDecoder("ascii"),bb=i=>gb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",yb=i=>{const e=Ws.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Tb=i=>{const e=Sb(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},Eb=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ls.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(wi(i,"sv3d")){e.is3dVideo=!0;const s=wi(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=wi(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=wi(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},$b={validateData:bb,parseInit:Eb,getIndexRange:()=>{},parseSegments:yb,parseFeedableSegmentChunk:Tb};var T;(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.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",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"})(T||(T={}));var I;(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"})(I||(I={}));const Po={[T.EBML]:{type:I.Master},[T.EBMLVersion]:{type:I.UnsignedInteger},[T.EBMLReadVersion]:{type:I.UnsignedInteger},[T.EBMLMaxIDLength]:{type:I.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[T.DocType]:{type:I.String},[T.DocTypeVersion]:{type:I.UnsignedInteger},[T.DocTypeReadVersion]:{type:I.UnsignedInteger},[T.Void]:{type:I.Binary},[T.Segment]:{type:I.Master},[T.SeekHead]:{type:I.Master},[T.Seek]:{type:I.Master},[T.SeekID]:{type:I.Binary},[T.SeekPosition]:{type:I.UnsignedInteger},[T.Info]:{type:I.Master},[T.TimestampScale]:{type:I.UnsignedInteger},[T.Duration]:{type:I.Float},[T.Tracks]:{type:I.Master},[T.TrackEntry]:{type:I.Master},[T.Video]:{type:I.Master},[T.Projection]:{type:I.Master},[T.ProjectionType]:{type:I.UnsignedInteger},[T.ProjectionPrivate]:{type:I.Master},[T.Chapters]:{type:I.Master},[T.Cluster]:{type:I.Master},[T.Timestamp]:{type:I.UnsignedInteger},[T.SilentTracks]:{type:I.Master},[T.SilentTrackNumber]:{type:I.UnsignedInteger},[T.Position]:{type:I.UnsignedInteger},[T.PrevSize]:{type:I.UnsignedInteger},[T.SimpleBlock]:{type:I.Binary},[T.BlockGroup]:{type:I.Master},[T.EncryptedBlock]:{type:I.Binary},[T.Attachments]:{type:I.Master},[T.Tags]:{type:I.Master},[T.Cues]:{type:I.Master},[T.CuePoint]:{type:I.Master},[T.CueTime]:{type:I.UnsignedInteger},[T.CueTrackPositions]:{type:I.Master},[T.CueTrack]:{type:I.UnsignedInteger},[T.CueClusterPosition]:{type:I.UnsignedInteger},[T.CueRelativePosition]:{type:I.UnsignedInteger},[T.CueDuration]:{type:I.UnsignedInteger},[T.CueBlockNumber]:{type:I.UnsignedInteger},[T.CueCodecState]:{type:I.UnsignedInteger},[T.CueReference]:{type:I.Master},[T.CueRefTime]:{type:I.UnsignedInteger}},_u=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=Os(i,t),r=s in Po,a=r?Po[s].type:I.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,l=Os(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let p;return h+c>i.byteLength?p=new DataView(i.buffer,i.byteOffset+h):p=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Os=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(i,e)=>{switch(e){case I.SignedInteger:return i.getInt8(0);case I.UnsignedInteger:return Os(i);case I.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(i);case I.UTF8:return new TextDecoder("utf-8").decode(i);case I.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case I.Master:return i;case I.Binary:return i;default:O(e)}},ni=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=_u(s);if(!e(r))return;r.type===I.Master&&ni(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Ab=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=_u(i);return ni(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=et(o,n):a===T.DocType?t=et(o,n):a===T.DocTypeReadVersion&&(s=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},wu=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],_b=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],wb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ni(i,({tag:h,type:p,value:m,valueSize:f})=>{if(h===T.SeekID){const S=et(m,p);d=Os(S)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=m.byteOffset,t=m.byteOffset+f):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=et(m,p):h===T.Duration?r=et(m,p):h===T.SeekPosition&&d===T.Cues?u=et(m,p):h===T.Tracks?ni(m,({tag:S,type:g,value:E})=>S===T.ProjectionType?(l=et(E,g)===1,!1):!0):a&&n&&wu.includes(h)&&(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,is3dVideo:l,stereoMode:c,projectionType:Ls.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Rb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Pb=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return ni(i,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=et(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=et(d,u));break;default:t&&wu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},kb=i=>{let e=0,t=!1;try{ni(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):_b.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ib={validateData:Ab,parseInit:wb,getIndexRange:Rb,parseSegments:Pb,parseFeedableSegmentChunk:kb};class ko{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.playingRepresentationInit$=new b(void 0),this.error$=new x,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ct,this.destroyAbortController=new Ct,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new tb(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},f=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:f}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(f=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Ro(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),f)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(f=>this.error$.next(f))),yield yield M(this.loadInit(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id),p=this.parsedInitData.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield M(void 0);let m=0;for(const f of h)f.time.from-m>0&&this.gaps.push({representation:l.id,from:m,to:f.time.from}),m=f.time.to;_(l.duration)&&l.duration-m>0&&this.gaps.push({representation:l.id,from:m,to:l.duration}),yield yield M(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(p)})}.bind(this)),this.switchTo=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(K(c)?yield yield M(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield M(c)),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal));const h=this.getCurrentPosition();_(h)&&this.maintain(h)})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case ai.MP4:this.containerParser=$b;break;case ai.WEBM:this.containerParser=Ib;break;default:O(s)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=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 Ct,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 l=Dt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Ro(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Dt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=ot(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&Dt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=ot(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.parsedInitData.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:c,time:{from:h,to:p}},m)=>{const f=h<=s&&p>=s,S=h>s||f||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+g||p<=s+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&S&&E&&this.sourceBuffer&&!ga(this.sourceBuffer.buffered,s))&&S&&E});if(r===-1)return[];if(t!==Ue.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return le(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ue.BYTE_RANGE:{r=t.segmentReference.url,a={from:ot(e,0).byte.from,to:ot(e,-1).byte.to};break}case Ue.TEMPLATE:{const d=ot(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:O(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 qe(u,function(){return je(this,arguments,function*(){const d=rn(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(s=Dt((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:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(h=this.segments.get(p.id))!==null&&h!==void 0?h:[])m.status===te.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=te.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,p=d===Ue.BYTE_RANGE,m=p?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!p||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const S=p?h.byte.from-s:0,g=p?h.byte.to-s:e.byteLength,E=S<r,D=g<=r;if(h.status===te.DOWNLOADING&&E&&D){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const w=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(m,r-S),c.loadedBytes>c.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===m?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(B=>{if(a.aborted)n();else if(B)c.fedBytes+=A.byteLength,c.fedBytes===m&&o(c);else{if(c.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=wo(()=>js(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return le(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?qe(this.destroyAbortController.signal,function(){return je(this,arguments,function*(){const o=rn(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{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,l),this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return le(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 l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const p of h)if(p.status===te.NONE&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const 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=wo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:C.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(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Zt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Zt||(Zt={}));class Db{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 Ct,this.subscription=new se,this.fetchManifest=qe(this.abortAllController.signal,function(r){return je(this,arguments,function*(){let a=r;this.requestQuic&&(a=ri(a));const n=yield yield M(si(a,{signal:this.abortAllController.signal}).catch(_i));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=qe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Zt.HEADER:Zt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,p,m;return je(this,arguments,function*(){let f=r;const S=new Headers;if(n)switch(a){case Zt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Zt.PARAM:{const R=new URL(f,location.href);R.searchParams.append("bytes",`${n.from}-${n.to}`),f=R.toString();break}default:O(a)}this.requestQuic&&(f=ri(f));let g=this.abortAllController.signal;if(d){const R=new Ct;if(this.subscription.add(L(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{R.abort()}catch(G){_i(G)}})),this.abortAllController.signal.aborted||d.aborted)try{R.abort()}catch(G){_i(G)}g=R.signal}const E=pe(),D=yield yield M(si(f,{priority:u,headers:S,signal:g}).catch(_i)),w=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(w-E),!D)return yield M(null);if(!D.ok||!D.body)return yield M(Promise.reject(new Error(`Fetch error ${D.status}: ${D.statusText}`)));this.onHeadersReceived(D.headers);const A=parseInt((h=D.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const R=yield yield M(D.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(R.byteLength,pe()-w),o==null||o(new DataView(R),R.byteLength),yield M(R)}if(!o&&!l)return yield M(D.arrayBuffer());const[B,X]=D.body.tee(),Y=B.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let F=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),N=new DataView(Z);let ie=!1;const ce=R=>{ie=!0,_i(R)},Se=qe(g,function({done:R,value:G}){return je(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(pe()-E),g.aborted)return yield M(void 0);R?o==null||o(N,F):G&&(V.set(G,F),F+=G.byteLength,o==null||o(N,F),yield yield M(Y==null?void 0:Y.read().then(Se,ce)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,ce)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=qe(this.abortAllController.signal,function(r,a,n){var o;return je(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,p,m;r.indexRange&&(p=r.indexRange.from,m=r.indexRange.to,h=d+1===p,h&&(l=Math.min(p,u),c=Math.max(m,d))),l=Math.min(l,0);const f=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!f)return yield M(null);const S=new DataView(f,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!E)throw new ReferenceError("No way to load representation index");let D;if(h)D=new DataView(f,E.from-l,E.to-E.from+1);else{const A=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!A)return yield M(null);D=new DataView(A)}const w=a.parseSegments(D,g,E);return yield M({init:g,dataView:new DataView(f),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=qe(this.abortAllController.signal,function(r,a){return je(this,arguments,function*(){if(r.type!==Ue.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({init:{},segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Tu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return le(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:O(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _i=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var Cb=ht,xb=Bi,Lb=Re,Ob=Lb("match"),Bb=function(i){var e;return Cb(i)&&((e=i[Ob])!==void 0?!!e:xb(i)=="RegExp")},Nb=Vi,Mb=String,Ub=function(i){if(Nb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Mb(i)},Fb=pt,Vb=function(){var i=Fb(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Hb=Le,Gb=it,Yb=Ns,qb=Vb,Io=RegExp.prototype,jb=function(i){var e=i.flags;return e===void 0&&!("flags"in Io)&&!Gb(i,"flags")&&Yb(Io,i)?Hb(qb,i):e},za=Ge,zb=Vs,Wb=Math.floor,Or=za("".charAt),Qb=za("".replace),Br=za("".slice),Jb=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Kb=/\$([$&'`]|\d{1,2})/g,Xb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=Kb;return r!==void 0&&(r=zb(r),u=Jb),Qb(a,u,function(d,l){var c;switch(Or(l,0)){case"$":return"$";case"&":return i;case"`":return Br(e,0,t);case"'":return Br(e,n);case"<":c=r[Br(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var p=Wb(h/10);return p===0?d:p<=o?s[p-1]===void 0?Or(l,1):s[p-1]+Or(l,1):d}c=s[h-1]}return c===void 0?"":c})},Zb=We,ey=Le,Wa=Ge,Do=ya,ty=Te,iy=Ni,sy=Bb,zt=Ub,ry=Fs,ay=jb,ny=Xb,oy=Re,dy=oy("replace"),uy=TypeError,Ru=Wa("".indexOf),ly=Wa("".replace),Co=Wa("".slice),cy=Math.max,xo=function(i,e,t){return t>i.length?-1:e===""?t:Ru(i,e,t)};Zb({target:"String",proto:!0},{replaceAll:function(e,t){var s=Do(this),r,a,n,o,u,d,l,c,h,p=0,m=0,f="";if(!iy(e)){if(r=sy(e),r&&(a=zt(Do(ay(e))),!~Ru(a,"g")))throw uy("`.replaceAll` does not allow non-global regexes");if(n=ry(e,dy),n)return ey(n,e,s,t);if(r)return ly(zt(s),e,t)}for(o=zt(s),u=zt(e),d=ty(t),d||(t=zt(t)),l=u.length,c=cy(1,l),p=xo(o,u,0);p!==-1;)h=d?zt(t(u,p,o)):ny(u,o,p,[],void 0,t),f+=Co(o,m,p)+h,m=p+l,p=xo(o,u,p+c);return m<o.length&&(f+=Co(o,m)),f}});var hy=Ga,fy=hy("String","replaceAll"),py=fy,vy=py,my=vy,Sy=my,Lo=Sy;const Oo=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},Nr=(i,e)=>{let t=i;t=Lo(t,"$$","$");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=Lo(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},gy=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,p,m,f,S,g,E,D,w,A,B,X,Y,F,Z,V,N,ie,ce,Se,R,G,oe,ve,ge,Ie,Qe;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},Pe=ee.children[0],Oe=Pe.getElementsByTagName("Period")[0],At=Oe.children;let Je;const gt=Pe.getAttribute("mediaPresentationDuration"),_t=Oe.getAttribute("duration");if(gt)Je=Oo(gt);else if(_t){const Ke=Oo(_t);_(Ke)&&(Je=Ke)}let hi=0;const Vt=(s=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],xu=Vt.includes(xs.WEBM_AS_IN_FFMPEG)||Vt.includes(xs.WEBM_AS_IN_SPEC)?ai.WEBM:ai.MP4;for(const Ke of At){const Wi=Ke.getAttribute("mimeType"),Lu=Ke.getAttribute("codecs"),Qa=(r=Ke.getAttribute("contentType"))!==null&&r!==void 0?r:Wi==null?void 0:Wi.split("/")[0],Ou=(n=(a=Ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Bu=Ke.querySelectorAll("Representation"),Nu=Ke.querySelector("SegmentTemplate");if(Qa!=="text")for(const $e of Bu){const fi=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Wi,Ja=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:Lu)!==null&&d!==void 0?d:"",Qi=(c=(l=$e.getAttribute("contentType"))!==null&&l!==void 0?l:fi==null?void 0:fi.split("/")[0])!==null&&c!==void 0?c:Qa,Mu=(p=(h=Ke.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&p!==void 0?p:[],Uu=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Ka=parseInt((f=$e.getAttribute("height"))!==null&&f!==void 0?f:"",10),Xa=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Za=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Fu=(E=$e.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Vu=Za?qa(Za):void 0,Hu=(D=$e.getAttribute("id"))!==null&&D!==void 0?D:(hi++).toString(10),Gu=Qi==="video"?`${Ka}p`:Qi==="audio"?`${Xa}Kbps`:Ja,Yu=`${Hu}@${Gu}`,qu=(B=(A=(w=$e.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&B!==void 0?B:"",en=new URL(qu,e).toString(),ju=[...Vt,...Ou,...Mu];let Js;const zu=$e.querySelector("SegmentBase"),wt=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:Nu;if(zu){const pi=(F=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&F!==void 0?F:"",[vi,Xs]=pi.split("-").map(Rt=>parseInt(Rt,10)),mi={from:vi,to:Xs},Si=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[Zs,Ji]=Si?Si.split("-").map(Rt=>parseInt(Rt,10)):[],gi=Si?{from:Zs,to:Ji}:void 0;Js={type:Ue.BYTE_RANGE,url:en,initRange:mi,indexRange:gi}}else if(wt){const pi={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(N=$e.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},vi=parseInt((ie=wt.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),Xs=(ce=wt.getAttribute("initialization"))!==null&&ce!==void 0?ce:"",mi=wt.getAttribute("media"),Si=(R=parseInt((Se=wt.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&R!==void 0?R:1,Zs=Nr(Xs,pi);if(!mi)throw new ReferenceError("No media attribute in SegmentTemplate");const Ji=(G=wt.querySelectorAll("SegmentTimeline S"))!==null&&G!==void 0?G:[],gi=[];if(Ji.length){let Rt=Si,Pt=0;for(const bi of Ji){const Ht=parseInt((oe=bi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,yi=parseInt((ve=bi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,Ti=(Ie=parseInt((ge=bi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Ie!==void 0?Ie:void 0;for(let tn=0;tn<yi+1;tn++){const Wu=Nr(mi,Object.assign(Object.assign({},pi),{segmentNumber:Rt.toString(10),segmentTime:Ti.toString(10)})),Qu=Ti?Ti/vi:Pt;Pt+=Ht/vi;const Ju=Pt;Rt++,gi.push({time:{from:Qu,to:Ju},url:Wu})}}}else if(_(Je)){const Pt=parseInt((Qe=wt.getAttribute("duration"))!==null&&Qe!==void 0?Qe:"",10)/vi*1e3,bi=Math.ceil(Je/Pt);let Ht=0;for(let yi=1;yi<bi;yi++){const Ti=Nr(mi,Object.assign(Object.assign({},pi),{segmentNumber:yi.toString(10),segmentTime:Ht.toString(10)}));gi.push({time:{from:Ht,to:Ht+Pt},url:Ti}),Ht+=Pt}}Js={type:Ue.TEMPLATE,baseUrl:en,initUrl:Zs,segments:gi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qi||!fi)continue;const Ks={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Qi];Ks&&Ee[Ks].push({id:Yu,kind:Ks,segmentReference:Js,profiles:ju,duration:Je,bitrate:Xa,mime:fi,codecs:Ja,width:Uu,height:Ka,fps:Vu,quality:Fu})}}return{duration:Je,container:xu,representations:Ee}},by=["timeupdate","progress","play","seeked","stalled","waiting"];var Ne;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ne||(Ne={}));let yy=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new ue(Ne.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new x,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new Ct,this.initManifest=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Ne.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=gy(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Hi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(Ne.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(Ne.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 ko(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new ko(Me.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=L(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=L(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(L(this.forceEnded$,ut({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:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(L(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),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(Ne.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=Xu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Db({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Ne.RUNNING),this.subscription.add(L(...by.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ga(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return le(this,void 0,void 0,function*(){const s={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.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),ga(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(Ne.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}}};const Ty=135,Ey=76;class $y{constructor(){this.fov={x:Ty,y:Ey},this.rotation={x:0,y:0,z:0}}}const Wt=10,Bo=175;class Ay{constructor(e,t={}){this.rotating=!1,this.torqueLossTS=0,this.hold=!1,this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+s)}pointCameraTo(e=0,t=0,s=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=s}setRotationSpeed(e,t,s){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),s===void 0&&(s=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=s,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-Bo,Math.min(e,Bo))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const s=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*s*Wt,this.rotationSpeed.y*s*Wt,this.rotationSpeed.z*s*Wt);else{let r=0,a=0,n=0;const o=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-o,0),r=this.rotationSpeed.x*s*Wt),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-o,0),a=this.rotationSpeed.y*s*Wt),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-o,0),n=this.rotationSpeed.z*s*Wt),this.turnCamera(r,a,n)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const _y=`
8
+ attribute vec2 a_vertex;
9
+ attribute vec2 a_texel;
10
+
11
+ varying vec2 v_texel;
12
+
13
+ void main(void) {
14
+ // direct vertex drawing
15
+ gl_Position = vec4(a_vertex, 0.0, 1.0);
16
+ // save texel vector to pass to fragment shader
17
+ v_texel = a_texel;
18
+ }
19
+ `,wy=`
20
+ #ifdef GL_ES
21
+ precision highp float;
22
+ precision highp int;
23
+ #else
24
+ precision mediumhp float;
25
+ #endif
26
+
27
+ varying vec2 v_texel; // [0..1, 0..1]
28
+
29
+ uniform sampler2D u_texture;
30
+ uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
31
+
32
+ const float PI = 3.14159265358979323846264;
33
+ const float PI_2 = PI * 0.5;
34
+ const float PI2 = PI * 2.0;
35
+
36
+ void main(void) {
37
+ // center point of output projection
38
+ float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
39
+ float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
40
+
41
+ float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
42
+ float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
43
+
44
+ float p = sqrt(x * x + y * y); // rou
45
+ float c = atan(p);
46
+ float cos_c = cos(c);
47
+ float sin_c = sin(c);
48
+
49
+ // geo coordinates of projection
50
+ float lambda = lambda0 + atan(
51
+ x * sin_c,
52
+ p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
53
+ );
54
+ float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
55
+
56
+ // reprojected texture coordinates
57
+ vec2 tc = vec2(
58
+ mod(lambda / PI2 - 0.5, 1.0), // [0..1]
59
+ mod(phi / PI - 0.5, 1.0) // [0..1]
60
+ );
61
+
62
+ // sample using new coordinates
63
+ gl_FragColor = texture2D(u_texture, tc);
64
+ }
65
+ `;class Ry{constructor(e,t,s={}){this.videoInitialized=!1,this.lastCameraRotationX=0,this.lastCameraRotationY=0,this.lastCameraRotationT=0,this.lastCameraRotationDX=0,this.lastCameraRotationDY=0,this.mouseDown=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.options=s,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new $y,this.cameraRotationManager=new Ay(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,s){this.cameraRotationManager.setRotationSpeed(e,t,s),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e==null||e()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.rotation.x,-this.camera.rotation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(_y,this.gl.VERTEX_SHADER),s=this.createShader(wy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.rotation.x/360,t=.5-this.camera.rotation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,l=t+r,c=e-s,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,s=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+s),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=s,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));const Py=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?ji(a):void 0)!==null&&n!==void 0?n:Ut({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},ky=({id:i,bitrate:e})=>({id:i,bitrate:e}),Iy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ot(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ot(i,-1)};class Dy{constructor(e){this.subscription=new se,this.videoState=new ue(he.STOPPED),this.elementSize$=new b(void 0),this.textTracksManager=new st,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new kg,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===H.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),k(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),k(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.READY&&k(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&&k(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&&k(this.params.desiredState.playbackState,v.PAUSED);return;default:return O(t)}}},this.init3DScene=t=>{this.scene3D||(this.scene3D=new Ry(this.params.container,this.video,t),this.scene3D.play())},this.destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})},this.params=e,this.video=mt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new yy({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=St(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:C.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,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(s.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(_),ye(),Lt(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ft(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Et(this.video,t.playbackRate,s.playbackRateState$,r)),a(Ds(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),k(t.playbackState,v.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),k(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 l;if(d===Ne.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((f,S)=>S.bitrate-f.bitrate),p=Array.from(c.video).sort((f,S)=>S.bitrate-f.bitrate);if(!this.params.tuning.isAudioDisabled)for(const f of h){const S=ky(f);S&&this.audioTracks.push({track:S,representation:f})}for(const f of p){const S=Py(f);if(S){this.videoTracks.push({track:S,representation:f});const g=!this.params.tuning.isAudioDisabled&&Iy(h,p,f);g&&this.audioRepresentations.set(f.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(l=this.audioRepresentations.get(m.id))===null||l===void 0?void 0:l.id)}else d===Ne.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(L(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Ne.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Me.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),$(d=>{var l;return d&&((l=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d)if(d.is3dVideo)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){}else this.destroy3DScene(),e.is3DVideo$.next(!1)},r)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const d=this.params.desiredState.cameraRotation.getState();d?this.scene3D.startCameraRotation(d.x,d.y,d.z):this.scene3D.stopCameraRotation(!1)}}),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===v.READY),me());this.subscription.add(L(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(L(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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,l=this.params.output.currentVideoTrack$.getValue(),c=Dt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),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,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),f=qi(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:p,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?f!=null?f:d:d!=null?d:f;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}prepare(){return le(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.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),k(this.params.desiredState.playbackState,v.PAUSED,!0))})}}const Cy=5e3,at={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const fs=(i,e)=>new Oi(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class xy{constructor(e){this.subscription=new se,this.videoState=new ue(J.INITIALIZING),this.textTracksManager=new st,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===H.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:O(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:O(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:O(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),k(this.params.desiredState.playbackState,v.PAUSED);break;case J.PLAYING:this.pause();break;default:O(t)}break;default:O(s)}},this.video=mt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(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:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Cy);js(import("hls.js/dist/hls.min.js").then(r=>{e||(at.Hls=r.default,at.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(at.Hls,"hls.js not loaded"),this.hls=new at.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(at.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=St(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,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$),a(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Ft(this.video,e.isLooped,s)),this.subscription.add(vt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(fs(this.hls,at.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),k(e.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),k(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(fs(this.hls,at.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,p;const m=c.name||c.height.toString(10),{width:f,height:S}=c,g=(p=ji((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&p!==void 0?p:Ut({width:f,height:S});if(!g)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,D={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:f,height:S},fps:E};return this.trackLevels.set(m,{track:D,level:c}),l.push(D),l},[]))),t.availableVideoTracks$),a(fs(this.hls,at.Events.LEVEL_LOADING).pipe($(({url:d})=>ke(d))),t.hostname$),this.subscription.add(tt(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 l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=fs(this.hls,at.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(tt(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(K(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),p=this.hls.currentLevel,m=this.hls.levels[p];!m||c.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=L(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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 le(this,void 0,void 0,function*(){this.videoState.startTransitionTo(J.PLAYING),(yield $t(this.video))||(this.videoState.setState(J.PAUSED),k(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),k(this.params.desiredState.playbackState,v.STOPPED,!0)}}const No="X-Playback-Duration";var Mo=i=>le(void 0,void 0,void 0,function*(){const e=yield si(i,{method:"HEAD"});return e.headers.has(No)?parseInt(e.headers.get(No),10):void 0});const Ly=i=>{let e=null;if(i.QUALITY&&(e=ji(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ut({width:t,height:s})}return e!=null?e:null},Pu=(i,e=i)=>le(void 0,void 0,void 0,function*(){var t;const a=(yield(yield si(i)).text()).split(`
66
+ `),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=Hi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Ly(l);let p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let f;if(l.RESOLUTION){const[g,E]=l.RESOLUTION.split("x").map(D=>parseInt(D,10));g&&E&&(f={width:g,height:E})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:p,size:f,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 Oy{constructor(e){var t;this.subscription=new se,this.videoState=new ue(re.STOPPED),this.textTracksManager=new st,this.manifests$=new b([]),this.liveOffset=new Ya,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),k(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==v.PAUSED&&l.state===H.Requested){this.videoState.startTransitionTo(re.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case re.READY:a===v.READY?k(this.params.desiredState.playbackState,v.READY):a===v.PAUSED?(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),k(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&&k(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&&(k(this.params.desiredState.playbackState,v.PAUSED),this.liveOffset.pause());return;case re.CHANGING_MANIFEST:break;default:return O(r)}},this.params=e,this.video=mt(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]),Pu(ii(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(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(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=St(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(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),k(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),k(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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ke(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===re.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===H.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},s)),this.subscription.add(ut({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:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,xe(["init"])).pipe(Ve(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=ii(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{si(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(l=>{K(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),k(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 By{constructor(e){this.subscription=new se,this.videoState=new ue(de.STOPPED),this.textTracksManager=new st,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),k(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 l=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==v.PAUSED&&d.state===H.Requested&&this.seek(d.position),s){case de.READY:r===v.READY?k(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(de.PAUSED),k(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&&k(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&&k(this.params.desiredState.playbackState,v.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return O(s)}},this.params=e,this.video=mt(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.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(this.params.source.url)),Pu(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.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(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=St(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ft(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(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),k(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),k(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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ke(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===H.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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(){$t(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),k(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 Ny{constructor(e){this.subscription=new se,this.videoState=new ue(fe.STOPPED),this.trackUrls={},this.textTracksManager=new st,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),k(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===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==v.PAUSED&&o.state===H.Requested&&this.seek(o.position),t){case fe.READY:s===v.READY?k(this.params.desiredState.playbackState,v.READY):s===v.PAUSED?(this.videoState.setState(fe.PAUSED),k(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&&k(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&&k(this.params.desiredState.playbackState,v.PAUSED);return;default:return O(t)}},this.params=e,this.video=mt(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.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=St(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ft(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),k(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),k(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=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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=ri(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(ke(r))}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),k(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Uo=["stun:videostun.mycdn.me:80"],My=1e3,Uy=3,Mr=()=>null;class Fy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Mr,this.externalStopCallback=Mr,this.externalErrorCallback=Mr,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 le(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 le(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Uo}]};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 le(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 le(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:C.WTF,message:e.message})}onPeerConnectionStream(e){return le(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 le(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),My)}normalizeOptions(e={}){const t={stunServerList:Uo,maxRetryNumber:Uy,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 Vy{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),k(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),k(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&&k(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&&k(this.params.desiredState.playbackState,v.PAUSED);return;default:return O(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=mt(e.container),this.liveStreamClient=new Fy(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:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};L(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=St(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===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(vt(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 O(n.to)}},s)).add(L(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ve(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ne.INVARIANT}),this.video.srcObject=e,k(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:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),k(this.params.desiredState.playbackState,v.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class Fo{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 Hy=()=>{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")},Ur,Fr,Vr,Hr,Gr,Yr,ps,qr,vs,jr,ms,zr,Ss,Wr,gs,Qr;const ku=Hy(),bt=document.createElement("video"),nt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Fr=(Ur=window.SourceBuffer)===null||Ur===void 0?void 0:Ur.prototype)===null||Fr===void 0?void 0:Fr.appendBuffer)),hls:Boolean(((Vr=bt.canPlayType)===null||Vr===void 0?void 0:Vr.call(bt,"application/x-mpegurl"))||((Hr=bt.canPlayType)===null||Hr===void 0?void 0:Hr.call(bt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Be={mp4:Boolean((Gr=bt.canPlayType)===null||Gr===void 0?void 0:Gr.call(bt,"video/mp4")),webm:Boolean((Yr=bt.canPlayType)===null||Yr===void 0?void 0:Yr.call(bt,"video/webm")),cmaf:!0},yt={h264:Boolean((qr=(ps=window.MediaSource)===null||ps===void 0?void 0:ps.isTypeSupported)===null||qr===void 0?void 0:qr.call(ps,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((jr=(vs=window.MediaSource)===null||vs===void 0?void 0:vs.isTypeSupported)===null||jr===void 0?void 0:jr.call(vs,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((zr=(ms=window.MediaSource)===null||ms===void 0?void 0:ms.isTypeSupported)===null||zr===void 0?void 0:zr.call(ms,'video/webm; codecs="vp9"')),aac:Boolean((Wr=(Ss=window.MediaSource)===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||Wr===void 0?void 0:Wr.call(Ss,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Qr=(gs=window.MediaSource)===null||gs===void 0?void 0:gs.isTypeSupported)===null||Qr===void 0?void 0:Qr.call(gs,'audio/webm; codecs="opus"'))},Qt=(yt.h264||yt.h265)&&yt.aac,Qs=nt.hls&&Be.mp4,Gy=Boolean(window.WebSocket),Yy=()=>Object.keys(yt).filter(i=>yt[i]),qy=(i,e=!1)=>i.filter(t=>{switch(t){case y.DASH:return nt.mse&&Be.mp4&&Qt;case y.DASH_SEP:return nt.mse&&Be.mp4&&Qt;case y.DASH_WEBM:return nt.mse&&Be.webm&&yt.vp9&&yt.opus;case y.DASH_LIVE:return nt.mse&&Be.mp4&&Qt;case y.DASH_LIVE_CMAF:return nt.mse&&Be.mp4&&Qt&&Be.cmaf;case y.DASH_ONDEMAND:return nt.mse&&Be.mp4&&Qt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return Qs||e&&nt.mse&&Be.mp4&&Qt;case y.MPEG:return Be.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return nt.webrtc&&Gy&&yt.h264&&(Be.mp4||Be.webm);default:return O(t)}}),jy=()=>ku?[y.MPEG,y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:Qs?[y.DASH_WEBM,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],zy=()=>ku?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF]:Qs?[y.WEB_RTC_LIVE,y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE,y.DASH_LIVE_CMAF]:[y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF,y.HLS_LIVE,y.HLS_LIVE_CMAF],Vo=i=>i?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Wy=i=>new Oi(e=>{const t=new se,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$,n=new x;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 Ho={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Qy={cacheDuration:12e4},Jy={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Ky={maxPausedTime:3e4},Go={maxPausedTime:3e4};class Xy{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,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([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,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),is3DVideo$:new b(!1)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=qy([...zy(),...jy()],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 Fo(r);const a=[...Vo(!0),...Vo(!1)];this.chromecastFormatsIterator=new Fo(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:C.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!==H.None;this.params.desiredState.seekState.setState({state:H.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 De.SCREEN:return this.createScreenProvider(t);case De.CHROMECAST:return this.createChromecastProvider(t);default:return O(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 y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new Xg(Object.assign(Object.assign({},n),{source:o,config:Qy}))}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new Ao(Object.assign(Object.assign({},n),{source:o,format:e,config:Go})):new Dy(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Ao(Object.assign(Object.assign({},n),{source:o,format:e,config:Go}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Qs||!this.params.tuning.useHlsJs?new By(Object.assign(Object.assign({},n),{source:o})):new xy(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Oy(Object.assign(Object.assign({},n),{source:o,config:Ky}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new Ny(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new zg(Object.assign(Object.assign({},n),{source:o,config:Jy}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Vy({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(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 tg({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()?De.CHROMECAST:De.SCREEN}chooseFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case De.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return O(e)}}skipFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.next();case De.CHROMECAST:return this.chromecastFormatsIterator.next();default:return O(e)}}handleNoFormatsError(e){switch(e){case De.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case De.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return O(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 Hi(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,s=0;return e.add(L(this.providerOutput.error$,Wy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ho.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:C.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===De.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===C.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Ho.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 Fe;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Fe||(Fe={}));const Iu=new Map;let xt=Fe.RUNTIME;const Jr=`vk-videoplayer-dummy-key-${Math.random()}`,Zy=()=>{try{localStorage.setItem(Jr,"test"),localStorage.removeItem(Jr),xt=Fe.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Jr),xt=Fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)xt=Fe.RUNTIME;else throw e}else throw i}};Zy();const eT=i=>{var e,t;switch(xt){case Fe.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Fe.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Fe.RUNTIME:return Iu.get(i);default:O(xt)}},Yo=(i,e)=>{switch(xt){case Fe.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.RUNTIME:return void Iu.set(i,e);default:O(xt)}},ba=(i,e,t)=>t*e+(1-t)*i,Du=(i,e)=>i.reduce((t,s)=>t+s,0)/e,tT=(i,e,t,s)=>{let r=0,a=t;const n=Du(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 Cu{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 Ze(`raw_${s}`),this.smoothedSeries$=new Ze(`smoothed_${s}`),this.reportedSeries$=new Ze(`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 iT extends Cu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ba(this.slow,e,this.params.emaAlphaSlow),this.fast=ba(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class sT extends Cu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Du(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ba(this.emaSmoothed,e,this.params.emaAlpha);const s=tT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class qo{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new iT({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new sT({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const rT=5e3,jo="one_video_throughput",zo="one_video_rtt",ct=window.navigator.connection,Wo=()=>{const i=ct==null?void 0:ct.downlink;if(_(i)&&i!==10)return i*1e3},Qo=()=>{const i=ct==null?void 0:ct.rtt;if(_(i)&&i!==3e3)return i},Jo=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Di{constructor(e){var t,s;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Di.load(jo)||(e.useBrowserEstimation?Wo():void 0)||rT,a=(s=(t=Di.load(zo))!==null&&t!==void 0?t:e.useBrowserEstimation?Qo():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(Jo(r,a,e.rttPenaltyRequestSize)),this.throughput=qo.getSmoothedValue(r,-1,e),this.rtt=qo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Wo();u&&this.throughput.next(u);const d=Qo();_(d)&&this.rtt.next(d)};ct&&"onchange"in ct&&this.subscription.add(U(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Yo(jo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Yo(zo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(ut({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Jo(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(U(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(U(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:l})=>le(this,void 0,void 0,function*(){d?(this.addRawSpeed(s,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.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(Di.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=eT(e);if(_(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Ko={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},aT=i=>{const e={};for(const t of Object.keys(Ko)){const s=Ko[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 nT=({seekState:i,position$:e})=>L(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===H.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),j(_)),e.pipe(j(()=>i.getState().state===H.None))),oT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const Xo=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new Oi(a=>{let n;const o=i.transitionEnded$.pipe(j(p=>(p.from===v.PAUSED||p.from===v.STOPPED)&&p.to===v.PLAYING)),u=i.stateChangeEnded$.pipe(j(p=>p.from===v.PLAYING&&p.to===v.PAUSED)),d=e.stateChangeEnded$.pipe(j(({to:p})=>{var m,f;return p.state===H.Requested&&((f=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&f!==void 0?f:i.getState())===v.PLAYING})),l=e.stateChangeEnded$.pipe(j(({from:p,to:m})=>{var f,S;return p.state===H.Applying&&m.state===H.None&&((S=(f=i.getTransition())===null||f===void 0?void 0:f.from)!==null&&S!==void 0?S:i.getState())===v.PLAYING})),c=L(o,l).pipe($(()=>r.getValue()),j(_)),h=L(L(u,d,t),s).pipe($(()=>r.getValue()),j(_));return new se().add(c.subscribe(p=>{n=p})).add(h.subscribe(p=>{if(K(n)||n===p)return;const m={from:n,to:p};n=void 0,a.next(m)}))});class fT{constructor(e={}){if(this.subscription=new se,this.logger=new Zu,this.isPlaybackStarted=!1,this.desiredState={playbackState:new ue(v.STOPPED),seekState:new ue({state:H.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!1),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraRotation:new ue(!1)},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([]),isAudioAvailable$: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(_e.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new x,started$:new x,willPause$:new x,willResume$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new b(void 0),enableDebugTelemetry$:new b(!1),dumpTelemetry:wg},this.initLogs(),this.tuning=aT(e),this.chromecastInitializer=new rl({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Di(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(c=>JSON.stringify(c,(h,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),d=`Player.${String(s)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=oT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Xy({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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===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:H.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===_e.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===_e.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const 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()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),this}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===H.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(L(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===H.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},u),{state:H.Applying})):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===H.Applying&&(this.desiredState.seekState.setState({state:H.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,l)=>ks(d)?1:ks(l)?-1:Es(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(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(nT({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(L(e.providerOutput.endedEvent$.pipe(Lt(!0)),e.providerOutput.seekedEvent$.pipe(Lt(!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:C.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=L(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=L(U(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(l=>d.next(l&&Math.floor(l/1e3)))),n.add(Xo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Xo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(L(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(u=>{this.info.is3DVideo$.next(u)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new 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=qi(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(L(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),_g(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Ag(s)),this.providerContainer.current$.subscribe(({type:s})=>ls("provider",s)),t.duration$.subscribe(s=>ls("duration",s)),t.availableVideoTracks$.pipe(j(s=>!!s.length),ye()).subscribe(s=>ls("tracks",s)),this.events.fatalError$.subscribe(new Ze("fatalError")),this.events.managedError$.subscribe(new Ze("managedError")),t.position$.subscribe(new Ze("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new Ze("quality")),this.info.currentBuffer$.subscribe(new Ze("buffer")),t.isBuffering$.subscribe(new Ze("isBuffering"))].forEach(s=>this.subscription.add(s)),ls("codecs",Yy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>le(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)}))});this.subscription.add(L(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===v.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const pT=`${il}@${tl}`;export{_e as ChromecastState,Ci as HttpConnectionType,ST as Observable,v as PlaybackState,fT as Player,pT as SDK_VERSION,gT as Subject,bT as Subscription,yT as ValueSubject,y as VideoFormat,ne as VideoQuality};