@vkontakte/videoplayer-core 2.0.87 → 2.0.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +6 -6
- package/index.d.ts +8 -25
- package/package.json +2 -2
package/es2015.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Mon,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.88
|
|
3
|
+
* Mon, 03 Jul 2023 18:19:16 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-88/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as T,Subject as L,Subscription as ne,isNonNullable as P,ErrorCategory as D,isNullable as te,fromEvent as M,assertNever as F,merge as H,tap as on,map as _,observableFrom as xe,filterChanged as Se,assertNonNullable as R,debounce as Ue,timeout as tl,combine as rt,once as Te,mapTo as si,filter as ie,now as pe,Observable as Cs,abortable as ze,getExponentialDelay as un,interval as il,safeStorage as Zs,Logger as sl,ACTIVE_LIVE_VALID_DELAY as rl}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as iT,Subject as sT,Subscription as rT,ValueSubject as aT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import al from"lodash/debounce.js";const nl="2.0.87";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));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_AV1="DASH_WEBM_AV1",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 _e;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Ae;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(Ae||(Ae={}));var Ii;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(Ii||(Ii={}));var z;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(z||(z={}));var $t;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})($t||($t={}));function de(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{u(s.next(l))}catch(c){n(c)}}function d(l){try{u(s.throw(l))}catch(c){n(c)}}function u(l){l.done?a(l.value):r(l.value).then(o,d)}u((s=s.apply(i,e||[])).next())})}function V(i){return this instanceof V?(this.v=i,this):new V(i)}function We(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,S){a.push([h,f,m,S])>1||o(h,f)})})}function o(h,f){try{d(s[h](f))}catch(m){c(a[0][3],m)}}function d(h){h.value instanceof V?Promise.resolve(h.value.v).then(u,l):c(a[0][2],h)}function u(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 ol=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 ul{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ae.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new T(Ae.NOT_AVAILABLE),this.subscription=new ne,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=P((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||ol("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var 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(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(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(M(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 F(r.sessionState)}})).add(H(M(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(on(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),xe([s.getCastState()])).pipe(Se(),_(dl),on(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ae.CONNECTED,o=P(this.connection$.getValue());if(n&&!o){const d=s.getCurrentSession();R(d);const u=d.getCastDevice(),l=(a=d.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ae.CONNECTED?P(this.connection$.getValue())?Ae.CONNECTED:Ae.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:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const dl=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ae.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ae.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ae.CONNECTING;case cast.framework.CastState.CONNECTED:return Ae.CONNECTED;default:return F(i)}};var dn=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Fe=function(i){try{return!!i()}catch(e){return!0}},ll=Fe,Os=!ll(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),iu=Os,su=Function.prototype,Xr=su.call,cl=iu&&su.bind.bind(Xr,Xr),Ve=iu?cl:function(i){return function(){return Xr.apply(i,arguments)}},ru=Ve,hl=ru({}.toString),fl=ru("".slice),Oi=function(i){return fl(hl(i),8,-1)},pl=Ve,vl=Fe,ml=Oi,er=Object,Sl=pl("".split),gl=vl(function(){return!er("z").propertyIsEnumerable(0)})?function(i){return ml(i)=="String"?Sl(i,""):er(i)}:er,Li=function(i){return i==null},bl=Li,yl=TypeError,Ea=function(i){if(bl(i))throw yl("Can't call method on "+i);return i},Tl=gl,El=Ea,xi=function(i){return Tl(El(i))},$l=function(){},ui={},Wi=function(i){return i&&i.Math==Math&&i},ke=Wi(typeof globalThis=="object"&&globalThis)||Wi(typeof window=="object"&&window)||Wi(typeof self=="object"&&self)||Wi(typeof dn=="object"&&dn)||function(){return this}()||Function("return this")(),Zr=typeof document=="object"&&document.all,Al=typeof Zr=="undefined"&&Zr!==void 0,au={all:Zr,IS_HTMLDDA:Al},nu=au,wl=nu.all,Ee=nu.IS_HTMLDDA?function(i){return typeof i=="function"||i===wl}:function(i){return typeof i=="function"},_l=ke,Pl=Ee,ln=_l.WeakMap,kl=Pl(ln)&&/native code/.test(String(ln)),cn=Ee,ou=au,Rl=ou.all,pt=ou.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:cn(i)||i===Rl}:function(i){return typeof i=="object"?i!==null:cn(i)},Il=Fe,vt=!Il(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Bt={},Dl=ke,hn=pt,ea=Dl.document,Cl=hn(ea)&&hn(ea.createElement),$a=function(i){return Cl?ea.createElement(i):{}},Ol=vt,Ll=Fe,xl=$a,uu=!Ol&&!Ll(function(){return Object.defineProperty(xl("div"),"a",{get:function(){return 7}}).a!=7}),Nl=vt,Bl=Fe,du=Nl&&Bl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Ml=pt,Ul=String,Fl=TypeError,mt=function(i){if(Ml(i))return i;throw Fl(Ul(i)+" is not an object")},Vl=Os,Qi=Function.prototype.call,Ne=Vl?Qi.bind(Qi):function(){return Qi.apply(Qi,arguments)},Aa={},tr=Aa,ir=ke,Hl=Ee,fn=function(i){return Hl(i)?i:void 0},Mt=function(i,e){return arguments.length<2?fn(tr[i])||fn(ir[i]):tr[i]&&tr[i][e]||ir[i]&&ir[i][e]},Gl=Ve,Ls=Gl({}.isPrototypeOf),xs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",lu=ke,sr=xs,pn=lu.process,vn=lu.Deno,mn=pn&&pn.versions||vn&&vn.version,Sn=mn&&mn.v8,je,Ts;Sn&&(je=Sn.split("."),Ts=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!Ts&&sr&&(je=sr.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=sr.match(/Chrome\/(\d+)/),je&&(Ts=+je[1])));var cu=Ts,gn=cu,ql=Fe,hu=!!Object.getOwnPropertySymbols&&!ql(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&gn&&gn<41}),Yl=hu,fu=Yl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",jl=Mt,zl=Ee,Wl=Ls,Ql=fu,Jl=Object,pu=Ql?function(i){return typeof i=="symbol"}:function(i){var e=jl("Symbol");return zl(e)&&Wl(e.prototype,Jl(i))},Kl=String,Ns=function(i){try{return Kl(i)}catch(e){return"Object"}},Xl=Ee,Zl=Ns,ec=TypeError,Ut=function(i){if(Xl(i))return i;throw ec(Zl(i)+" is not a function")},tc=Ut,ic=Li,Bs=function(i,e){var t=i[e];return ic(t)?void 0:tc(t)},rr=Ne,ar=Ee,nr=pt,sc=TypeError,rc=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 sc("Can't convert object to primitive value")},Es={},ac={get exports(){return Es},set exports(i){Es=i}},vu=!0,bn=ke,nc=Object.defineProperty,oc=function(i,e){try{nc(bn,i,{value:e,configurable:!0,writable:!0})}catch(t){bn[i]=e}return e},uc=ke,dc=oc,yn="__core-js_shared__",lc=uc[yn]||dc(yn,{}),wa=lc,Tn=wa;(ac.exports=function(i,e){return Tn[i]||(Tn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var cc=Ea,hc=Object,Ms=function(i){return hc(cc(i))},fc=Ve,pc=Ms,vc=fc({}.hasOwnProperty),at=Object.hasOwn||function(e,t){return vc(pc(e),t)},mc=Ve,Sc=0,gc=Math.random(),bc=mc(1 .toString),mu=function(i){return"Symbol("+(i===void 0?"":i)+")_"+bc(++Sc+gc,36)},yc=ke,Tc=Es,En=at,Ec=mu,$c=hu,Ac=fu,Kt=yc.Symbol,or=Tc("wks"),wc=Ac?Kt.for||Kt:Kt&&Kt.withoutSetter||Ec,Re=function(i){return En(or,i)||(or[i]=$c&&En(Kt,i)?Kt[i]:wc("Symbol."+i)),or[i]},_c=Ne,$n=pt,An=pu,Pc=Bs,kc=rc,Rc=Re,Ic=TypeError,Dc=Rc("toPrimitive"),Cc=function(i,e){if(!$n(i)||An(i))return i;var t=Pc(i,Dc),s;if(t){if(e===void 0&&(e="default"),s=_c(t,i,e),!$n(s)||An(s))return s;throw Ic("Can't convert object to primitive value")}return e===void 0&&(e="number"),kc(i,e)},Oc=Cc,Lc=pu,_a=function(i){var e=Oc(i,"string");return Lc(e)?e:e+""},xc=vt,Nc=uu,Bc=du,Ji=mt,wn=_a,Mc=TypeError,ur=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,dr="enumerable",lr="configurable",cr="writable";Bt.f=xc?Bc?function(e,t,s){if(Ji(e),t=wn(t),Ji(s),typeof e=="function"&&t==="prototype"&&"value"in s&&cr in s&&!s[cr]){var r=Uc(e,t);r&&r[cr]&&(e[t]=s.value,s={configurable:lr in s?s[lr]:r[lr],enumerable:dr in s?s[dr]:r[dr],writable:!1})}return ur(e,t,s)}:ur:function(e,t,s){if(Ji(e),t=wn(t),Ji(s),Nc)try{return ur(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Mc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Us=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Fc=vt,Vc=Bt,Hc=Us,Ni=Fc?function(i,e,t){return Vc.f(i,e,Hc(1,t))}:function(i,e,t){return i[e]=t,i},Gc=Es,qc=mu,_n=Gc("keys"),Pa=function(i){return _n[i]||(_n[i]=qc(i))},ka={},Yc=kl,Su=ke,jc=pt,zc=Ni,hr=at,fr=wa,Wc=Pa,Qc=ka,Pn="Object already initialized",ta=Su.TypeError,Jc=Su.WeakMap,$s,Di,As,Kc=function(i){return As(i)?Di(i):$s(i,{})},Xc=function(i){return function(e){var t;if(!jc(e)||(t=Di(e)).type!==i)throw ta("Incompatible receiver, "+i+" required");return t}};if(Yc||fr.state){var et=fr.state||(fr.state=new Jc);et.get=et.get,et.has=et.has,et.set=et.set,$s=function(i,e){if(et.has(i))throw ta(Pn);return e.facade=i,et.set(i,e),e},Di=function(i){return et.get(i)||{}},As=function(i){return et.has(i)}}else{var Yt=Wc("state");Qc[Yt]=!0,$s=function(i,e){if(hr(i,Yt))throw ta(Pn);return e.facade=i,zc(i,Yt,e),e},Di=function(i){return hr(i,Yt)?i[Yt]:{}},As=function(i){return hr(i,Yt)}}var gu={set:$s,get:Di,has:As,enforce:Kc,getterFor:Xc},Zc=Os,bu=Function.prototype,kn=bu.apply,Rn=bu.call,yu=typeof Reflect=="object"&&Reflect.apply||(Zc?Rn.bind(kn):function(){return Rn.apply(kn,arguments)}),eh=Oi,th=Ve,Tu=function(i){if(eh(i)==="Function")return th(i)},Ra={},Eu={},$u={}.propertyIsEnumerable,Au=Object.getOwnPropertyDescriptor,ih=Au&&!$u.call({1:2},1);Eu.f=ih?function(e){var t=Au(this,e);return!!t&&t.enumerable}:$u;var sh=vt,rh=Ne,ah=Eu,nh=Us,oh=xi,uh=_a,dh=at,lh=uu,In=Object.getOwnPropertyDescriptor;Ra.f=sh?In:function(e,t){if(e=oh(e),t=uh(t),lh)try{return In(e,t)}catch(s){}if(dh(e,t))return nh(!rh(ah.f,e,t),e[t])};var ch=Fe,hh=Ee,fh=/#|\.prototype\./,Bi=function(i,e){var t=vh[ph(i)];return t==Sh?!0:t==mh?!1:hh(e)?ch(e):!!e},ph=Bi.normalize=function(i){return String(i).replace(fh,".").toLowerCase()},vh=Bi.data={},mh=Bi.NATIVE="N",Sh=Bi.POLYFILL="P",wu=Bi,Dn=Tu,gh=Ut,bh=Os,yh=Dn(Dn.bind),Fs=function(i,e){return gh(i),e===void 0?i:bh?yh(i,e):function(){return i.apply(e,arguments)}},Ki=ke,Th=yu,Eh=Tu,$h=Ee,Ah=Ra.f,wh=wu,jt=Aa,_h=Fs,zt=Ni,Cn=at,Ph=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 Th(i,this,arguments)};return e.prototype=i.prototype,e},Ke=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Ki:r?Ki[t]:(Ki[t]||{}).prototype,o=s?jt:jt[t]||zt(jt,t,{})[t],d=o.prototype,u,l,c,h,f,m,S,b,v;for(h in e)u=wh(s?h:t+(r?".":"#")+h,i.forced),l=!u&&n&&Cn(n,h),m=o[h],l&&(i.dontCallGetSet?(v=Ah(n,h),S=v&&v.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?b=_h(f,Ki):i.wrap&&l?b=Ph(f):a&&$h(f)?b=Eh(f):b=f,(i.sham||f&&f.sham||m&&m.sham)&&zt(b,"sham",!0),zt(o,h,b),a&&(c=t+"Prototype",Cn(jt,c)||zt(jt,c,{}),zt(jt[c],h,f),i.real&&d&&(u||!d[h])&&zt(d,h,f)))},ia=vt,kh=at,_u=Function.prototype,Rh=ia&&Object.getOwnPropertyDescriptor,Ia=kh(_u,"name"),Ih=Ia&&function(){}.name==="something",Dh=Ia&&(!ia||ia&&Rh(_u,"name").configurable),Ch={EXISTS:Ia,PROPER:Ih,CONFIGURABLE:Dh},Pu={},Oh=Math.ceil,Lh=Math.floor,xh=Math.trunc||function(e){var t=+e;return(t>0?Lh:Oh)(t)},Nh=xh,Da=function(i){var e=+i;return e!==e||e===0?0:Nh(e)},Bh=Da,Mh=Math.max,Uh=Math.min,Fh=function(i,e){var t=Bh(i);return t<0?Mh(t+e,0):Uh(t,e)},Vh=Da,Hh=Math.min,Gh=function(i){return i>0?Hh(Vh(i),9007199254740991):0},qh=Gh,Ca=function(i){return qh(i.length)},Yh=xi,jh=Fh,zh=Ca,On=function(i){return function(e,t,s){var r=Yh(e),a=zh(r),n=jh(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}},Wh={includes:On(!0),indexOf:On(!1)},Qh=Ve,pr=at,Jh=xi,Kh=Wh.indexOf,Xh=ka,Ln=Qh([].push),Zh=function(i,e){var t=Jh(i),s=0,r=[],a;for(a in t)!pr(Xh,a)&&pr(t,a)&&Ln(r,a);for(;e.length>s;)pr(t,a=e[s++])&&(~Kh(r,a)||Ln(r,a));return r},ku=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ef=Zh,tf=ku,sf=Object.keys||function(e){return ef(e,tf)},rf=vt,af=du,nf=Bt,of=mt,uf=xi,df=sf;Pu.f=rf&&!af?Object.defineProperties:function(e,t){of(e);for(var s=uf(t),r=df(t),a=r.length,n=0,o;a>n;)nf.f(e,o=r[n++],s[o]);return e};var lf=Mt,Ru=lf("document","documentElement"),cf=mt,hf=Pu,xn=ku,ff=ka,pf=Ru,vf=$a,mf=Pa,Nn=">",Bn="<",sa="prototype",ra="script",Iu=mf("IE_PROTO"),vr=function(){},Du=function(i){return Bn+ra+Nn+i+Bn+"/"+ra+Nn},Mn=function(i){i.write(Du("")),i.close();var e=i.parentWindow.Object;return i=null,e},Sf=function(){var i=vf("iframe"),e="java"+ra+":",t;return i.style.display="none",pf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Du("document.F=Object")),t.close(),t.F},Xi,ms=function(){try{Xi=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&Xi?Mn(Xi):Sf():Mn(Xi);for(var i=xn.length;i--;)delete ms[sa][xn[i]];return ms()};ff[Iu]=!0;var Cu=Object.create||function(e,t){var s;return e!==null?(vr[sa]=cf(e),s=new vr,vr[sa]=null,s[Iu]=e):s=ms(),t===void 0?s:hf.f(s,t)},gf=Fe,bf=!gf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),yf=at,Tf=Ee,Ef=Ms,$f=Pa,Af=bf,Un=$f("IE_PROTO"),aa=Object,wf=aa.prototype,Ou=Af?aa.getPrototypeOf:function(i){var e=Ef(i);if(yf(e,Un))return e[Un];var t=e.constructor;return Tf(t)&&e instanceof t?t.prototype:e instanceof aa?wf:null},_f=Ni,Oa=function(i,e,t,s){return s&&s.enumerable?i[e]=t:_f(i,e,t),i},Pf=Fe,kf=Ee,Rf=pt,If=Cu,Fn=Ou,Df=Oa,Cf=Re,na=Cf("iterator"),Lu=!1,ht,mr,Sr;[].keys&&(Sr=[].keys(),"next"in Sr?(mr=Fn(Fn(Sr)),mr!==Object.prototype&&(ht=mr)):Lu=!0);var Of=!Rf(ht)||Pf(function(){var i={};return ht[na].call(i)!==i});Of?ht={}:ht=If(ht);kf(ht[na])||Df(ht,na,function(){return this});var xu={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Lu},Lf=Re,xf=Lf("toStringTag"),Nu={};Nu[xf]="z";var La=String(Nu)==="[object z]",Nf=La,Bf=Ee,Ss=Oi,Mf=Re,Uf=Mf("toStringTag"),Ff=Object,Vf=Ss(function(){return arguments}())=="Arguments",Hf=function(i,e){try{return i[e]}catch(t){}},Mi=Nf?Ss:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Hf(e=Ff(i),Uf))=="string"?t:Vf?Ss(e):(s=Ss(e))=="Object"&&Bf(e.callee)?"Arguments":s},Gf=La,qf=Mi,Yf=Gf?{}.toString:function(){return"[object "+qf(this)+"]"},jf=La,zf=Bt.f,Wf=Ni,Qf=at,Jf=Yf,Kf=Re,Vn=Kf("toStringTag"),xa=function(i,e,t,s){if(i){var r=t?i:i.prototype;Qf(r,Vn)||zf(r,Vn,{configurable:!0,value:e}),s&&!jf&&Wf(r,"toString",Jf)}},Xf=xu.IteratorPrototype,Zf=Cu,ep=Us,tp=xa,ip=ui,sp=function(){return this},rp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Zf(Xf,{next:ep(+!s,t)}),tp(i,r,!1,!0),ip[r]=sp,i},ap=Ke,np=Ne,Bu=Ch,op=rp,up=Ou,dp=xa,Hn=Oa,lp=Re,Gn=ui,Mu=xu,cp=Bu.PROPER;Bu.CONFIGURABLE;Mu.IteratorPrototype;var Zi=Mu.BUGGY_SAFARI_ITERATORS,gr=lp("iterator"),qn="keys",es="values",Yn="entries",hp=function(){return this},fp=function(i,e,t,s,r,a,n){op(t,e,s);var o=function(v){if(v===r&&h)return h;if(!Zi&&v in l)return l[v];switch(v){case qn:return function(){return new t(this,v)};case es:return function(){return new t(this,v)};case Yn:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,l=i.prototype,c=l[gr]||l["@@iterator"]||r&&l[r],h=!Zi&&c||o(r),f=e=="Array"&&l.entries||c,m,S,b;if(f&&(m=up(f.call(new i)),m!==Object.prototype&&m.next&&(dp(m,d,!0,!0),Gn[d]=hp)),cp&&r==es&&c&&c.name!==es&&(u=!0,h=function(){return np(c,this)}),r)if(S={values:o(es),keys:a?h:o(qn),entries:o(Yn)},n)for(b in S)(Zi||u||!(b in l))&&Hn(l,b,S[b]);else ap({target:e,proto:!0,forced:Zi||u},S);return n&&l[gr]!==h&&Hn(l,gr,h,{name:r}),Gn[e]=h,S},pp=function(i,e){return{value:i,done:e}},vp=xi,Na=$l,jn=ui,Uu=gu,mp=Bt.f,Sp=fp,ts=pp,gp=vu,bp=vt,Fu="Array Iterator",yp=Uu.set,Tp=Uu.getterFor(Fu);Sp(Array,"Array",function(i,e){yp(this,{type:Fu,target:vp(i),index:0,kind:e})},function(){var i=Tp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ts(void 0,!0)):t=="keys"?ts(s,!1):t=="values"?ts(e[s],!1):ts([s,e[s]],!1)},"values");var zn=jn.Arguments=jn.Array;Na();Na();Na();if(!gp&&bp&&zn.name!=="values")try{mp(zn,"name",{value:"values"})}catch(i){}var Ep=Re,$p=ui,Ap=Ep("iterator"),wp=Array.prototype,_p=function(i){return i!==void 0&&($p.Array===i||wp[Ap]===i)},Pp=Mi,Wn=Bs,kp=Li,Rp=ui,Ip=Re,Dp=Ip("iterator"),Vu=function(i){if(!kp(i))return Wn(i,Dp)||Wn(i,"@@iterator")||Rp[Pp(i)]},Cp=Ne,Op=Ut,Lp=mt,xp=Ns,Np=Vu,Bp=TypeError,Mp=function(i,e){var t=arguments.length<2?Np(i):e;if(Op(t))return Lp(Cp(t,i));throw Bp(xp(i)+" is not iterable")},Up=Ne,Qn=mt,Fp=Bs,Vp=function(i,e,t){var s,r;Qn(i);try{if(s=Fp(i,"return"),!s){if(e==="throw")throw t;return t}s=Up(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Qn(s),t},Hp=Fs,Gp=Ne,qp=mt,Yp=Ns,jp=_p,zp=Ca,Jn=Ls,Wp=Mp,Qp=Vu,Kn=Vp,Jp=TypeError,gs=function(i,e){this.stopped=i,this.result=e},Xn=gs.prototype,Ba=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),d=Hp(e,s),u,l,c,h,f,m,S,b=function(g){return u&&Kn(u,"normal",g),new gs(!0,g)},v=function(g){return r?(qp(g),o?d(g[0],g[1],b):d(g[0],g[1])):o?d(g,b):d(g)};if(a)u=i.iterator;else if(n)u=i;else{if(l=Qp(i),!l)throw Jp(Yp(i)+" is not iterable");if(jp(l)){for(c=0,h=zp(i);h>c;c++)if(f=v(i[c]),f&&Jn(Xn,f))return f;return new gs(!1)}u=Wp(i,l)}for(m=a?i.next:u.next;!(S=Gp(m,u)).done;){try{f=v(S.value)}catch(g){Kn(u,"throw",g)}if(typeof f=="object"&&f&&Jn(Xn,f))return f}return new gs(!1)},Kp=_a,Xp=Bt,Zp=Us,ev=function(i,e,t){var s=Kp(e);s in i?Xp.f(i,s,Zp(0,t)):i[s]=t},tv=Ke,iv=Ba,sv=ev;tv({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iv(e,function(s,r){sv(t,s,r)},{AS_ENTRIES:!0}),t}});var rv=Aa,av=rv.Object.fromEntries,nv={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},ov=nv,uv=ke,dv=Mi,lv=Ni,Zn=ui,cv=Re,eo=cv("toStringTag");for(var br in ov){var to=uv[br],yr=to&&to.prototype;yr&&dv(yr)!==eo&&lv(yr,eo,br),Zn[br]=Zn.Array}var hv=av,fv=hv,pv=fv,vv=pv,Ui=vv,mv=Oi,Vs=typeof process!="undefined"&&mv(process)=="process",Sv=Mt,gv=Bt,bv=Re,yv=vt,io=bv("species"),Tv=function(i){var e=Sv(i),t=gv.f;yv&&e&&!e[io]&&t(e,io,{configurable:!0,get:function(){return this}})},Ev=Ls,$v=TypeError,Av=function(i,e){if(Ev(e,i))return i;throw $v("Incorrect invocation")},wv=Ve,_v=Ee,oa=wa,Pv=wv(Function.toString);_v(oa.inspectSource)||(oa.inspectSource=function(i){return Pv(i)});var Hu=oa.inspectSource,kv=Ve,Rv=Fe,Gu=Ee,Iv=Mi,Dv=Mt,Cv=Hu,qu=function(){},Ov=[],Yu=Dv("Reflect","construct"),Ma=/^\s*(?:class|function)\b/,Lv=kv(Ma.exec),xv=!Ma.exec(qu),yi=function(e){if(!Gu(e))return!1;try{return Yu(qu,Ov,e),!0}catch(t){return!1}},ju=function(e){if(!Gu(e))return!1;switch(Iv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return xv||!!Lv(Ma,Cv(e))}catch(t){return!0}};ju.sham=!0;var Nv=!Yu||Rv(function(){var i;return yi(yi.call)||!yi(Object)||!yi(function(){i=!0})||i})?ju:yi,Bv=Nv,Mv=Ns,Uv=TypeError,Fv=function(i){if(Bv(i))return i;throw Uv(Mv(i)+" is not a constructor")},so=mt,Vv=Fv,Hv=Li,Gv=Re,qv=Gv("species"),zu=function(i,e){var t=so(i).constructor,s;return t===void 0||Hv(s=so(t)[qv])?e:Vv(s)},Yv=Ve,jv=Yv([].slice),zv=TypeError,Wv=function(i,e){if(i<e)throw zv("Not enough arguments");return i},Qv=xs,Wu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Qv),Le=ke,Jv=yu,Kv=Fs,ro=Ee,Xv=at,Qu=Fe,ao=Ru,Zv=jv,no=$a,em=Wv,tm=Wu,im=Vs,ua=Le.setImmediate,da=Le.clearImmediate,sm=Le.process,Tr=Le.Dispatch,rm=Le.Function,oo=Le.MessageChannel,am=Le.String,Er=0,wi={},uo="onreadystatechange",Ci,Ct,$r,Ar;Qu(function(){Ci=Le.location});var Ua=function(i){if(Xv(wi,i)){var e=wi[i];delete wi[i],e()}},wr=function(i){return function(){Ua(i)}},lo=function(i){Ua(i.data)},co=function(i){Le.postMessage(am(i),Ci.protocol+"//"+Ci.host)};(!ua||!da)&&(ua=function(e){em(arguments.length,1);var t=ro(e)?e:rm(e),s=Zv(arguments,1);return wi[++Er]=function(){Jv(t,void 0,s)},Ct(Er),Er},da=function(e){delete wi[e]},im?Ct=function(i){sm.nextTick(wr(i))}:Tr&&Tr.now?Ct=function(i){Tr.now(wr(i))}:oo&&!tm?($r=new oo,Ar=$r.port2,$r.port1.onmessage=lo,Ct=Kv(Ar.postMessage,Ar)):Le.addEventListener&&ro(Le.postMessage)&&!Le.importScripts&&Ci&&Ci.protocol!=="file:"&&!Qu(co)?(Ct=co,Le.addEventListener("message",lo,!1)):uo in no("script")?Ct=function(i){ao.appendChild(no("script"))[uo]=function(){ao.removeChild(this),Ua(i)}}:Ct=function(i){setTimeout(wr(i),0)});var Ju={set:ua,clear:da},Ku=function(){this.head=null,this.tail=null};Ku.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 Xu=Ku,nm=xs,om=/ipad|iphone|ipod/i.test(nm)&&typeof Pebble!="undefined",um=xs,dm=/web0s(?!.*chrome)/i.test(um),Nt=ke,ho=Fs,lm=Ra.f,_r=Ju.set,cm=Xu,hm=Wu,fm=om,pm=dm,Pr=Vs,fo=Nt.MutationObserver||Nt.WebKitMutationObserver,po=Nt.document,vo=Nt.process,is=Nt.Promise,mo=lm(Nt,"queueMicrotask"),la=mo&&mo.value,Wt,kr,Rr,ss,So;if(!la){var rs=new cm,as=function(){var i,e;for(Pr&&(i=vo.domain)&&i.exit();e=rs.get();)try{e()}catch(t){throw rs.head&&Wt(),t}i&&i.enter()};!hm&&!Pr&&!pm&&fo&&po?(kr=!0,Rr=po.createTextNode(""),new fo(as).observe(Rr,{characterData:!0}),Wt=function(){Rr.data=kr=!kr}):!fm&&is&&is.resolve?(ss=is.resolve(void 0),ss.constructor=is,So=ho(ss.then,ss),Wt=function(){So(as)}):Pr?Wt=function(){vo.nextTick(as)}:(_r=ho(_r,Nt),Wt=function(){_r(as)}),la=function(i){rs.head||Wt(),rs.add(i)}}var vm=la,mm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Fa=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Sm=ke,di=Sm.Promise,Zu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",gm=Zu,bm=Vs,ym=!gm&&!bm&&typeof window=="object"&&typeof document=="object",Tm=ke,_i=di,Em=Ee,$m=wu,Am=Hu,wm=Re,_m=ym,Pm=Zu,Ir=cu,go=_i&&_i.prototype,km=wm("species"),ca=!1,ed=Em(Tm.PromiseRejectionEvent),Rm=$m("Promise",function(){var i=Am(_i),e=i!==String(_i);if(!e&&Ir===66||!(go.catch&&go.finally))return!0;if(!Ir||Ir<51||!/native code/.test(i)){var t=new _i(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[km]=s,ca=t.then(function(){})instanceof s,!ca)return!0}return!e&&(_m||Pm)&&!ed}),Fi={CONSTRUCTOR:Rm,REJECTION_EVENT:ed,SUBCLASSING:ca},li={},bo=Ut,Im=TypeError,Dm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw Im("Bad Promise constructor");e=s,t=r}),this.resolve=bo(e),this.reject=bo(t)};li.f=function(i){return new Dm(i)};var Cm=Ke,ws=Vs,wt=ke,Vi=Ne,Om=Oa,Lm=xa,xm=Tv,Nm=Ut,ha=Ee,Bm=pt,Mm=Av,Um=zu,td=Ju.set,Va=vm,Fm=mm,Vm=Fa,Hm=Xu,id=gu,fa=di,Ha=Fi,sd=li,Hs="Promise",rd=Ha.CONSTRUCTOR,Gm=Ha.REJECTION_EVENT;Ha.SUBCLASSING;var Dr=id.getterFor(Hs),qm=id.set,Ym=fa&&fa.prototype,Xt=fa,Cr=Ym,ad=wt.TypeError,pa=wt.document,Ga=wt.process,va=sd.f,jm=va,zm=!!(pa&&pa.createEvent&&wt.dispatchEvent),nd="unhandledrejection",Wm="rejectionhandled",yo=0,od=1,Qm=2,qa=1,ud=2,ns,To,Jm,dd=function(i){var e;return Bm(i)&&ha(e=i.then)?e:!1},ld=function(i,e){var t=e.value,s=e.state==od,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,d,u,l;try{r?(s||(e.rejection===ud&&Xm(e),e.rejection=qa),r===!0?d=t:(o&&o.enter(),d=r(t),o&&(o.exit(),l=!0)),d===i.promise?n(ad("Promise-chain cycle")):(u=dd(d))?Vi(u,d,a,n):a(d)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},cd=function(i,e){i.notified||(i.notified=!0,Va(function(){for(var t=i.reactions,s;s=t.get();)ld(s,i);i.notified=!1,e&&!i.rejection&&Km(i)}))},hd=function(i,e,t){var s,r;zm?(s=pa.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),wt.dispatchEvent(s)):s={promise:e,reason:t},!Gm&&(r=wt["on"+i])?r(s):i===nd&&Fm("Unhandled promise rejection",t)},Km=function(i){Vi(td,wt,function(){var e=i.facade,t=i.value,s=Eo(i),r;if(s&&(r=Vm(function(){ws?Ga.emit("unhandledRejection",t,e):hd(nd,e,t)}),i.rejection=ws||Eo(i)?ud:qa,r.error))throw r.value})},Eo=function(i){return i.rejection!==qa&&!i.parent},Xm=function(i){Vi(td,wt,function(){var e=i.facade;ws?Ga.emit("rejectionHandled",e):hd(Wm,e,i.value)})},Zt=function(i,e,t){return function(s){i(e,s,t)}},ti=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Qm,cd(i,!0))},ma=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ad("Promise can't be resolved itself");var s=dd(e);s?Va(function(){var r={done:!1};try{Vi(s,e,Zt(ma,r,i),Zt(ti,r,i))}catch(a){ti(r,a,i)}}):(i.value=e,i.state=od,cd(i,!1))}catch(r){ti({done:!1},r,i)}}};rd&&(Xt=function(e){Mm(this,Cr),Nm(e),Vi(ns,this);var t=Dr(this);try{e(Zt(ma,t),Zt(ti,t))}catch(s){ti(t,s)}},Cr=Xt.prototype,ns=function(e){qm(this,{type:Hs,done:!1,notified:!1,parent:!1,reactions:new Hm,rejection:!1,state:yo,value:void 0})},ns.prototype=Om(Cr,"then",function(e,t){var s=Dr(this),r=va(Um(this,Xt));return s.parent=!0,r.ok=ha(e)?e:!0,r.fail=ha(t)&&t,r.domain=ws?Ga.domain:void 0,s.state==yo?s.reactions.add(r):Va(function(){ld(r,s)}),r.promise}),To=function(){var i=new ns,e=Dr(i);this.promise=i,this.resolve=Zt(ma,e),this.reject=Zt(ti,e)},sd.f=va=function(i){return i===Xt||i===Jm?new To(i):jm(i)});Cm({global:!0,constructor:!0,wrap:!0,forced:rd},{Promise:Xt});Lm(Xt,Hs,!1,!0);xm(Hs);var Zm=Re,fd=Zm("iterator"),pd=!1;try{var eS=0,$o={next:function(){return{done:!!eS++}},return:function(){pd=!0}};$o[fd]=function(){return this},Array.from($o,function(){throw 2})}catch(i){}var tS=function(i,e){if(!e&&!pd)return!1;var t=!1;try{var s={};s[fd]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},iS=di,sS=tS,rS=Fi.CONSTRUCTOR,vd=rS||!sS(function(i){iS.all(i).then(void 0,function(){})}),aS=Ke,nS=Ne,oS=Ut,uS=li,dS=Fa,lS=Ba,cS=vd;aS({target:"Promise",stat:!0,forced:cS},{all:function(e){var t=this,s=uS.f(t),r=s.resolve,a=s.reject,n=dS(function(){var o=oS(t.resolve),d=[],u=0,l=1;lS(e,function(c){var h=u++,f=!1;l++,nS(o,t,c).then(function(m){f||(f=!0,d[h]=m,--l||r(d))},a)}),--l||r(d)});return n.error&&a(n.value),s.promise}});var hS=Ke,fS=Fi.CONSTRUCTOR,Ao=di;Ao&&Ao.prototype;hS({target:"Promise",proto:!0,forced:fS,real:!0},{catch:function(i){return this.then(void 0,i)}});var pS=Ke,vS=Ne,mS=Ut,SS=li,gS=Fa,bS=Ba,yS=vd;pS({target:"Promise",stat:!0,forced:yS},{race:function(e){var t=this,s=SS.f(t),r=s.reject,a=gS(function(){var n=mS(t.resolve);bS(e,function(o){vS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var TS=Ke,ES=Ne,$S=li,AS=Fi.CONSTRUCTOR;TS({target:"Promise",stat:!0,forced:AS},{reject:function(e){var t=$S.f(this);return ES(t.reject,void 0,e),t.promise}});var wS=mt,_S=pt,PS=li,md=function(i,e){if(wS(i),_S(e)&&e.constructor===i)return e;var t=PS.f(i),s=t.resolve;return s(e),t.promise},kS=Ke,RS=Mt,IS=vu,DS=di,CS=Fi.CONSTRUCTOR,OS=md,LS=RS("Promise"),xS=!CS;kS({target:"Promise",stat:!0,forced:IS},{resolve:function(e){return OS(xS&&this===LS?DS:this,e)}});var NS=Ke,Sa=di,BS=Fe,MS=Mt,US=Ee,FS=zu,wo=md,VS=Sa&&Sa.prototype,HS=!!Sa&&BS(function(){VS.finally.call({then:function(){}},function(){})});NS({target:"Promise",proto:!0,real:!0,forced:HS},{finally:function(i){var e=FS(this,MS("Promise")),t=US(i);return this.then(t?function(s){return wo(e,i()).then(function(){return s})}:i,t?function(s){return wo(e,i()).then(function(){throw s})}:i)}});var GS=Mt,Ya=GS,qS=Ya,YS=qS("Promise","finally"),jS=YS,zS=jS,WS=zS,QS=WS,Gs=QS,ii;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ii||(ii={}));var ri=(i,e=0,t=ii.OFFSET_P)=>{switch(t){case ii.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ii.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:F(t)}return i},I=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)},ae;(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"})(ae||(ae={}));const Je={[ae.Q_144P]:{width:256,height:144},[ae.Q_240P]:{width:428,height:240},[ae.Q_360P]:{width:640,height:360},[ae.Q_480P]:{width:856,height:480},[ae.Q_720P]:{width:1280,height:720},[ae.Q_1080P]:{width:1920,height:1080},[ae.Q_1440P]:{width:2560,height:1440},[ae.Q_2160P]:{width:3840,height:2160},[ae.Q_4320P]:{width:7680,height:4320}},bs=(i,e)=>Je[i].height>Je[e].height,JS=(i,e)=>Je[i].height>=Je[e].height,Pi=(i,e)=>Je[i].height<Je[e].height,KS=(i,e)=>Je[i].height<=Je[e].height,XS=i=>i.sort((e,t)=>e===t?0:e===ae.INVARIANT?1:t===ae.INVARIANT?-1:Pi(e,t)?1:-1)[0],ZS=Object.keys(Je).sort((i,e)=>Pi(i,e)?-1:1),Ft=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return ZS.find(r=>{const a=Je[r];return a.width>=s&&a.height>=t})},eg=i=>Je[i].height,_s=i=>i===ae.INVARIANT;class ce{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(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||P(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 tg=i=>{switch(i){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1: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 F(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const ig=5,sg=5,rg=500,_o=7e3;class ag{constructor(e){this.subscription=new ne,this.loadMediaTimeoutSubscription=new ne,this.videoState=new ce(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===p.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.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:F(s)}break}case p.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:F(s)}break}case p.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:F(s)}break}default:F(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(tg(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 ne;this.subscription.add(e),this.subscription.add(H(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 L;e.add(r.pipe(Ue(rg)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>ig)&&r.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),d=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<sg&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:F(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(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),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),I(this.params.desiredState.playbackState,p.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:z.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),I(this.params.desiredState.playbackState,p.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),I(this.params.desiredState.playbackState,p.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)===p.READY&&I(this.params.desiredState.playbackState,p.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];R(l);const c=XS(Object.keys(l));R(c);const h=l[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=s[e];R(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:case y.DASH_WEBM_AV1:{const l=s[e];R(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=s[e];R(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];R(l),r=ri(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:D.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return F(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:d,subtitle:u}=this.params.meta;return P(d)&&(o.metadata.title=d),P(u)&&(o.metadata.subtitle=u),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===z.Applying||s.state===z.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(tl(_o).subscribe(()=>a(`timeout(${_o})`)))});Gs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Po{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 Sd extends Po{constructor(){super(),this.listeners||Po.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 gd=class{constructor(){Object.defineProperty(this,"signal",{value:new Sd,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&&(gd.prototype[Symbol.toStringTag]="AbortController",Sd.prototype[Symbol.toStringTag]="AbortSignal");function bd(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 ng(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!bd({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(u,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(u,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:(d,u)=>{const l=a&&a.prototype.isPrototypeOf(d)?d.signal:u?u.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 u&&u.signal&&delete u.signal,Promise.race([h,n(d,u)])}return n(d,u)},Request:a}}const qs=bd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yd=qs?ng({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ai=qs?yd.fetch:window.fetch;qs?yd.Request:window.Request;const xt=qs?gd:window.AbortController,Ti=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ki{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 de(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]=Ti(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(Ti),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(),d=new xt,u=d.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:d};u.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:D.PARSER,message:"Error parsing response data",thrown:h}),h};return ai(o,{signal:u}).then(h=>{var f,m,S;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[b,v]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,v);const g=b.getReader(),E=parseInt((S=h.headers.get("Content-Length"))!==null&&S!==void 0?S:"",10)||a-r+1;l.data=new ArrayBuffer(E);const $=new Uint8Array(l.data),A=({done:C,value:Y})=>de(this,void 0,void 0,function*(){C?this.onBigRequestProgress(l):Y&&($.set(Y,l.loaded),l.loaded+=Y.byteLength,this.onBigRequestProgress(l),yield g==null?void 0:g.read().then(A,ki.suppressStreamErrors).catch(c))});g==null||g.read().then(A,ki.suppressStreamErrors).catch(c)},ki.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,d,u,l,c,h,f,m;if(!this.activeRequests.has(e)||!a)return;const S=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const b of S){const{request:v}=b,[g,E]=Ti(v),$=g>=t&&E<=t+r,A=t>=g&&t+r<E,C=a.slice(g-t,Math.min(E-t+1,r));if(($||A)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=C.byteLength,v.bytesTotal=s-t),$){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(N=>N!==b)),(c=b.success)===null||c===void 0||c.call(b,C,"",e);const Y=n?Array.from(n.headers.entries()).map(([N,U])=>`${N}: ${U}`).join(`\r
|
|
7
|
-
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(v,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,Y,[])}else A&&((m=b.progress)===null||m===void 0||m.call(b,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){var a,n,o,d;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:D.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const u=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of u){const[c,h]=Ti(l.request);(c>=t&&c<s||h>t&&h<=s)&&((d=l==null?void 0:l.error)===null||d===void 0||d.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[d,u]=Ti(o.request);(d>=t&&d<s||u>t&&u<=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 Ps{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(Ps.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;Ps.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const og=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new Ps(r,e,s)}}),ug=(i,e)=>{const t=new ki(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return og(n,t)}}},!0),()=>t.destroy()};var dg=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)},lg=i=>{const e=new T(1/0),t=new L,s=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},d=l=>{var c,h,f,m,S;const b=Ui(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(E=>E.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const E=parseInt((c=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?$:E*1e3)!==null&&f!==void 0?f:NaN;P(A)&&!isNaN(A)&&e.next(A)}const v=(m=b["x-delivery-type"])!==null&&m!==void 0?m:Ii.HTTP1,g=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;s.next(v),r.next(g)},u=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(...S){return d(this),f(...S)},h.progress=function(...S){return u(this),m(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ni=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},cg=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ni}),!0),hg=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 Qe=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),d=te(r),u=new ne;return r&&u.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),d&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),d&&i.setState(l.to)},a)),u},Vt=(i,e,t)=>Qe(e,()=>i.loop,s=>{P(s)&&(i.loop=s)},{onError:t}),St=(i,e,t,s)=>Qe(e,()=>({muted:i.muted,volume:i.volume}),r=>{P(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}),_t=(i,e,t,s)=>Qe(e,()=>i.playbackRate,r=>{P(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),fg=i=>["__",i.language,i.label].join("|"),pg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class nt{constructor(){this.available$=new L,this.current$=new T(void 0),this.error$=new L,this.subscription=new ne,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Qe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Qe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Qe(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(H(M(e,"addtrack"),M(e,"removetrack"),xe(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),Se((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(M(e,"change"),xe(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),_(s=>s&&this.htmlTextTrackToITextTrack(s).id),Se()).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(M(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var d,u,l,c,h;const f=(u=(d=o.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u: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(M(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;P(t.align)&&(r.align=t.align),P(t.position)&&(r.position=t.position),P(t.size)&&(r.size=t.size),P(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:fg(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,url:this.internalTracks.get(r).url}}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).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))P(e)&&pg(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){R(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const ja=i=>{i.removeAttribute("src"),i.load()},vg=i=>{try{i.pause(),i.playbackRate=0,ja(i),i.remove()}catch(e){console.error(e)}};class mg{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const ga=window.WeakMap?new WeakMap:new mg,gt=i=>{let e=i.querySelector("video");const t=Boolean(e);return e?ja(e):(e=document.createElement("video"),i.appendChild(e)),ga.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=i=>{const e=ga.get(i);ga.delete(i),e?ja(i):vg(i)};class za{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,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Td=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},ko=i=>{const e=Td(i);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===i)},Sg=i=>{const e=Td(i);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var Ed=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const ba=3;class gg{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<ba&&(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||ba))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 $d=(i,e,t=ba)=>{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 d=a-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=a+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const bg=1e3,yg=i=>i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,yt=i=>{const e=E=>M(i,E).pipe(si(void 0)),s=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>M(i,E))).pipe(_(E=>E.type==="ended"?i.readyState<2:i.readyState<3),Se()),r=H(M(i,"progress"),M(i,"timeupdate")).pipe(_(()=>$d(i.buffered,i.currentTime))),a=Ed()?rt({play:e("play").pipe(Te()),playing:e("playing")}).pipe(si(void 0)):e("playing"),n=M(i,"playing").pipe(Ue(bg),_(()=>yg(i))),o=M(i,"volumechange").pipe(_(()=>({muted:i.muted,volume:i.volume}))),d=M(i,"ratechange").pipe(_(()=>i.playbackRate)),u=M(i,"error").pipe(ie(()=>Boolean(i.error||i.played.length)),_(()=>{var E;const $=i.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(E=i.error)!==null&&E!==void 0?E:void 0}})),l=M(i,"timeupdate").pipe(_(()=>i.currentTime)),c=new L,h=.3;let f;l.subscribe(E=>{i.loop&&P(f)&&P(E)&&f>=i.duration-h&&E<=h&&c.next(f),f=E});const m=M(i,"enterpictureinpicture"),S=M(i,"leavepictureinpicture"),b=new T(Sg(i));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const v=new T(ko(i));return M(i,"fullscreenchange").pipe(_(()=>ko(i))).subscribe(v),{playing$:a,pause$:e("pause").pipe(ie(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:M(i,"durationchange").pipe(_(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:d,inPiP$:b,inFullscreen$:v}},Wa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Tg=Ke,Eg=Ms,$g=Ca,Ag=Da;Tg({target:"Array",proto:!0},{at:function(e){var t=Eg(this),s=$g(t),r=Ag(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var wg=Ya,_g=wg("Array","at"),Pg=_g,kg=Pg,Rg=kg,Ig=Rg,ut=Ig;let Qa=!1,lt={};const Dg=i=>{Qa=i},Cg=()=>{lt={}},Og=i=>{i(lt)},os=(i,e)=>{var t;Qa&&(lt.meta=(t=lt.meta)!==null&&t!==void 0?t:{},lt.meta[i]=e)};class it{constructor(e){this.name=e}next(e){var t,s;if(!Qa)return;lt.series=(t=lt.series)!==null&&t!==void 0?t:{};const r=(s=lt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),lt.series[this.name]=r}}const Lg=new it("best_bitrate"),xg=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class Ng{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Hi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:d,history:u})=>{var l,c,h,f;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,S=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},b=S&&Ft(S),v=s.considerPlaybackRate&&P(o)?o:1,g=i.filter(B=>!_s(B.quality)).sort((B,x)=>bs(B.quality,x.quality)?-1:1),E=(c=ut(g,-1))===null||c===void 0?void 0:c.quality,$=(h=ut(g,0))===null||h===void 0?void 0:h.quality,A=te(r)||P(r.min)&&P(r.max)&&Pi(r.max,r.min)||P(r.min)&&$&&bs(r.min,$)||P(r.max)&&E&&Pi(r.max,E),C=v*xg(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),N=g.filter(B=>{const x=b?Pi(B.quality,b):!0,Z=P(t)&&isFinite(t)&&P(B.bitrate)?t-a>=B.bitrate*C:!0,le=s.lazyQualitySwitch&&P(s.minBufferToSwitchUp)&&d&&!_s(d.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&bs(B.quality,d.quality),ve=A||(te(r.max)||KS(B.quality,r.max))&&(te(r.min)||JS(B.quality,r.min));return x&&Z&&!le&&ve})[0];N&&N.bitrate&&Lg.next(N.bitrate);const U=(f=N!=null?N:g[Math.ceil((g.length-1)/2)])!==null&&f!==void 0?f:i[0],Q=U&&u&&u.history[U.id]&&pe()-u.history[U.id]<=s.trackCooldown&&(!u.last||U.id!==u.last.id);if(U!=null&&U.id&&u&&!Q&&u.recordSelection(U),Q&&(u!=null&&u.last)){const B=u.last;return u==null||u.recordSwitch(B),B}return u==null||u.recordSwitch(U),U};var Ie=i=>new URL(i).hostname;const Bg=300,ks=(i,e=Bg)=>new Cs(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(al(n=>{const o=n[0];if(!o)return;let d,u;o.contentBoxSize&&o.contentBoxSize[0]?(u=o.contentBoxSize[0].blockSize,d=o.contentBoxSize[0].inlineSize):o.contentRect&&(d=o.contentRect.width,u=o.contentRect.height),P(d)&&P(u)&&t.next({width:d,height:u})},e));return a.observe(i),()=>a.disconnect()}),Mg=5e3,Ei={};var W;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const be=(i,e)=>new Cs(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class Ro{constructor(e){this.subscription=new ne,this.videoState=new ce(W.DOWNLOADING_LIB),this.textTracksManager=new nt,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new za,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===W.DOWNLOADING_LIB||t===W.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&t!==W.STOPPED&&s!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case p.STOPPED:{switch(t){case W.STOPPED:break;case W.PLAYING:case W.PAUSED:case W.READY:this.stop();break;default:F(t)}break}case p.READY:{switch(t){case W.STOPPED:this.prepare();break;case W.PLAYING:case W.PAUSED:case W.READY:break;default:F(t)}break}case p.PLAYING:{switch(t){case W.PLAYING:break;case W.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 W.READY:this.play();break;case W.STOPPED:this.prepare();break;default:F(t)}break}case p.PAUSED:{switch(t){case W.PLAYING:this.pause(),this.liveOffset.pause();break;case W.PAUSED:break;case W.READY:this.videoState.setState(W.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case W.STOPPED:this.prepare();break;default:F(t)}break}default:F(s)}},this.video=gt(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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:D.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Mg);Gs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Ei.MediaPlayer=r.MediaPlayer,Ei.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(Ei.MediaPlayer,"dashjs not loaded"),R(Ei.Debug,"dashjs not loaded"),this.player=Ei.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?Wa(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=ug(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&&hg(this.player),dg(this.player),this.params.tuning.requestQuick&&cg(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,g)=>this.subscription.add(v.subscribe(g,s));r(ks(this.video),this.elementSize$),r(be(this.player,"error").pipe(_(v=>{const g=typeof v.error=="object"?v.error.code:v.error,E=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${g}`,message:E}})),e.error$),r(be(this.player,"playbackError").pipe(_(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(ie(({mediaType:v})=>v==="video"),_(({newQuality:v})=>{var g;return(g=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===v))===null||g===void 0?void 0:g.track}));a.pipe(ie(P)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(ie(({to:v})=>v===W.STREAM_INITIALIZED),Te()).subscribe(()=>{this.subscription.add(Qe(t.videoTrack,()=>{var v,g;const E=this.player.getQualityFor("video");return(g=(v=this.videoTracks.find(({bitrateInfo:$})=>$.qualityIndex===E))===null||v===void 0?void 0:v.track)===null||g===void 0?void 0:g.id},v=>{var g;if(te(v))return;const E=(g=this.videoTracks.find(({track:$})=>$.id===v))===null||g===void 0?void 0:g.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:a.pipe(_(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(Qe(t.autoVideoTrackSwitching,()=>{var v,g,E;return(E=(g=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||g===void 0?void 0:g.autoSwitchBitrate)===null||E===void 0?void 0:E.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(ie(({mediaType:v})=>v==="video"),_(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:g}})=>{var E,$;const A=this.player.getDashMetrics(),C=A.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),Y=(E=A.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&E!==void 0?E:Ii.HTTP1,N=($={1:!0,0:!1}[C])!==null&&$!==void 0?$:void 0;this.params.output.httpConnectionType$.next(Y),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Ie(g))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:g,availableFrom:E}}})=>{this.isLive$.next(g),this.availableFrom$.next(E.getTime()),g||e.duration$.next(v),this.videoTracks=[];const $=this.player.getQualityFor("video");let A;for(const C of this.player.getBitrateInfoListFor("video")){const Y=C.qualityIndex.toString(10),N=Ft(C),U=C.bitrate/1e3,Q={width:C.width,height:C.height},B=this.frameRatesByFrameHeight[C.height];if(N){const x={id:Y,quality:N,bitrate:U,size:Q,fps:B};this.videoTracks.push({track:x,bitrateInfo:C}),C.qualityIndex===$&&(A=x)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:C})=>C)),A&&e.currentVideoTrack$.next(A),this.videoState.setState(W.STREAM_INITIALIZED),this.videoState.startTransitionTo(W.READY)}),r(be(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const g=v.requestEndDate.getTime()-v.firstByteDate.getTime(),E=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,g)}),r(H(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),g=Hi(this.videoTracks.map(({track:$})=>$),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),E=this.videoTracks.find(({track:$})=>$===g);E!=null&&E.bitrateInfo&&this.player.setQualityFor("video",E==null?void 0:E.bitrateInfo.qualityIndex,!1)}),r(rt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(ie(P))}).pipe(ie(({isLive:v})=>v),_(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe(_(({time:v})=>v!=null?v:0));r(rt({availableFrom:this.availableFrom$.pipe(ie(P)),currentTime:n}),({availableFrom:v,currentTime:g})=>this.params.output.liveTime$.next(v+g*1e3)),r(n.pipe(ie(()=>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(_(()=>$d(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(W.PLAYING),I(t.playbackState,p.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(W.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(W.PAUSED),I(t.playbackState,p.PAUSED)}),r(be(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===W.READY&&this.videoState.setState(W.READY)}),r(this.isLive$,e.isLive$),r(ks(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0));r(o,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:l,connectionReused$:c}=lg(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(Te()),e.firstBytesEvent$),r(be(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(rt({isLive:this.isLive$,isShort:e.duration$.pipe(_(v=>v<60))}),({isLive:v,isShort:g})=>{const E=!v&&g;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(n.pipe(ie(v=>v>this.params.tuning.insufficientBufferRuleMargin),Te()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(be(this.player,"manifestLoaded").pipe(Te()).subscribe(()=>{this.subscription.add(be(this.player,"playbackPlaying").pipe(Te(),si(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(be(this.player,"manifestLoaded"),v=>{var g,E,$,A,C,Y,N;if(!((E=(g=v.data)===null||g===void 0?void 0:g.Period)===null||E===void 0)&&E.AdaptationSet){const U=[];for(const Q of(A=($=v.data)===null||$===void 0?void 0:$.Period)===null||A===void 0?void 0:A.AdaptationSet)if(Q.contentType==="text"){const B=(C=Q.Representation)===null||C===void 0?void 0:C.id,x=new URL((Y=Q.Representation)===null||Y===void 0?void 0:Y.BaseURL,(N=v.data)===null||N===void 0?void 0:N.baseUri).toString(),Z="internal",le=Q.lang,ve=Boolean(B.includes("auto"));U.push({id:B,url:x,type:Z,language:le,isAuto:ve})}t.internalTextTracks.startTransitionTo(U)}}),this.subscription.add(Vt(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:S,inFullscreen$:b}=yt(this.video);this.subscription.add(St(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(_t(this.video,t.playbackRate,m,s)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(W.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(W.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=ri(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ii.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(W.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(W.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){}bt(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Gi=i=>{switch(i){case"mobile":return ae.Q_144P;case"lowest":return ae.Q_240P;case"low":return ae.Q_360P;case"sd":case"medium":return ae.Q_480P;case"hd":case"high":return ae.Q_720P;case"fullhd":case"full":return ae.Q_1080P;case"quadhd":case"quad":return ae.Q_1440P;case"ultrahd":case"ultra":return ae.Q_2160P}};const Io=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Pt=i=>de(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Io(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return Io(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function Pe(){return pe()}function Ad(i){return Pe()-i}function Do(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,d=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return d&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ug(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function ys(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,d=!1,u=0,l,c,h=!1,f="arraybuffer",m=7e3,S=2e3,b=()=>{if(d)return;R(l);const x=Ad(l);let Z;if(x<S){Z=S-x,setTimeout(b,Z);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new r,C()};const v=x=>(a=x,B),g=x=>(c=x,B),E=()=>(f="json",B),$=()=>{if(!d){if(--u>=0){b(),s&&s();return}d=!0,c&&c(),t&&t()}},A=x=>(h=x,B),C=()=>{l=Pe(),n=new r,n.open("get",i);let x=0,Z,le=0;const ve=()=>(R(l),Math.max(l,Math.max(Z||0,le||0)));if(a&&n.addEventListener("progress",k=>{const G=Pe();a.updateChunk&&k.loaded>x&&(a.updateChunk(ve(),k.loaded-x),x=k.loaded,Z=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(d)return;R(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const G=n.response.byteLength-x;G&&a.updateChunk&&a.updateChunk(ve(),G)}c&&c(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),h){const k=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Pe(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),B},B={withBitrateReporting:v,withParallel:A,withJSONResponse:E,withRetryCount:x=>(u=x,B),withRetryInterval:(x,Z)=>(P(x)&&(S=x),P(Z)&&(m=Z),B),withTimeout:x=>(o=x,B),withFinally:g,send:C,abort:()=>{n&&(n.abort(),n=void 0),d=!0,c&&c()}};return B}const Fg=100,Vg=2e3,Hg=500;let Gg=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-Hg;if(t-e>Vg){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 d=a.bytes*n/o;r+=d,a.start=t,a.bytes-=d}}}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>Fg&&(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 qg{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=Pe(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=d=>{e._complete=1,e._responseData=d,e._downloadTime=Pe()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ys(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=Pe()}_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=Pe();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 us=1e4,ds=3,Yg=300,jg=2e3,zg=6e4,Wg=10,Qg=1,Jg=500;class Kg{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 Gg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Do(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=Do(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||P(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=()=>{Ug(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 qg(ds,us,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,d=null,u=null,l=!1;const c=()=>{const $=a&&(!l||l===this.rep);return $||t("Not running!"),$},h=($,A,C)=>{d&&d.abort(),d=ys(this.urlResolver.resolve($,!1),A,C,()=>this._retryCallback()).withTimeout(us).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ds).withFinally(()=>{d=null}).send()},f=($,A,C)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),A,C,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=$=>{const A=s.playbackRate;s.playbackRate!==$&&(t(`Playback rate switch: ${A}=>${$}`),s.playbackRate=$)},S=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const C=Pe()-1e4;let Y=0;for(let U=0;U<this.bufferStates.length;U++){const Q=this.bufferStates[U];$=Math.min($,Q.buf),Q.ts<C&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${$} drop=${Y} jitter=${this.sourceJitter}`);let N=$-Qg;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?m(1.15):N>1?m(1.1):N>.3?m(1.05):m(1)}},v=$=>{let A;const C=()=>A&&A.start?A.start.length:0,Y=k=>A.start[k]/1e3,N=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,Q=(k,G)=>({chunkIdx:U(k),startTS:Y(k),dur:N(k),discontinuity:G}),B=()=>{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,me=G;this.sourceJitter>1&&(me+=this.sourceJitter-1);let ye=A.dur.length-1;for(;ye>=0&&(me-=A.dur[ye],!(me<=0));--ye);k=Math.min(ye,A.dur.length-1-oe),k=Math.max(k,0)}return Q(k,!0)},x=k=>{const G=C();if(!(G<=0)){if(P(k)){for(let oe=0;oe<G;oe++)if(Y(oe)>k)return Q(oe)}return B()}},Z=k=>{const G=C(),oe=k?k.chunkIdx+1:0,me=oe-A.fragIndex;if(!(G<=0)){if(!k||me<0||me-G>Wg)return t(`Resync: offset=${me} bChunks=${G} chunk=`+JSON.stringify(k)),B();if(!(me>=G))return Q(oe-A.fragIndex,!1)}},le=(k,G,oe)=>{u&&u.abort(),u=ys(this.urlResolver.resolve(k,!0,this.lowLatency),G,oe,()=>this._retryCallback()).withTimeout(us).withRetryCount(ds).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,G)=>{le($,oe=>{if(!c())return;A=oe;const me=Boolean(A.lowLatency);me!==this.lowLatency&&S(me);let ye=0;for(let De=0;De<A.dur.length;++De)ye+=A.dur[De];ye>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ye/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(x(G))},()=>this._handleNetworkError())},nextChunk:Z}},g=()=>{a=!1,o&&o.abort(),d&&d.abort(),u&&u.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:$=>{const{videoElement:A,logger:C}=this.params;let Y=v(e.jidxUrl),N,U,Q,B,x=0,Z,le,ve;const k=()=>{Z&&(clearTimeout(Z),Z=void 0);const K=Math.max(Jg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=x+K,Ce=Pe(),Ge=Math.min(1e4,$e-Ce);x=Ce;const ot=()=>{u||c()&&Y.seek(()=>{c()&&(x=Pe(),G(),k())})};Ge>0?Z=window.setTimeout(()=>{this.paused?k():ot()},Ge):ot()},G=()=>{let K;for(;K=Y.nextChunk(B);)B=K,Xe(K);const $e=Y.nextChunk(Q);if($e){if(Q&&$e.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?k():(g(),this._initPlayerWith(e));return}De($e)}else k()},oe=(K,$e)=>{if(!c()||!this.sourceBuffer)return;let Ce,Ge,ot;const kt=Tt=>{window.setTimeout(()=>{c()&&oe(K,$e)},Tt)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),kt(100);else{const Tt=Pe(),Ht=A.currentTime;!this.paused&&A.buffered.length>1&&le===Ht&&Tt-ve>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),le!==Ht&&(le=Ht,ve=Tt);const Ze=this._getBufferSizeSec();if(Ze>30)C(`Buffered ${Ze} seconds; delaying appendBuffer`),kt(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:Tt,buf:Ze}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(ci){if(ci.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Ce=this.sourceBuffer.buffered.start(0),Ge=Ht,Ge-Ce>4&&this.sourceBuffer.remove(Ce,Ge-3)),kt(1e3);else throw ci}}},me=()=>{U&&N&&(C([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Q)]),oe(U,function(){U=null,G()}))},ye=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),De=K=>{c()&&f(ye(K),($e,Ce)=>{if(c()){if(Ce/=1e3,U=$e,Q=K,n=K.startTS,Ce){const Ge=Math.min(10,K.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ge:Ge}me()}},()=>this._handleNetworkError())},Xe=K=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ye(K),!1)))},He=K=>{c()&&(e.cachedHeader=K,oe(K,()=>{N=!0,me()}))};a=!0,Y.seek(K=>{if(c()){if(x=Pe(),!K){k();return}B=K,!te($)||K.startTS>$?De(K):(Q=K,G())}},$),e.cachedHeader?He(e.cachedHeader):h(e.headerUrl,He,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),P(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(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=Pe();if(this.chunkRateEstimator.addInterval(h,m,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:b}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,d=!0;const u=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(d&&c>o&&Ad(n)<3e4)return;s(c)}d=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&u(),f},notifySwitch:c=>{const h=Pe();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=ys(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(us).withRetryCount(ds).withRetryInterval(Yg,jg).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Pt(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((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,o.push(d))}),o.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.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))},zg))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const Xg=[j.PAUSED,j.PLAYING,j.READY],Zg=[j.PAUSED,j.PLAYING,j.READY];class eb{constructor(e){this.subscription=new ne,this.videoState=new ce(j.STOPPED),this.representations$=new T([]),this.textTracksManager=new nt,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new za,this._dashCb=r=>{var a,n,o,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,l=[];for(const c of u){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Gi(c.name))!==null&&n!==void 0?n:Ft(c.video),m=c.bitrate/1e3,S=Object.assign({},c.video);if(!f)continue;const b={id:h,quality:f,bitrate:m,size:S};l.push({track:b,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,l=(d=this.representations$.getValue().find(({representation:c})=>c===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),P(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:u,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,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(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(u)};`}),o===p.STOPPED){a!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(!n){if(Zg.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;P(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((d==null?void 0:d.to)!==p.PAUSED&&u.state===z.Requested&&Xg.includes(a)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(a){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(ri(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(o===p.PAUSED)this.videoState.setState(j.PAUSED);else if(o===p.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const l=d==null?void 0:d.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:o===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:o===p.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return F(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:r})};H(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=gt(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(Ie(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=yt(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Se(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(rt({zeroTime:this.zeroTime$.pipe(ie(P)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Vt(this.video,this.params.desiredState.isLooped,t)).add(St(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(_t(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(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&eg(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return F(r.to)}},t)).add(H(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}createLiveDashPlayer(){const e=new Kg({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(),d=(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(),u=(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=!u&&P(d)?d:(a=Hi(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;R(c,"Representations missing"),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;R(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=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ri(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var wd=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?Ii.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}},Lt=(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 tb=i=>{const e=document.createElement("a");return e.href=i,e.origin},ib=i=>{const e=document.createElement("a");return e.href=i,e.host};class _d{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,d,u;if(R(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=Ui(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&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(l){throw(u=this._errorCb)===null||u===void 0||u.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(ib(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 Rs{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 d=0;const u=Date.now();let l=0,c=0,h=0;const f=S=>{r(Rs._str2ua(S.substr(d))),d=S.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ni(m)),this._lastXhr=new _d(m,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const b=Date.now()-u;this._params.onBandwidthChange({size:S.length,duration:b,speed:8*S.length/(b/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),a==null||a()},S=>{if(S.length-d>o&&f(S),c===0){c=Date.now();return}h=S.length-l;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,l=S.length,c=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},n,(S,b,v)=>this._params.onError(S,b,v))})}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=Rs._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 sb{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,d)=>{const u=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},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=ni(s)),new _d(s,t,r=>{this.attachManifest(r,t,tb(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=(u,l)=>{const c=u.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],d=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),u=>{var l,c,h,f,m,S,b,v,g,E,$,A,C,Y,N,U,Q,B,x;const Z=u.getElementsByTagName("SegmentBase")[0],le=Z&&n(Z,"indexRange").split("-"),ve=Z&&Z.getElementsByTagName("Initialization")[0],k=ve&&n(ve,"range").split("-");if(!k||!le){const Xe=u.parentElement;if((Xe==null?void 0:Xe.getAttribute("contentType"))==="text"){const He=(l=u.getAttribute("id"))!==null&&l!==void 0?l:void 0,K=(s?s+"/":"")+((m=(f=(h=(c=u.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),$e=(S=Xe.getAttribute("lang"))!==null&&S!==void 0?S:void 0,Ce=He==null?void 0:He.includes("auto");K&&d.push({id:He,url:K,language:$e,isAuto:Ce})}return}const G=.1,oe=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),me=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ye;const De=(g=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&g!==void 0?g:void 0;ye=De?Wa(De):void 0,o.push({width:Number((E=u.attributes.getNamedItem("width"))===null||E===void 0?void 0:E.value),height:Number(($=u.attributes.getNamedItem("height"))===null||$===void 0?void 0:$.value),bandwidth:oe,baseURL:me,failoverHosts:t,indexFrom:Number(le[0]),indexTo:Number(le[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(C=(A=u.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&C!==void 0?C:void 0,mimeType:(N=(Y=u.attributes.getNamedItem("mimeType"))===null||Y===void 0?void 0:Y.value)!==null&&N!==void 0?N:void 0,fps:ye,bufferSize:G*oe/8,bufferLength:G,name:(Q=(U=u.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&Q!==void 0?Q:void 0,id:(x=(B=u.attributes.getNamedItem("id"))===null||B===void 0?void 0:B.value)!==null&&x!==void 0?x:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}d.forEach(({id:u,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),u&&h.setAttribute("id",u),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((u,l)=>l.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_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 d=n.getUint32(a,!1),u=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=u+(n.getUint32(a,!1)&2147483647),m=d+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:d/o,toTime:m/o,fromOffset:u,toOffset:f-1}),u=f,d=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 u=this._findRef(this._video.currentTime);if(!u||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(u.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(u.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(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}o()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Rs({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-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),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?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,d)=>this._stream.remove(o,d)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,d)=>this._stream.remove(o,d)),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||te(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 J;(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"})(J||(J={}));const rb=[J.PAUSED,J.PLAYING];class ab{constructor(e){this.videoState=new ce(J.STOPPED),this.subscription=new ne,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new nt,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,a,n;const o=[];for(const d of t){const u=(a=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&a!==void 0?a:d.height.toString(10),l=(n=d.name&&Gi(d.name))!==null&&n!==void 0?n:Ft(d),c=d.bandwidth/1e3,h={width:d.width,height:d.height},f=d.fps;if(!l)continue;const m={id:u,quality:l,bitrate:c,size:h,fps:f};o.push({track:m,representation:d})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const l=u.id||`${u.language}_${Date.now()}`;d.push({id:l,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(J.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 R(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===p.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&rb.includes(t)&&this.seek(n.position,n.forcePrecise),t){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_LOADED),this.prepare();return;case J.MANIFEST_LOADED:this.videoState.startTransitionTo(J.INITIAL_REPRESENTATION_SELECTED);return;case J.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(J.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case J.METADATA_LOADED:this.videoState.startTransitionTo(J.READY),this.dash.updateRefsForCurrentTime();return;case J.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case J.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),H(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=gt(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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new gg(this.video),this.dash=new sb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),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:D.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:D.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:o},a=yt(this.video),n=(o,d)=>this.subscription.add(o.subscribe(d,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$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{te(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===J.PLAYING||this.videoState.getState()===J.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Vt(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_t(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(ks(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===J.READY&&this.videoState.setState(J.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(J.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(_(({id:o,message:d,thrown:u})=>({id:`DashLite_${o}`,category:D.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(H(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe(_(()=>{var o,d,u;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(),S=this.elementSize$.getValue(),b=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let v;if(!b&&P(f))v=f;else{const g=Lt(this.video.buffered,this.video.currentTime*1e3),E=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(g/E,1);v=(d=Hi(c.map(({track:A})=>A),{container:S,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||d===void 0?void 0:d.id}return P(v)?(u=c.find(({track:g})=>g.id===v))===null||u===void 0?void 0:u.representation:void 0}),Se()).subscribe(this.currentRepresentation$,s)).add(rt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(ie(o=>o.to===J.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(ie(P))}).pipe(Te()).subscribe(()=>this.videoState.setState(J.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(ie(P),Se((o,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=d.height:o===d)).subscribe(o=>{const d=Lt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ie(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:d,reused:u}=wd(o);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(Te(),si(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(ie(P)).subscribe(this.handleRepresentationPlay,s)).add(H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return F(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var we;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(we||(we={}));var Is;(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"})(Is||(Is={}));var Me;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Me||(Me={}));var ee;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(ee||(ee={}));var oi;(function(i){i.MP4="mp4",i.WEBM="webm"})(oi||(oi={}));var ya=(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 nb=(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)},ob=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=ob?nb:window.requestIdleCallback;var Or,Lr;let Pd=!1;try{Pd=Ed()&&parseInt((Lr=(Or=navigator.userAgent.match(/Version\/(\d+)/))===null||Or===void 0?void 0:Or[1])!==null&&Lr!==void 0?Lr:"",10)<16}catch(i){console.error(i)}class ub{constructor(e){this.bufferFull$=new L,this.error$=new L,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:D.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return de(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 de(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 de(this,void 0,void 0,function*(){return new Promise(t=>{let s;Pd&&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);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation: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"||this.error$.next({id:`BufferTaskQueue:${s}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:F(t)}}}var Oo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const kd=new TextDecoder("ascii"),Rd=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=kd.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}},db=i=>kd.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",lb=(i,e,t)=>{const s=Rd(i),r=[];let a=0;const n=()=>{const S=s.contents.getUint32(a);return a+=4,S};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const u=n(),l=n(),c=n(),h=n()&4294967295;let f=l/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+c;for(let S=0;S<h;S++){const b=n(),v=b>>>31,g=b<<1>>>1,E=n();if(n(),v!==0)throw new Error("Unsupported multilevel sidx");const $=E/u*1e3;r.push({status:ee.NONE,time:{from:f,to:f+$},byte:{from:m,to:m+g-1}}),f+=$,m+=g}return r},cb=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=Rd(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},hb={validateData:db,parseInit:()=>null,getIndexRange:()=>{},parseSegments:lb,parseFeedableSegmentChunk:cb};var w;(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"})(w||(w={}));var O;(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"})(O||(O={}));const Lo={[w.EBML]:{type:O.Master},[w.EBMLVersion]:{type:O.UnsignedInteger},[w.EBMLReadVersion]:{type:O.UnsignedInteger},[w.EBMLMaxIDLength]:{type:O.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:O.UnsignedInteger},[w.DocType]:{type:O.String},[w.DocTypeVersion]:{type:O.UnsignedInteger},[w.DocTypeReadVersion]:{type:O.UnsignedInteger},[w.Void]:{type:O.Binary},[w.Segment]:{type:O.Master},[w.SeekHead]:{type:O.Master},[w.Seek]:{type:O.Master},[w.SeekID]:{type:O.Binary},[w.SeekPosition]:{type:O.UnsignedInteger},[w.Info]:{type:O.Master},[w.TimestampScale]:{type:O.UnsignedInteger},[w.Duration]:{type:O.Float},[w.Tracks]:{type:O.Master},[w.Chapters]:{type:O.Master},[w.Cluster]:{type:O.Master},[w.Timestamp]:{type:O.UnsignedInteger},[w.SilentTracks]:{type:O.Master},[w.SilentTrackNumber]:{type:O.UnsignedInteger},[w.Position]:{type:O.UnsignedInteger},[w.PrevSize]:{type:O.UnsignedInteger},[w.SimpleBlock]:{type:O.Binary},[w.BlockGroup]:{type:O.Master},[w.EncryptedBlock]:{type:O.Binary},[w.Attachments]:{type:O.Master},[w.Tags]:{type:O.Master},[w.Cues]:{type:O.Master},[w.CuePoint]:{type:O.Master},[w.CueTime]:{type:O.UnsignedInteger},[w.CueTrackPositions]:{type:O.Master},[w.CueTrack]:{type:O.UnsignedInteger},[w.CueClusterPosition]:{type:O.UnsignedInteger},[w.CueRelativePosition]:{type:O.UnsignedInteger},[w.CueDuration]:{type:O.UnsignedInteger},[w.CueBlockNumber]:{type:O.UnsignedInteger},[w.CueCodecState]:{type:O.UnsignedInteger},[w.CueReference]:{type:O.Master},[w.CueRefTime]:{type:O.UnsignedInteger}},Id=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=Ds(i,t),r=s in Lo,a=r?Lo[s].type:O.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 d=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,l=Ds(d),c=u*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}},Ds=(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},ct=(i,e)=>{switch(e){case O.SignedInteger:return i.getInt8(0);case O.UnsignedInteger:return Ds(i);case O.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case O.String:return new TextDecoder("ascii").decode(i);case O.UTF8:return new TextDecoder("utf-8").decode(i);case O.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case O.Master:return i;case O.Binary:return i;default:F(e)}},qi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Id(s);if(!e(r))return;r.type===O.Master&&qi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},fb=i=>{if(i.getUint32(0)!==w.EBML)return!1;let e,t,s;const r=Id(i);return qi(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=ct(o,n):a===w.DocType?t=ct(o,n):a===w.DocTypeReadVersion&&(s=ct(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Dd=[w.Info,w.SeekHead,w.Tracks,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],pb=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],vb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,d,u;return qi(i,({tag:l,type:c,value:h,valueSize:f})=>{if(l===w.SeekID){const m=ct(h,c);u=Ds(m)}else l!==w.SeekPosition&&(u=void 0);return l===w.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===w.Info?a=!0:l===w.SeekHead?n=!0:l===w.TimestampScale?s=ct(h,c):l===w.Duration?r=ct(h,c):l===w.SeekPosition&&u===w.Cues?d=ct(h,c):a&&n&&Dd.includes(l)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(r,"Failed to parse webm Segment duration"),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:d}},mb=i=>{if(te(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Sb=(i,e)=>{let t=!1,s=!1;const r=o=>P(o.time)&&P(o.position),a=[];let n;return qi(i,({tag:o,type:d,value:u})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=ct(u,d));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=ct(u,d));break;default:t&&Dd.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,d)=>{const{time:u,position:l}=o,c=a[d+1];return{status:ee.NONE,time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},gb=i=>{let e=0,t=!1;try{qi(i,s=>s.tag===w.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):pb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},bb={validateData:fb,parseInit:vb,getIndexRange:mb,parseSegments:Sb,parseFeedableSegmentChunk:gb};class xo{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:d=!1}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.error$=new L,this.gaps=[],this.subscription=new ne,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new xt,this.destroyAbortController=new xt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=ze(this.destroyAbortController.signal,function(u){return We(this,arguments,function*(){const l=this.representations.get(u);R(l,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new ub(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Oo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield V(this.loadInit(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id);if(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield V(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;P(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield yield V(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=ze(this.destroyAbortController.signal,function(u){return We(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield V(void 0);this.switchingToRepresentationId=u;const l=this.representations.get(u);R(l,`No such representation ${u}`);let c=this.initData.get(u);if(te(c)?yield yield V(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield V(c)),c=this.initData.get(u),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield V(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield V(this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal));const h=this.getCurrentPosition();P(h)&&this.maintain(h)})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case oi.MP4:this.containerParser=hb;break;case oi.WEBM:this.containerParser=bb;break;default:F(s)}this.initData=new Map(r.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(r.map(u=>[u.id,u])),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 xt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(R(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Lt(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)&&Oo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Lt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))u="high";else{const l=ut(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===ee.FED&&!o.length&&Lt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=ut(s,-1);d&&d.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}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(d=>d.time.from<=e&&d.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const S=h<=s&&f>=s,b=h>s||S||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=s+v||f<=s+v;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&b&&g&&this.sourceBuffer&&!ya(this.sourceBuffer.buffered,s))&&b&&g});if(r===-1)return[];if(t!==Me.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=u||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===ee.NONE||h.status===ee.PARTIALLY_EJECTED)d.push(h);else break}return d}loadSegments(e,t,s="auto"){return de(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Me.BYTE_RANGE:{r=t.segmentReference.url,a={from:ut(e,0).byte.from,to:ut(e,-1).byte.to};break}case Me.TEMPLATE:{const u=ut(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),n=[u];break}default:F(o)}for(const u of n)u.status=ee.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield ze(d,function(){return We(this,arguments,function*(){const u=un(this.failedDownloads,this.tuning.downloadBackoff);yield yield V(new Promise(l=>setTimeout(l,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(u,l)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,a?a.from:0,l,d)}catch(c){this.error$.next({id:"SegmentFeeding",category:D.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&P(r)&&(s=Lt((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:D.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=ee.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===ee.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=u===Me.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 b=f?h.byte.from-s:0,v=f?h.byte.to-s:e.byteLength,g=b<r,E=v<=r;if(h.status===ee.DOWNLOADING&&g&&E){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const $=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append($,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(c.loadedBytes=Math.min(m,r-b),c.loadedBytes>c.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===m?$:this.containerParser.parseFeedableSegmentChunk($);A!=null&&A.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(C=>{if(a.aborted)n();else if(C)c.fedBytes+=A.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Co(()=>Gs(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return de(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?ze(this.destroyAbortController.signal,function(){return We(this,arguments,function*(){const o=un(this.failedDownloads,this.tuning.downloadBackoff);yield yield V(new Promise(d=>setTimeout(d,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:d,segments:u}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:D.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return de(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||te(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const d=u=>{var l;a=Math.min(a,u.time.from),n=Math.max(n,u.time.to);const c="size"in u?(l=u.size)!==null&&l!==void 0?l:0:u.byte.to-u.byte.from;r+=c};for(const u of this.segments.values())for(const l of u){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.FED&&d(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const u of this.segments.values())for(const l of u){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===ee.FED&&d(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===ee.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 u=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+u&&c.status===ee.FED&&d(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=Co(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(te(this.sourceBuffer)||te(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!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),d=e.some(l=>l.from-t<=n&&l.to+t>=o),u=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);d||(u.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var ei;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(ei||(ei={}));class yb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new xt,this.subscription=new ne,this.fetchManifest=ze(this.abortAllController.signal,function(r){return We(this,arguments,function*(){let a=r;this.requestQuic&&(a=ni(a));const n=yield yield V(ai(a,{signal:this.abortAllController.signal}).catch($i));return n?(this.onHeadersReceived(n.headers),yield V(n.text())):yield V(null)})}.bind(this)),this.fetch=ze(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?ei.HEADER:ei.PARAM,range:n,onProgress:o,priority:d="auto",signal:u,measureThroughput:l=!0}={}){var c,h,f,m;return We(this,arguments,function*(){let S=r;const b=new Headers;if(n)switch(a){case ei.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case ei.PARAM:{const k=new URL(S,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),S=k.toString();break}default:F(a)}this.requestQuic&&(S=ni(S));let v=this.abortAllController.signal;if(u){const k=new xt;if(this.subscription.add(H(M(this.abortAllController.signal,"abort"),M(u,"abort")).subscribe(()=>{try{k.abort()}catch(G){$i(G)}})),this.abortAllController.signal.aborted||u.aborted)try{k.abort()}catch(G){$i(G)}v=k.signal}const g=pe(),E=yield yield V(ai(S,{priority:d,headers:b,signal:v}).catch($i)),$=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-g),!E)return yield V(null);if(!E.ok||!E.body)return yield V(Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`)));this.onHeadersReceived(E.headers);const A=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield yield V(E.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,pe()-$),o==null||o(new DataView(k),k.byteLength),yield V(k)}if(!o&&!l)return yield V(E.arrayBuffer());const[C,Y]=E.body.tee(),N=C.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(Y));let U=0;const Q=new ArrayBuffer(A),B=new Uint8Array(Q),x=new DataView(Q);let Z=!1;const le=k=>{Z=!0,$i(k)},ve=ze(v,function({done:k,value:G}){return We(this,arguments,function*(){if(U===0&&this.lastRequestFirstBytes$.next(pe()-g),v.aborted)return yield V(void 0);!k&&G&&(B.set(G,U),U+=G.byteLength,o==null||o(x,U),yield yield V(N==null?void 0:N.read().then(ve,le)))})}.bind(this));return yield yield V(N==null?void 0:N.read().then(ve,le)),yield V(Z?null:Q)})}.bind(this)),this.fetchByteRangeRepresentation=ze(this.abortAllController.signal,function(r,a,n){var o;return We(this,arguments,function*(){if(r.type!==Me.BYTE_RANGE)return yield V(null);const{from:d,to:u}=r.initRange;let l=d,c=u,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=u+1===f,h&&(l=Math.min(f,d),c=Math.max(m,u))),l=Math.min(l,0);const S=yield yield V(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield V(null);const b=new DataView(S,d-l,u-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),g=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!g)throw new ReferenceError("No way to load representation index");let E;if(h)E=new DataView(S,g.from-l,g.to-g.from+1);else{const A=yield yield V(this.fetch(r.url,{range:g,priority:n,measureThroughput:!1}));if(!A)return yield V(null);E=new DataView(A)}const $=a.parseSegments(E,v,g);return yield V({dataView:new DataView(S),segments:$})})}.bind(this)),this.fetchTemplateRepresentation=ze(this.abortAllController.signal,function(r,a){return We(this,arguments,function*(){if(r.type!==Me.TEMPLATE)return yield V(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield V(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield V(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:ee.NONE,size:void 0}));return yield V({segments:d,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=wd(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return de(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Me.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Me.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:F(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const $i=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var Tb=pt,Eb=Oi,$b=Re,Ab=$b("match"),wb=function(i){var e;return Tb(i)&&((e=i[Ab])!==void 0?!!e:Eb(i)=="RegExp")},_b=Mi,Pb=String,kb=function(i){if(_b(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Pb(i)},Rb=mt,Ib=function(){var i=Rb(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},Db=Ne,Cb=at,Ob=Ls,Lb=Ib,No=RegExp.prototype,xb=function(i){var e=i.flags;return e===void 0&&!("flags"in No)&&!Cb(i,"flags")&&Ob(No,i)?Db(Lb,i):e},Ja=Ve,Nb=Ms,Bb=Math.floor,xr=Ja("".charAt),Mb=Ja("".replace),Nr=Ja("".slice),Ub=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Fb=/\$([$&'`]|\d{1,2})/g,Vb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,d=Fb;return r!==void 0&&(r=Nb(r),d=Ub),Mb(a,d,function(u,l){var c;switch(xr(l,0)){case"$":return"$";case"&":return i;case"`":return Nr(e,0,t);case"'":return Nr(e,n);case"<":c=r[Nr(l,1,-1)];break;default:var h=+l;if(h===0)return u;if(h>o){var f=Bb(h/10);return f===0?u:f<=o?s[f-1]===void 0?xr(l,1):s[f-1]+xr(l,1):u}c=s[h-1]}return c===void 0?"":c})},Hb=Ke,Gb=Ne,Ka=Ve,Bo=Ea,qb=Ee,Yb=Li,jb=wb,Qt=kb,zb=Bs,Wb=xb,Qb=Vb,Jb=Re,Kb=Jb("replace"),Xb=TypeError,Cd=Ka("".indexOf),Zb=Ka("".replace),Mo=Ka("".slice),ey=Math.max,Uo=function(i,e,t){return t>i.length?-1:e===""?t:Cd(i,e,t)};Hb({target:"String",proto:!0},{replaceAll:function(e,t){var s=Bo(this),r,a,n,o,d,u,l,c,h,f=0,m=0,S="";if(!Yb(e)){if(r=jb(e),r&&(a=Qt(Bo(Wb(e))),!~Cd(a,"g")))throw Xb("`.replaceAll` does not allow non-global regexes");if(n=zb(e,Kb),n)return Gb(n,e,s,t);if(r)return Zb(Qt(s),e,t)}for(o=Qt(s),d=Qt(e),u=qb(t),u||(t=Qt(t)),l=d.length,c=ey(1,l),f=Uo(o,d,0);f!==-1;)h=u?Qt(t(d,f,o)):Qb(d,o,f,[],void 0,t),S+=Mo(o,m,f)+h,m=f+l,f=Uo(o,d,f+c);return m<o.length&&(S+=Mo(o,m)),S}});var ty=Ya,iy=ty("String","replaceAll"),sy=iy,ry=sy,ay=ry,ny=ay,Fo=ny;const Vo=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const d=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(d)?0:d)*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},Br=(i,e)=>{let t=i;t=Fo(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=Fo(t,n,(o,d)=>te(a)?o:te(d)?a:a.padStart(parseInt(d,10),"0"))}return t},oy=(i,e)=>{var t,s,r,a,n,o,d,u,l,c,h,f,m,S,b,v,g,E,$,A,C,Y,N,U,Q,B,x,Z,le,ve,k,G,oe,me,ye,De,Xe,He,K,$e;const Ge=new DOMParser().parseFromString(i,"application/xml"),ot={video:[],audio:[],text:[]},kt=Ge.children[0],Tt=kt.getElementsByTagName("Period")[0],Ht=Tt.children;let Ze;const ci=kt.getAttribute("mediaPresentationDuration"),Xa=Tt.getAttribute("duration");if(ci)Ze=Vo(ci);else if(Xa){const qe=Vo(Xa);P(qe)&&(Ze=qe)}let Ud=0;const js=(s=(t=kt.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Fd=js.includes(Is.WEBM_AS_IN_FFMPEG)||js.includes(Is.WEBM_AS_IN_SPEC)?oi.WEBM:oi.MP4;for(const qe of Ht){const Yi=qe.getAttribute("mimeType"),Vd=qe.getAttribute("codecs"),Za=(r=qe.getAttribute("contentType"))!==null&&r!==void 0?r:Yi==null?void 0:Yi.split("/")[0],Hd=(n=(a=qe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],en=qe.querySelectorAll("Representation"),Gd=qe.querySelector("SegmentTemplate");if(Za===we.TEXT){for(const ge of en){const Et=ge.getAttribute("id")||"",ji=qe.getAttribute("lang"),Gt=(u=(d=(o=ge.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",zs=Et.includes("auto"),Ws=new URL(Gt,e).toString();ot[we.TEXT].push({id:Et,lang:ji,kind:we.TEXT,url:Ws,isAuto:zs})}continue}for(const ge of en){const Et=(l=ge.getAttribute("mimeType"))!==null&&l!==void 0?l:Yi,ji=(h=(c=ge.getAttribute("codecs"))!==null&&c!==void 0?c:Vd)!==null&&h!==void 0?h:"",Gt=(m=(f=ge.getAttribute("contentType"))!==null&&f!==void 0?f:Et==null?void 0:Et.split("/")[0])!==null&&m!==void 0?m:Za,zs=(b=(S=qe.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Ws=parseInt((v=ge.getAttribute("width"))!==null&&v!==void 0?v:"",10),tn=parseInt((g=ge.getAttribute("height"))!==null&&g!==void 0?g:"",10),sn=parseInt((E=ge.getAttribute("bandwidth"))!==null&&E!==void 0?E:"",10)/1e3,rn=($=ge.getAttribute("frameRate"))!==null&&$!==void 0?$:"",qd=(A=ge.getAttribute("quality"))!==null&&A!==void 0?A:void 0,Yd=rn?Wa(rn):void 0,jd=(C=ge.getAttribute("id"))!==null&&C!==void 0?C:(Ud++).toString(10),zd=Gt==="video"?`${tn}p`:Gt==="audio"?`${sn}Kbps`:ji,Wd=`${jd}@${zd}`,Qd=(U=(N=(Y=ge.querySelector("BaseURL"))===null||Y===void 0?void 0:Y.textContent)===null||N===void 0?void 0:N.trim())!==null&&U!==void 0?U:"",an=new URL(Qd,e).toString(),Jd=[...js,...Hd,...zs];let Qs;const Kd=ge.querySelector("SegmentBase"),Rt=(Q=ge.querySelector("SegmentTemplate"))!==null&&Q!==void 0?Q:Gd;if(Kd){const hi=(x=(B=ge.querySelector("SegmentBase Initialization"))===null||B===void 0?void 0:B.getAttribute("range"))!==null&&x!==void 0?x:"",[fi,Ks]=hi.split("-").map(It=>parseInt(It,10)),pi={from:fi,to:Ks},vi=(Z=ge.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[Xs,zi]=vi?vi.split("-").map(It=>parseInt(It,10)):[],mi=vi?{from:Xs,to:zi}:void 0;Qs={type:Me.BYTE_RANGE,url:an,initRange:pi,indexRange:mi}}else if(Rt){const hi={representationId:(le=ge.getAttribute("id"))!==null&&le!==void 0?le:void 0,bandwidth:(ve=ge.getAttribute("bandwidth"))!==null&&ve!==void 0?ve:void 0},fi=parseInt((k=Rt.getAttribute("timescale"))!==null&&k!==void 0?k:"",10),Ks=(G=Rt.getAttribute("initialization"))!==null&&G!==void 0?G:"",pi=Rt.getAttribute("media"),vi=(me=parseInt((oe=Rt.getAttribute("startNumber"))!==null&&oe!==void 0?oe:"",10))!==null&&me!==void 0?me:1,Xs=Br(Ks,hi);if(!pi)throw new ReferenceError("No media attribute in SegmentTemplate");const zi=(ye=Rt.querySelectorAll("SegmentTimeline S"))!==null&&ye!==void 0?ye:[],mi=[];if(zi.length){let It=vi,Dt=0;for(const Si of zi){const qt=parseInt((De=Si.getAttribute("d"))!==null&&De!==void 0?De:"",10)*1e3,gi=parseInt((Xe=Si.getAttribute("r"))!==null&&Xe!==void 0?Xe:"",10)||0,bi=(K=parseInt((He=Si.getAttribute("t"))!==null&&He!==void 0?He:"",10))!==null&&K!==void 0?K:void 0;for(let nn=0;nn<gi+1;nn++){const Xd=Br(pi,Object.assign(Object.assign({},hi),{segmentNumber:It.toString(10),segmentTime:bi.toString(10)})),Zd=bi?bi/fi:Dt;Dt+=qt/fi;const el=Dt;It++,mi.push({time:{from:Zd,to:el},url:Xd})}}}else if(P(Ze)){const Dt=parseInt(($e=Rt.getAttribute("duration"))!==null&&$e!==void 0?$e:"",10)/fi*1e3,Si=Math.ceil(Ze/Dt);let qt=0;for(let gi=1;gi<Si;gi++){const bi=Br(pi,Object.assign(Object.assign({},hi),{segmentNumber:gi.toString(10),segmentTime:qt.toString(10)}));mi.push({time:{from:qt,to:qt+Dt},url:bi}),qt+=Dt}}Qs={type:Me.TEMPLATE,baseUrl:an,initUrl:Xs,segments:mi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Gt||!Et)continue;const Js={video:we.VIDEO,audio:we.AUDIO,text:we.TEXT}[Gt];Js&&ot[Js].push({id:Wd,kind:Js,segmentReference:Qs,profiles:Jd,duration:Ze,bitrate:sn,mime:Et,codecs:ji,width:Ws,height:tn,fps:Yd,quality:qd})}}return{duration:Ze,container:Fd,representations:ot}},uy=["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 dy=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ne,this.state$=new ce(Be.NONE),this.currentVideoRepresentation$=new T(void 0),this.error$=new L,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new xt,this.initManifest=ze(this.destroyController.signal,function(t,s){return We(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Be.MANIFEST_READY);const r=yield yield V(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield V(void 0);let a;try{a=oy(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield V(void 0);const n=({kind:o,mime:d,codecs:u})=>{var l,c,h;return Boolean(((l=t.canPlayType)===null||l===void 0?void 0:l.call(t,d))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${d}; codecs="${u}"`))||o===we.TEXT)};this.manifest=Object.assign(Object.assign({},a),{representations:Ui(Object.entries(a.representations).map(([o,d])=>[o,d.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(Be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=ze(this.destroyController.signal,function(t,s){return We(this,arguments,function*(){R(this.manifest),R(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 xo(we.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],P(s)&&(this.audioBufferManager=new xo(we.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=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(H(this.forceEnded$,rt({allBuffersFull:a,someBufferEnded:n}).pipe(ie(({allBuffersFull:o,someBufferEnded:d})=>o&&d))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield V(new Promise(o=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",o)}))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(s)?yield yield V(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield V(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=il(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new yb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(Be.RUNNING),this.subscription.add(H(...uy.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ya(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return de(this,void 0,void 0,function*(){const s={[we.VIDEO]:this.videoBufferManager,[we.AUDIO]:this.audioBufferManager,[we.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;R(this.element),R(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=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),ya(this.element.buffered,d)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(d),(o=this.audioBufferManager)===null||o===void 0||o.maintain(d),this.element.currentTime=d/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(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const 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 ly=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Gi(a):void 0)!==null&&n!==void 0?n:Ft({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},cy=({id:i,bitrate:e})=>({id:i,bitrate:e}),hy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),fy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ut(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ut(i,-1)};class py{constructor(e){this.subscription=new ne,this.videoState=new ce(he.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new nt,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ng,this.textTracks=[],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===z.Requested&&(r==null?void 0:r.to)!==p.PAUSED&&t!==he.STOPPED&&s!==p.STOPPED&&this.seek(a.position,a.forcePrecise),s===p.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(t){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:s===p.PAUSED?(this.videoState.setState(he.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case he.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case he.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}}},this.params=e,this.video=gt(e.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(Ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new dy({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=yt(this.video),r=u=>{e.error$.next({id:"DashVKProvider",category:D.WTF,message:"DashVKProvider internal logic error",thrown:u})},a=(u,l)=>this.subscription.add(u.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(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(ie(P),Te()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Vt(this.video,t.isLooped,r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_t(this.video,t.playbackRate,s.playbackRateState$,r)),a(ks(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),I(t.playbackState,p.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var l;if(u===Be.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((b,v)=>v.bitrate-b.bitrate),f=Array.from(c.video).sort((b,v)=>v.bitrate-b.bitrate),m=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(const b of h){const v=cy(b);v&&this.audioTracks.push({track:v,representation:b})}for(const b of f){const v=ly(b);if(v){this.videoTracks.push({track:v,representation:b});const g=!this.params.tuning.isAudioDisabled&&fy(h,f,b);g&&this.audioRepresentations.set(b.id,g)}}for(const b of m){const v=hy(b);v&&this.textTracks.push({track:v,representation:b})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const S=this.selectVideoRepresentation();R(S),this.player.initRepresentations(S.id,(l=this.audioRepresentations.get(S.id))===null||l===void 0?void 0:l.id)}else u===Be.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=u=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),l=this.player.state$.getTransition();if(u!==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(we.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(we.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Se(),_(u=>{var l;return u&&((l=this.videoTracks.find(({representation:{id:c}})=>c===u))===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:u})=>u===p.READY),Se());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const d=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:v}})=>v===d))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=Lt(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(u&&!o&&(s=(t=this.audioRepresentations.get(u.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),S=Hi(this.videoTracks.map(({track:v})=>v),{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}),b=o?S!=null?S:u:u!=null?u:S;return b&&((n=this.videoTracks.find(({track:v})=>v===b))===null||n===void 0?void 0:n.representation)}prepare(){return de(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.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const vy=5e3,tt={};var X;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const Ai=(i,e)=>new Cs(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class my{constructor(e){this.subscription=new ne,this.videoState=new ce(X.INITIALIZING),this.textTracksManager=new nt,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!==X.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:F(t)}break;case p.READY:switch(t){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:F(t)}break;case p.PLAYING:switch(t){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:F(t)}break;case p.PAUSED:switch(t){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case X.PLAYING:this.pause();break;default:F(t)}break;default:F(s)}},this.video=gt(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(Ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),vy);Gs(import("hls.js").then(r=>{e||(tt.Hls=r.default,tt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){R(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=yt(this.video),a=(u,l)=>this.subscription.add(u.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$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Vt(this.video,e.isLooped,s)),this.subscription.add(St(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_t(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(Ai(this.hls,tt.Events.ERROR).subscribe(u=>{var l;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:D.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(l=u.err)===null||l===void 0?void 0:l.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),I(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),I(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),a(Ai(this.hls,tt.Events.MANIFEST_PARSED).pipe(_(({levels:u})=>u.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:S,height:b}=c,v=(f=Gi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Ft({width:S,height:b});if(!v)return l;const g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,E={id:m.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:g};return this.trackLevels.set(m,{track:E,level:c}),l.push(E),l},[]))),t.availableVideoTracks$),a(Ai(this.hls,tt.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const l=[];for(const c of u.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,S="internal",b=h.includes("auto");l.push({id:h,url:f,language:m,type:S,isAuto:b})}e.internalTextTracks.startTransitionTo(l)}}),a(Ai(this.hls,tt.Events.LEVEL_LOADING).pipe(_(({url:u})=>Ie(u))),t.hostname$),this.subscription.add(Qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const n=u=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===u))===null||l===void 0?void 0:l.track},o=Ai(this.hls,tt.Events.LEVEL_SWITCHED).pipe(_(({level:u})=>n(this.hls.levels[u])));o.pipe(ie(P)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Qe(e.videoTrack,()=>{var u;return(u=n(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var l;if(te(u))return;const c=(l=this.trackLevels.get(u))===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(_(u=>u==null?void 0:u.id)),onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return de(this,void 0,void 0,function*(){this.videoState.startTransitionTo(X.PLAYING),(yield Pt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:t})))||(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(X.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(X.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const Ho="X-Playback-Duration";var Go=i=>de(void 0,void 0,void 0,function*(){const e=yield ai(i,{method:"HEAD"});return e.headers.has(Ho)?parseInt(e.headers.get(Ho),10):void 0});const Sy=i=>{let e=null;if(i.QUALITY&&(e=Gi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ft({width:t,height:s})}return e!=null?e:null},Od=(i,e=i)=>de(void 0,void 0,void 0,function*(){var t;const a=(yield(yield ai(i)).text()).split(`
|
|
8
|
-
`),n=[];for(let o=0;o<a.length;o++){const u=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const l=Ui(u[1].split(",").map(v=>v.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Sy(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 S;if(l.RESOLUTION){const[v,g]=l.RESOLUTION.split("x").map(E=>parseInt(E,10));v&&g&&(S={width:v,height:g})}const b=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:b,bandwidth:f,size:S,fps:m})}return n});var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(se||(se={}));class gy{constructor(e){var t;this.subscription=new ne,this.videoState=new ce(se.STOPPED),this.textTracksManager=new nt,this.manifests$=new T([]),this.liveOffset=new za,this.manifestStartTime$=new T(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o||d){const c=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested){this.videoState.startTransitionTo(se.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case se.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return F(r)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Od(ri(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.maxSeekBackTime$=new T((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",d=this.manifests$.getValue();if(!d)return;const u=a?"master":o;return a&&!n&&r.startTransitionTo("master"),d.find(l=>l.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(St(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(_t(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),I(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(Se(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&P(u.to)){const c=u.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(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===se.CHANGING_MANIFEST&&this.videoState.setState(d.to),o&&o.state===z.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,d,u;const l=(u=(d=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||d===void 0?void 0:d.call(o))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(l||void 0)},s)),this.subscription.add(rt({startTime:this.manifestStartTime$.pipe(ie(P)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),s)),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:h})=>({id:d,quality:u,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,xe(["init"])).pipe(Ue(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(te(e))return;const t=ri(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Go(t).then(s=>{var r;if(!te(s))this.maxSeekBackTime$.next(s);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(te(a)||!isFinite(a))try{ai(t).then(n=>n.text()).then(n=>{var o;const d=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(d){const u=new URL(d,t).toString();Go(u).then(l=>{te(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ue;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ue||(ue={}));class by{constructor(e){this.subscription=new ne,this.videoState=new ce(ue.STOPPED),this.textTracksManager=new nt,this.manifests$=new T([]),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===p.STOPPED){s!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ue.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(ue.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),u.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&u.state===z.Requested&&this.seek(u.position),s){case ue.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ue.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ue.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ue.CHANGING_MANIFEST:break;default:return F(s)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),Od(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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",d=this.manifests$.getValue();if(!d)return;const u=a?"master":o;return a&&!n&&r.startTransitionTo("master"),d.find(l=>l.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Vt(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(_t(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),I(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ue.READY&&this.videoState.setState(ue.READY),this.videoState.getState()===ue.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&P(u.to)){const c=u.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(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===ue.CHANGING_MANIFEST&&this.videoState.setState(d.to),o.state===z.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:h})=>({id:d,quality:u,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();te(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var fe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(fe||(fe={}));class yy{constructor(e){this.subscription=new ne,this.videoState=new ce(fe.STOPPED),this.trackUrls={},this.textTracksManager=new nt,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(fe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(n){const{currentTime:d}=this.video;this.prepare(),o.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==p.PAUSED&&o.state===z.Requested&&this.seek(o.position),t){case fe.READY:s===p.READY?I(this.params.desiredState.playbackState,p.READY):s===p.PAUSED?(this.videoState.setState(fe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case fe.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}},this.params=e,this.video=gt(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:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Vt(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(_t(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),I(t.playbackState,p.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 d=this.params.desiredState.videoTrack.getTransition();d&&P(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===fe.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}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();R(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];R(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=ni(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ie(r))}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const qo=["stun:videostun.mycdn.me:80"],Ty=1e3,Ey=3,Mr=()=>null;class $y{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 de(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 de(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:qo}]};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 de(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 de(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:D.WTF,message:e.message})}onPeerConnectionStream(e){return de(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 de(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),Ty)}normalizeOptions(e={}){const t={stunServerList:qo,maxRetryNumber:Ey,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(re||(re={}));class Ay{constructor(e){this.videoState=new ce(re.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case re.READY:s===p.PAUSED?(this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}},this.subscription=new ne,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=gt(e.container),this.liveStreamClient=new $y(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(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=yt(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)===re.READY&&this.videoState.setState(re.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(St(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case re.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case re.READY:break;case re.PAUSED:t.playbackState.setState(p.PAUSED);break;case re.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return F(n.to)}},s)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xe(["init"])).pipe(Ue(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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ae.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(re.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Yo{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 wy=()=>{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,qr,ls,Yr,cs,jr,hs,zr,fs,Wr,ps,Qr,vs,Jr;const Ld=wy(),At=document.createElement("video"),_y='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Py='video/mp4; codecs="hev1.1.6.L93.B0"',xd='video/webm; codecs="vp09.00.10.08"',Nd='video/webm; codecs="av01.0.00M.08"',ky='audio/mp4; codecs="mp4a.40.2"',Ry='audio/webm; codecs="opus"',Ye={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=At.canPlayType)===null||Vr===void 0?void 0:Vr.call(At,"application/x-mpegurl"))||((Hr=At.canPlayType)===null||Hr===void 0?void 0:Hr.call(At,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},Oe={mp4:Boolean((Gr=At.canPlayType)===null||Gr===void 0?void 0:Gr.call(At,"video/mp4")),webm:Boolean((qr=At.canPlayType)===null||qr===void 0?void 0:qr.call(At,"video/webm")),cmaf:!0},st={h264:Boolean((Yr=(ls=window.MediaSource)===null||ls===void 0?void 0:ls.isTypeSupported)===null||Yr===void 0?void 0:Yr.call(ls,_y)),h265:Boolean((jr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||jr===void 0?void 0:jr.call(cs,Py)),vp9:Boolean((zr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||zr===void 0?void 0:zr.call(hs,xd)),av1:Boolean((Wr=(fs=window.MediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||Wr===void 0?void 0:Wr.call(fs,Nd)),aac:Boolean((Qr=(ps=window.MediaSource)===null||ps===void 0?void 0:ps.isTypeSupported)===null||Qr===void 0?void 0:Qr.call(ps,ky)),opus:Boolean((Jr=(vs=window.MediaSource)===null||vs===void 0?void 0:vs.isTypeSupported)===null||Jr===void 0?void 0:Jr.call(vs,Ry))},Jt=(st.h264||st.h265)&&st.aac;var dt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(dt||(dt={}));let Ot;const Iy=()=>de(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Nd})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:xd})}))]);Ot={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{Iy()}catch(i){console.error(i)}const Ys=Ye.hls&&Oe.mp4,Dy=()=>Object.keys(st).filter(i=>st[i]),Cy=(i,e=!1)=>i.filter(t=>{switch(t){case y.DASH:return Ye.mse&&Oe.mp4&&Jt;case y.DASH_SEP:return Ye.mse&&Oe.mp4&&Jt;case y.DASH_WEBM:return Ye.mse&&Oe.webm&&st.vp9&&st.opus;case y.DASH_WEBM_AV1:return Ye.mse&&Oe.webm&&st.av1&&st.opus;case y.DASH_LIVE:return Ye.mse&&Oe.mp4&&Jt;case y.DASH_LIVE_CMAF:return Ye.mse&&Oe.mp4&&Jt&&Oe.cmaf;case y.DASH_ONDEMAND:return Ye.mse&&Oe.mp4&&Jt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return Ys||e&&Ye.mse&&Oe.mp4&&Jt;case y.MPEG:return Oe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ye.webrtc&&Ye.ws&&st.h264&&(Oe.mp4||Oe.webm);default:return F(t)}}),Kr=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case dt.VP9:return[e,t];case dt.AV1:return[t,e];case dt.NONE:return[];case dt.SMOOTH:return Ot?Ot[t].smooth?[t,e]:Ot[e].smooth?[e,t]:[t,e]:[e,t];case dt.POWER_EFFICIENT:return Ot?Ot[t].powerEfficient?[t,e]:Ot[e].powerEfficient?[e,t]:[t,e]:[e,t];default:F(i)}return[e,t]},Oy=(i=dt.VP9)=>Ld?[y.MPEG,...Kr(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:Ys?[...Kr(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...Kr(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],Ly=()=>Ld?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF]:Ys?[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],jo=i=>i?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var xy=i=>new Cs(e=>{const t=new ne,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:u,to:l})=>`${u}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(_(({type:u})=>u!==void 0)),n=new L;let o=0,d="unknown";return t.add(s.subscribe(u=>{o&&window.clearTimeout(o),d=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),d="provider change",o=0})),t.add(a.subscribe(u=>{o&&window.clearTimeout(o),u&&(o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const zo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Ny={cacheDuration:12e4},By={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},My={maxPausedTime:3e4},Wo={maxPausedTime:3e4};class Uy{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new T(void 0),liveTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0)},this.subscription=new ne,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Cy([...Ly(),...Oy(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(o=>P(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.screenFormatsIterator=new Yo(a);const n=[...jo(!0),...jo(!1)];this.chromecastFormatsIterator=new Yo(n.filter(o=>P(e.sources[o])))}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(te(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,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!==z.None;this.params.desiredState.seekState.setState({state:z.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 _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return F(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 R(o),new ab(Object.assign(Object.assign({},n),{source:o,config:Ny}))}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Ro(Object.assign(Object.assign({},n),{source:o,format:e,config:Wo})):new py(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Ro(Object.assign(Object.assign({},n),{source:o,format:e,config:Wo}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),Ys||!this.params.tuning.useHlsJs?new by(Object.assign(Object.assign({},n),{source:o})):new my(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new gy(Object.assign(Object.assign({},n),{source:o,config:My}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new yy(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new eb(Object.assign(Object.assign({},n),{source:o,config:By}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new Ay({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 F(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 R(o),new ag({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()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return F(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return F(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return F(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 Ui(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ne;let t=!1,s=0;return e.add(H(this.providerOutput.error$,xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:zo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(r=>({id:`ProviderHangup:${r}`,category:D.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ie(({to:a})=>a===p.PLAYING),Te()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(_e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===D.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<zo.providerErrorLimit;o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:_e.SCREEN)}})),e}}const Ta=(i,e,t)=>t*e+(1-t)*i,Bd=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Fy=(i,e,t,s)=>{let r=0,a=t;const n=Bd(i,e),o=e<s?e:s;for(let d=0;d<o;d++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class Md{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 T(e.initial),this.debounced$=new T(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new it(`raw_${s}`),this.smoothedSeries$=new it(`smoothed_${s}`),this.reportedSeries$=new it(`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)&&(te(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 Vy extends Md{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ta(this.slow,e,this.params.emaAlphaSlow),this.fast=Ta(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Hy extends Md{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Bd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ta(this.emaSmoothed,e,this.params.emaAlpha);const s=Fy(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 Vy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Hy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Gy=5e3,Jo="one_video_throughput",Ko="one_video_rtt",ft=window.navigator.connection,Xo=()=>{const i=ft==null?void 0:ft.downlink;if(P(i)&&i!==10)return i*1e3},Zo=()=>{const i=ft==null?void 0:ft.rtt;if(P(i)&&i!==3e3)return i},eu=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Ri{constructor(e){var t,s;this.subscription=new ne,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ri.load(Jo)||(e.useBrowserEstimation?Xo():void 0)||Gy,a=(s=(t=Ri.load(Ko))!==null&&t!==void 0?t:e.useBrowserEstimation?Zo():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(eu(r,a,e.rttPenaltyRequestSize)),this.throughput=Qo.getSmoothedValue(r,-1,e),this.rtt=Qo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const d=Xo();d&&this.throughput.next(d);const u=Zo();P(u)&&this.rtt.next(u)};ft&&"onchange"in ft&&this.subscription.add(M(ft,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Zs.set(Jo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Zs.set(Ko,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(rt({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>eu(n,o,e.rttPenaltyRequestSize)),ie(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 ne;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(M(e,"progress").pipe(Te()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(M(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),d=n-t,u=o-s;this.addRawSpeed(d,u,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=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:l})=>de(this,void 0,void 0,function*(){u?(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(d,o))});this.concurrentDownloads.add(e),t==null||t.read().then(d,o)}addRawSpeed(e,t,s=1){if(Ri.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=Zs.get(e);if(P(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const tu={configName:["core"],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,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:dt.VP9,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}},qy=i=>{const e={};for(const t of Object.keys(tu)){const s=tu[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?t==="configName"?e[t]=[...r,...s]: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 Yy=({seekState:i,position$:e})=>H(i.stateChangeEnded$.pipe(_(({to:t})=>{var s;return t.state===z.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ie(P)),e.pipe(ie(()=>i.getState().state===z.None))),jy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return R(e,`Wrong container or containerId {${i.container}}`),e};class Xy{constructor(e={configName:[]}){if(this.subscription=new ne,this.logger=new sl,this.isPlaybackStarted=!1,this.desiredState={playbackState:new ce(p.STOPPED),seekState:new ce({state:z.None}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),atLiveEdge$:new T(void 0),liveTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T($t.NONE),chromecastState$:new T(Ae.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0)},this.events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Og},this.initLogs(),this.tuning=qy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ul({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ri(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 d=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),u=`Player.${String(s)}`,l=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:D.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=jy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Uy({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(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==p.PLAYING&&e.startTransitionTo(p.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.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()===Ae.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()===Ae.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){R(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const 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;R(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(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(te(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===z.None?void 0:t.position;return P(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(H(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(ie(({from:e})=>e===p.STOPPED),Te()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:z.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),Se()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,d)=>_s(o)?1:_s(d)?-1:bs(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const d of n)d.fps&&(o[d.quality]=d.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(Se()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Se()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Se()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(rt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(_(({isLive:n,position:o})=>n&&o>-rl),Se()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),Se()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),Se()).subscribe(this.info.volume$)).add(Yy({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(si(!0)),e.providerOutput.seekedEvent$.pipe(si(!1))).pipe(Se()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:D.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Te(),_(n=>n!=null?n:pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Te(),_(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Te(),_(()=>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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new T(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ie(({to:n})=>n===p.PLAYING),Te()).subscribe(()=>s.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,s).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),Se());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(d=n==null?void 0:n.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let l;u===Ae.CONNECTED?l=$t.SECOND_SCREEN:d?n?l=$t.PIP:o?l=$t.FULLSCREEN:l=$t.INLINE:l=$t.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}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 ne;this.subscription.add(t),this.subscription.add(e.current$.pipe(Se((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ie(s=>s.length>0),Te()).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=Hi(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(H(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),Cg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Dg(s)),this.providerContainer.current$.subscribe(({type:s})=>os("provider",s)),t.duration$.subscribe(s=>os("duration",s)),t.availableVideoTracks$.pipe(ie(s=>!!s.length),Te()).subscribe(s=>os("tracks",s)),this.events.fatalError$.subscribe(new it("fatalError")),this.events.managedError$.subscribe(new it("managedError")),t.position$.subscribe(new it("position")),t.currentVideoTrack$.pipe(_(s=>s==null?void 0:s.quality)).subscribe(new it("quality")),this.info.currentBuffer$.subscribe(new it("buffer")),t.isBuffering$.subscribe(new it("isBuffering"))].forEach(s=>this.subscription.add(s)),os("codecs",Dy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>de(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})});this.subscription.add(H(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const Zy=`@vkontakte/videoplayer-core@${nl}`;export{Ae as ChromecastState,Ii as HttpConnectionType,iT as Observable,p as PlaybackState,Xy as Player,Zy as SDK_VERSION,sT as Subject,rT as Subscription,$t as Surface,nl as VERSION,aT as ValueSubject,y as VideoFormat,ae as VideoQuality};
|
|
6
|
+
import{ValueSubject as T,Subject as L,Subscription as ae,isNonNullable as k,ErrorCategory as D,isNullable as te,fromEvent as M,assertNever as F,merge as H,tap as on,map as _,observableFrom as Oe,filterChanged as ve,assertNonNullable as R,debounce as Be,getHighestQuality as sl,timeout as rl,getCurrentBrowser as Is,CurrentClientBrowser as Ta,CurrentClientDevice as su,combine as it,once as ye,mapTo as ii,filter as ie,now as fe,videoSizeToQuality as Nt,isInvariantQuality as bs,isHigher as ps,isLower as Ks,isLowerOrEqual as al,isHigherOrEqual as nl,Observable as Ds,VideoQuality as qe,videoQualityToHeight as ol,abortable as je,getExponentialDelay as un,interval as ul,safeStorage as Xs,Logger as dl,ACTIVE_LIVE_VALID_DELAY as ll}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as tT,Subject as iT,Subscription as sT,ValueSubject as rT,VideoQuality as aT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import cl from"lodash/debounce.js";const hl="2.0.88";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));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_AV1="DASH_WEBM_AV1",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 we;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(we||(we={}));var $e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})($e||($e={}));var Pi;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(Pi||(Pi={}));var z;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(z||(z={}));var Tt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(Tt||(Tt={}));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{u(s.next(l))}catch(c){n(c)}}function d(l){try{u(s.throw(l))}catch(c){n(c)}}function u(l){l.done?a(l.value):r(l.value).then(o,d)}u((s=s.apply(i,e||[])).next())})}function V(i){return this instanceof V?(this.v=i,this):new V(i)}function ze(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,g){a.push([h,f,m,g])>1||o(h,f)})})}function o(h,f){try{d(s[h](f))}catch(m){c(a[0][3],m)}}function d(h){h.value instanceof V?Promise.resolve(h.value.v).then(u,l):c(a[0][2],h)}function u(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 fl=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 pl{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T($e.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new T($e.NOT_AVAILABLE),this.subscription=new ae,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=k((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||fl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var 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(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(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(M(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 F(r.sessionState)}})).add(H(M(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(on(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),Oe([s.getCastState()])).pipe(ve(),_(vl),on(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===$e.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const d=s.getCurrentSession();R(d);const u=d.getCastDevice(),l=(a=d.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===$e.CONNECTED?k(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:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const vl=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 F(i)}};var dn=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Me=function(i){try{return!!i()}catch(e){return!0}},ml=Me,Cs=!ml(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),ru=Cs,au=Function.prototype,Kr=au.call,Sl=ru&&au.bind.bind(Kr,Kr),Ue=ru?Sl:function(i){return function(){return Kr.apply(i,arguments)}},nu=Ue,gl=nu({}.toString),bl=nu("".slice),Di=function(i){return bl(gl(i),8,-1)},yl=Ue,Tl=Me,El=Di,Zs=Object,$l=yl("".split),Al=Tl(function(){return!Zs("z").propertyIsEnumerable(0)})?function(i){return El(i)=="String"?$l(i,""):Zs(i)}:Zs,Ci=function(i){return i==null},wl=Ci,_l=TypeError,Ea=function(i){if(wl(i))throw _l("Can't call method on "+i);return i},kl=Al,Pl=Ea,Oi=function(i){return kl(Pl(i))},Rl=function(){},oi={},ji=function(i){return i&&i.Math==Math&&i},ke=ji(typeof globalThis=="object"&&globalThis)||ji(typeof window=="object"&&window)||ji(typeof self=="object"&&self)||ji(typeof dn=="object"&&dn)||function(){return this}()||Function("return this")(),Xr=typeof document=="object"&&document.all,Il=typeof Xr=="undefined"&&Xr!==void 0,ou={all:Xr,IS_HTMLDDA:Il},uu=ou,Dl=uu.all,Te=uu.IS_HTMLDDA?function(i){return typeof i=="function"||i===Dl}:function(i){return typeof i=="function"},Cl=ke,Ol=Te,ln=Cl.WeakMap,Ll=Ol(ln)&&/native code/.test(String(ln)),cn=Te,du=ou,xl=du.all,ht=du.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:cn(i)||i===xl}:function(i){return typeof i=="object"?i!==null:cn(i)},Nl=Me,ft=!Nl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Bt={},Bl=ke,hn=ht,Zr=Bl.document,Ml=hn(Zr)&&hn(Zr.createElement),$a=function(i){return Ml?Zr.createElement(i):{}},Ul=ft,Fl=Me,Vl=$a,lu=!Ul&&!Fl(function(){return Object.defineProperty(Vl("div"),"a",{get:function(){return 7}}).a!=7}),Hl=ft,Gl=Me,cu=Hl&&Gl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ql=ht,Yl=String,jl=TypeError,pt=function(i){if(ql(i))return i;throw jl(Yl(i)+" is not an object")},zl=Cs,zi=Function.prototype.call,Le=zl?zi.bind(zi):function(){return zi.apply(zi,arguments)},Aa={},er=Aa,tr=ke,Wl=Te,fn=function(i){return Wl(i)?i:void 0},Mt=function(i,e){return arguments.length<2?fn(er[i])||fn(tr[i]):er[i]&&er[i][e]||tr[i]&&tr[i][e]},Ql=Ue,Os=Ql({}.isPrototypeOf),Ls=typeof navigator!="undefined"&&String(navigator.userAgent)||"",hu=ke,ir=Ls,pn=hu.process,vn=hu.Deno,mn=pn&&pn.versions||vn&&vn.version,Sn=mn&&mn.v8,Ye,ys;Sn&&(Ye=Sn.split("."),ys=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!ys&&ir&&(Ye=ir.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=ir.match(/Chrome\/(\d+)/),Ye&&(ys=+Ye[1])));var fu=ys,gn=fu,Jl=Me,pu=!!Object.getOwnPropertySymbols&&!Jl(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&gn&&gn<41}),Kl=pu,vu=Kl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Xl=Mt,Zl=Te,ec=Os,tc=vu,ic=Object,mu=tc?function(i){return typeof i=="symbol"}:function(i){var e=Xl("Symbol");return Zl(e)&&ec(e.prototype,ic(i))},sc=String,xs=function(i){try{return sc(i)}catch(e){return"Object"}},rc=Te,ac=xs,nc=TypeError,Ut=function(i){if(rc(i))return i;throw nc(ac(i)+" is not a function")},oc=Ut,uc=Ci,Ns=function(i,e){var t=i[e];return uc(t)?void 0:oc(t)},sr=Le,rr=Te,ar=ht,dc=TypeError,lc=function(i,e){var t,s;if(e==="string"&&rr(t=i.toString)&&!ar(s=sr(t,i))||rr(t=i.valueOf)&&!ar(s=sr(t,i))||e!=="string"&&rr(t=i.toString)&&!ar(s=sr(t,i)))return s;throw dc("Can't convert object to primitive value")},Ts={},cc={get exports(){return Ts},set exports(i){Ts=i}},Su=!0,bn=ke,hc=Object.defineProperty,fc=function(i,e){try{hc(bn,i,{value:e,configurable:!0,writable:!0})}catch(t){bn[i]=e}return e},pc=ke,vc=fc,yn="__core-js_shared__",mc=pc[yn]||vc(yn,{}),wa=mc,Tn=wa;(cc.exports=function(i,e){return Tn[i]||(Tn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Sc=Ea,gc=Object,Bs=function(i){return gc(Sc(i))},bc=Ue,yc=Bs,Tc=bc({}.hasOwnProperty),st=Object.hasOwn||function(e,t){return Tc(yc(e),t)},Ec=Ue,$c=0,Ac=Math.random(),wc=Ec(1 .toString),gu=function(i){return"Symbol("+(i===void 0?"":i)+")_"+wc(++$c+Ac,36)},_c=ke,kc=Ts,En=st,Pc=gu,Rc=pu,Ic=vu,Jt=_c.Symbol,nr=kc("wks"),Dc=Ic?Jt.for||Jt:Jt&&Jt.withoutSetter||Pc,Pe=function(i){return En(nr,i)||(nr[i]=Rc&&En(Jt,i)?Jt[i]:Dc("Symbol."+i)),nr[i]},Cc=Le,$n=ht,An=mu,Oc=Ns,Lc=lc,xc=Pe,Nc=TypeError,Bc=xc("toPrimitive"),Mc=function(i,e){if(!$n(i)||An(i))return i;var t=Oc(i,Bc),s;if(t){if(e===void 0&&(e="default"),s=Cc(t,i,e),!$n(s)||An(s))return s;throw Nc("Can't convert object to primitive value")}return e===void 0&&(e="number"),Lc(i,e)},Uc=Mc,Fc=mu,_a=function(i){var e=Uc(i,"string");return Fc(e)?e:e+""},Vc=ft,Hc=lu,Gc=cu,Wi=pt,wn=_a,qc=TypeError,or=Object.defineProperty,Yc=Object.getOwnPropertyDescriptor,ur="enumerable",dr="configurable",lr="writable";Bt.f=Vc?Gc?function(e,t,s){if(Wi(e),t=wn(t),Wi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&lr in s&&!s[lr]){var r=Yc(e,t);r&&r[lr]&&(e[t]=s.value,s={configurable:dr in s?s[dr]:r[dr],enumerable:ur in s?s[ur]:r[ur],writable:!1})}return or(e,t,s)}:or:function(e,t,s){if(Wi(e),t=wn(t),Wi(s),Hc)try{return or(e,t,s)}catch(r){}if("get"in s||"set"in s)throw qc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ms=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},jc=ft,zc=Bt,Wc=Ms,Li=jc?function(i,e,t){return zc.f(i,e,Wc(1,t))}:function(i,e,t){return i[e]=t,i},Qc=Ts,Jc=gu,_n=Qc("keys"),ka=function(i){return _n[i]||(_n[i]=Jc(i))},Pa={},Kc=Ll,bu=ke,Xc=ht,Zc=Li,cr=st,hr=wa,eh=ka,th=Pa,kn="Object already initialized",ea=bu.TypeError,ih=bu.WeakMap,Es,Ri,$s,sh=function(i){return $s(i)?Ri(i):Es(i,{})},rh=function(i){return function(e){var t;if(!Xc(e)||(t=Ri(e)).type!==i)throw ea("Incompatible receiver, "+i+" required");return t}};if(Kc||hr.state){var Xe=hr.state||(hr.state=new ih);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Es=function(i,e){if(Xe.has(i))throw ea(kn);return e.facade=i,Xe.set(i,e),e},Ri=function(i){return Xe.get(i)||{}},$s=function(i){return Xe.has(i)}}else{var qt=eh("state");th[qt]=!0,Es=function(i,e){if(cr(i,qt))throw ea(kn);return e.facade=i,Zc(i,qt,e),e},Ri=function(i){return cr(i,qt)?i[qt]:{}},$s=function(i){return cr(i,qt)}}var yu={set:Es,get:Ri,has:$s,enforce:sh,getterFor:rh},ah=Cs,Tu=Function.prototype,Pn=Tu.apply,Rn=Tu.call,Eu=typeof Reflect=="object"&&Reflect.apply||(ah?Rn.bind(Pn):function(){return Rn.apply(Pn,arguments)}),nh=Di,oh=Ue,$u=function(i){if(nh(i)==="Function")return oh(i)},Ra={},Au={},wu={}.propertyIsEnumerable,_u=Object.getOwnPropertyDescriptor,uh=_u&&!wu.call({1:2},1);Au.f=uh?function(e){var t=_u(this,e);return!!t&&t.enumerable}:wu;var dh=ft,lh=Le,ch=Au,hh=Ms,fh=Oi,ph=_a,vh=st,mh=lu,In=Object.getOwnPropertyDescriptor;Ra.f=dh?In:function(e,t){if(e=fh(e),t=ph(t),mh)try{return In(e,t)}catch(s){}if(vh(e,t))return hh(!lh(ch.f,e,t),e[t])};var Sh=Me,gh=Te,bh=/#|\.prototype\./,xi=function(i,e){var t=Th[yh(i)];return t==$h?!0:t==Eh?!1:gh(e)?Sh(e):!!e},yh=xi.normalize=function(i){return String(i).replace(bh,".").toLowerCase()},Th=xi.data={},Eh=xi.NATIVE="N",$h=xi.POLYFILL="P",ku=xi,Dn=$u,Ah=Ut,wh=Cs,_h=Dn(Dn.bind),Us=function(i,e){return Ah(i),e===void 0?i:wh?_h(i,e):function(){return i.apply(e,arguments)}},Qi=ke,kh=Eu,Ph=$u,Rh=Te,Ih=Ra.f,Dh=ku,Yt=Aa,Ch=Us,jt=Li,Cn=st,Oh=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 kh(i,this,arguments)};return e.prototype=i.prototype,e},Qe=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Qi:r?Qi[t]:(Qi[t]||{}).prototype,o=s?Yt:Yt[t]||jt(Yt,t,{})[t],d=o.prototype,u,l,c,h,f,m,g,b,v;for(h in e)u=Dh(s?h:t+(r?".":"#")+h,i.forced),l=!u&&n&&Cn(n,h),m=o[h],l&&(i.dontCallGetSet?(v=Ih(n,h),g=v&&v.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?b=Ch(f,Qi):i.wrap&&l?b=Oh(f):a&&Rh(f)?b=Ph(f):b=f,(i.sham||f&&f.sham||m&&m.sham)&&jt(b,"sham",!0),jt(o,h,b),a&&(c=t+"Prototype",Cn(Yt,c)||jt(Yt,c,{}),jt(Yt[c],h,f),i.real&&d&&(u||!d[h])&&jt(d,h,f)))},ta=ft,Lh=st,Pu=Function.prototype,xh=ta&&Object.getOwnPropertyDescriptor,Ia=Lh(Pu,"name"),Nh=Ia&&function(){}.name==="something",Bh=Ia&&(!ta||ta&&xh(Pu,"name").configurable),Mh={EXISTS:Ia,PROPER:Nh,CONFIGURABLE:Bh},Ru={},Uh=Math.ceil,Fh=Math.floor,Vh=Math.trunc||function(e){var t=+e;return(t>0?Fh:Uh)(t)},Hh=Vh,Da=function(i){var e=+i;return e!==e||e===0?0:Hh(e)},Gh=Da,qh=Math.max,Yh=Math.min,jh=function(i,e){var t=Gh(i);return t<0?qh(t+e,0):Yh(t,e)},zh=Da,Wh=Math.min,Qh=function(i){return i>0?Wh(zh(i),9007199254740991):0},Jh=Qh,Ca=function(i){return Jh(i.length)},Kh=Oi,Xh=jh,Zh=Ca,On=function(i){return function(e,t,s){var r=Kh(e),a=Zh(r),n=Xh(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}},ef={includes:On(!0),indexOf:On(!1)},tf=Ue,fr=st,sf=Oi,rf=ef.indexOf,af=Pa,Ln=tf([].push),nf=function(i,e){var t=sf(i),s=0,r=[],a;for(a in t)!fr(af,a)&&fr(t,a)&&Ln(r,a);for(;e.length>s;)fr(t,a=e[s++])&&(~rf(r,a)||Ln(r,a));return r},Iu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],of=nf,uf=Iu,df=Object.keys||function(e){return of(e,uf)},lf=ft,cf=cu,hf=Bt,ff=pt,pf=Oi,vf=df;Ru.f=lf&&!cf?Object.defineProperties:function(e,t){ff(e);for(var s=pf(t),r=vf(t),a=r.length,n=0,o;a>n;)hf.f(e,o=r[n++],s[o]);return e};var mf=Mt,Du=mf("document","documentElement"),Sf=pt,gf=Ru,xn=Iu,bf=Pa,yf=Du,Tf=$a,Ef=ka,Nn=">",Bn="<",ia="prototype",sa="script",Cu=Ef("IE_PROTO"),pr=function(){},Ou=function(i){return Bn+sa+Nn+i+Bn+"/"+sa+Nn},Mn=function(i){i.write(Ou("")),i.close();var e=i.parentWindow.Object;return i=null,e},$f=function(){var i=Tf("iframe"),e="java"+sa+":",t;return i.style.display="none",yf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ou("document.F=Object")),t.close(),t.F},Ji,vs=function(){try{Ji=new ActiveXObject("htmlfile")}catch(e){}vs=typeof document!="undefined"?document.domain&&Ji?Mn(Ji):$f():Mn(Ji);for(var i=xn.length;i--;)delete vs[ia][xn[i]];return vs()};bf[Cu]=!0;var Lu=Object.create||function(e,t){var s;return e!==null?(pr[ia]=Sf(e),s=new pr,pr[ia]=null,s[Cu]=e):s=vs(),t===void 0?s:gf.f(s,t)},Af=Me,wf=!Af(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),_f=st,kf=Te,Pf=Bs,Rf=ka,If=wf,Un=Rf("IE_PROTO"),ra=Object,Df=ra.prototype,xu=If?ra.getPrototypeOf:function(i){var e=Pf(i);if(_f(e,Un))return e[Un];var t=e.constructor;return kf(t)&&e instanceof t?t.prototype:e instanceof ra?Df:null},Cf=Li,Oa=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Cf(i,e,t),i},Of=Me,Lf=Te,xf=ht,Nf=Lu,Fn=xu,Bf=Oa,Mf=Pe,aa=Mf("iterator"),Nu=!1,lt,vr,mr;[].keys&&(mr=[].keys(),"next"in mr?(vr=Fn(Fn(mr)),vr!==Object.prototype&&(lt=vr)):Nu=!0);var Uf=!xf(lt)||Of(function(){var i={};return lt[aa].call(i)!==i});Uf?lt={}:lt=Nf(lt);Lf(lt[aa])||Bf(lt,aa,function(){return this});var Bu={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Nu},Ff=Pe,Vf=Ff("toStringTag"),Mu={};Mu[Vf]="z";var La=String(Mu)==="[object z]",Hf=La,Gf=Te,ms=Di,qf=Pe,Yf=qf("toStringTag"),jf=Object,zf=ms(function(){return arguments}())=="Arguments",Wf=function(i,e){try{return i[e]}catch(t){}},Ni=Hf?ms:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Wf(e=jf(i),Yf))=="string"?t:zf?ms(e):(s=ms(e))=="Object"&&Gf(e.callee)?"Arguments":s},Qf=La,Jf=Ni,Kf=Qf?{}.toString:function(){return"[object "+Jf(this)+"]"},Xf=La,Zf=Bt.f,ep=Li,tp=st,ip=Kf,sp=Pe,Vn=sp("toStringTag"),xa=function(i,e,t,s){if(i){var r=t?i:i.prototype;tp(r,Vn)||Zf(r,Vn,{configurable:!0,value:e}),s&&!Xf&&ep(r,"toString",ip)}},rp=Bu.IteratorPrototype,ap=Lu,np=Ms,op=xa,up=oi,dp=function(){return this},lp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=ap(rp,{next:np(+!s,t)}),op(i,r,!1,!0),up[r]=dp,i},cp=Qe,hp=Le,Uu=Mh,fp=lp,pp=xu,vp=xa,Hn=Oa,mp=Pe,Gn=oi,Fu=Bu,Sp=Uu.PROPER;Uu.CONFIGURABLE;Fu.IteratorPrototype;var Ki=Fu.BUGGY_SAFARI_ITERATORS,Sr=mp("iterator"),qn="keys",Xi="values",Yn="entries",gp=function(){return this},bp=function(i,e,t,s,r,a,n){fp(t,e,s);var o=function(v){if(v===r&&h)return h;if(!Ki&&v in l)return l[v];switch(v){case qn:return function(){return new t(this,v)};case Xi:return function(){return new t(this,v)};case Yn:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,l=i.prototype,c=l[Sr]||l["@@iterator"]||r&&l[r],h=!Ki&&c||o(r),f=e=="Array"&&l.entries||c,m,g,b;if(f&&(m=pp(f.call(new i)),m!==Object.prototype&&m.next&&(vp(m,d,!0,!0),Gn[d]=gp)),Sp&&r==Xi&&c&&c.name!==Xi&&(u=!0,h=function(){return hp(c,this)}),r)if(g={values:o(Xi),keys:a?h:o(qn),entries:o(Yn)},n)for(b in g)(Ki||u||!(b in l))&&Hn(l,b,g[b]);else cp({target:e,proto:!0,forced:Ki||u},g);return n&&l[Sr]!==h&&Hn(l,Sr,h,{name:r}),Gn[e]=h,g},yp=function(i,e){return{value:i,done:e}},Tp=Oi,Na=Rl,jn=oi,Vu=yu,Ep=Bt.f,$p=bp,Zi=yp,Ap=Su,wp=ft,Hu="Array Iterator",_p=Vu.set,kp=Vu.getterFor(Hu);$p(Array,"Array",function(i,e){_p(this,{type:Hu,target:Tp(i),index:0,kind:e})},function(){var i=kp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Zi(void 0,!0)):t=="keys"?Zi(s,!1):t=="values"?Zi(e[s],!1):Zi([s,e[s]],!1)},"values");var zn=jn.Arguments=jn.Array;Na();Na();Na();if(!Ap&&wp&&zn.name!=="values")try{Ep(zn,"name",{value:"values"})}catch(i){}var Pp=Pe,Rp=oi,Ip=Pp("iterator"),Dp=Array.prototype,Cp=function(i){return i!==void 0&&(Rp.Array===i||Dp[Ip]===i)},Op=Ni,Wn=Ns,Lp=Ci,xp=oi,Np=Pe,Bp=Np("iterator"),Gu=function(i){if(!Lp(i))return Wn(i,Bp)||Wn(i,"@@iterator")||xp[Op(i)]},Mp=Le,Up=Ut,Fp=pt,Vp=xs,Hp=Gu,Gp=TypeError,qp=function(i,e){var t=arguments.length<2?Hp(i):e;if(Up(t))return Fp(Mp(t,i));throw Gp(Vp(i)+" is not iterable")},Yp=Le,Qn=pt,jp=Ns,zp=function(i,e,t){var s,r;Qn(i);try{if(s=jp(i,"return"),!s){if(e==="throw")throw t;return t}s=Yp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Qn(s),t},Wp=Us,Qp=Le,Jp=pt,Kp=xs,Xp=Cp,Zp=Ca,Jn=Os,ev=qp,tv=Gu,Kn=zp,iv=TypeError,Ss=function(i,e){this.stopped=i,this.result=e},Xn=Ss.prototype,Ba=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),d=Wp(e,s),u,l,c,h,f,m,g,b=function(S){return u&&Kn(u,"normal",S),new Ss(!0,S)},v=function(S){return r?(Jp(S),o?d(S[0],S[1],b):d(S[0],S[1])):o?d(S,b):d(S)};if(a)u=i.iterator;else if(n)u=i;else{if(l=tv(i),!l)throw iv(Kp(i)+" is not iterable");if(Xp(l)){for(c=0,h=Zp(i);h>c;c++)if(f=v(i[c]),f&&Jn(Xn,f))return f;return new Ss(!1)}u=ev(i,l)}for(m=a?i.next:u.next;!(g=Qp(m,u)).done;){try{f=v(g.value)}catch(S){Kn(u,"throw",S)}if(typeof f=="object"&&f&&Jn(Xn,f))return f}return new Ss(!1)},sv=_a,rv=Bt,av=Ms,nv=function(i,e,t){var s=sv(e);s in i?rv.f(i,s,av(0,t)):i[s]=t},ov=Qe,uv=Ba,dv=nv;ov({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uv(e,function(s,r){dv(t,s,r)},{AS_ENTRIES:!0}),t}});var lv=Aa,cv=lv.Object.fromEntries,hv={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},fv=hv,pv=ke,vv=Ni,mv=Li,Zn=oi,Sv=Pe,eo=Sv("toStringTag");for(var gr in fv){var to=pv[gr],br=to&&to.prototype;br&&vv(br)!==eo&&mv(br,eo,gr),Zn[gr]=Zn.Array}var gv=cv,bv=gv,yv=bv,Tv=yv,Bi=Tv,Ev=Di,Fs=typeof process!="undefined"&&Ev(process)=="process",$v=Mt,Av=Bt,wv=Pe,_v=ft,io=wv("species"),kv=function(i){var e=$v(i),t=Av.f;_v&&e&&!e[io]&&t(e,io,{configurable:!0,get:function(){return this}})},Pv=Os,Rv=TypeError,Iv=function(i,e){if(Pv(e,i))return i;throw Rv("Incorrect invocation")},Dv=Ue,Cv=Te,na=wa,Ov=Dv(Function.toString);Cv(na.inspectSource)||(na.inspectSource=function(i){return Ov(i)});var qu=na.inspectSource,Lv=Ue,xv=Me,Yu=Te,Nv=Ni,Bv=Mt,Mv=qu,ju=function(){},Uv=[],zu=Bv("Reflect","construct"),Ma=/^\s*(?:class|function)\b/,Fv=Lv(Ma.exec),Vv=!Ma.exec(ju),bi=function(e){if(!Yu(e))return!1;try{return zu(ju,Uv,e),!0}catch(t){return!1}},Wu=function(e){if(!Yu(e))return!1;switch(Nv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Vv||!!Fv(Ma,Mv(e))}catch(t){return!0}};Wu.sham=!0;var Hv=!zu||xv(function(){var i;return bi(bi.call)||!bi(Object)||!bi(function(){i=!0})||i})?Wu:bi,Gv=Hv,qv=xs,Yv=TypeError,jv=function(i){if(Gv(i))return i;throw Yv(qv(i)+" is not a constructor")},so=pt,zv=jv,Wv=Ci,Qv=Pe,Jv=Qv("species"),Qu=function(i,e){var t=so(i).constructor,s;return t===void 0||Wv(s=so(t)[Jv])?e:zv(s)},Kv=Ue,Xv=Kv([].slice),Zv=TypeError,em=function(i,e){if(i<e)throw Zv("Not enough arguments");return i},tm=Ls,Ju=/(?:ipad|iphone|ipod).*applewebkit/i.test(tm),Ce=ke,im=Eu,sm=Us,ro=Te,rm=st,Ku=Me,ao=Du,am=Xv,no=$a,nm=em,om=Ju,um=Fs,oa=Ce.setImmediate,ua=Ce.clearImmediate,dm=Ce.process,yr=Ce.Dispatch,lm=Ce.Function,oo=Ce.MessageChannel,cm=Ce.String,Tr=0,Ai={},uo="onreadystatechange",Ii,Dt,Er,$r;Ku(function(){Ii=Ce.location});var Ua=function(i){if(rm(Ai,i)){var e=Ai[i];delete Ai[i],e()}},Ar=function(i){return function(){Ua(i)}},lo=function(i){Ua(i.data)},co=function(i){Ce.postMessage(cm(i),Ii.protocol+"//"+Ii.host)};(!oa||!ua)&&(oa=function(e){nm(arguments.length,1);var t=ro(e)?e:lm(e),s=am(arguments,1);return Ai[++Tr]=function(){im(t,void 0,s)},Dt(Tr),Tr},ua=function(e){delete Ai[e]},um?Dt=function(i){dm.nextTick(Ar(i))}:yr&&yr.now?Dt=function(i){yr.now(Ar(i))}:oo&&!om?(Er=new oo,$r=Er.port2,Er.port1.onmessage=lo,Dt=sm($r.postMessage,$r)):Ce.addEventListener&&ro(Ce.postMessage)&&!Ce.importScripts&&Ii&&Ii.protocol!=="file:"&&!Ku(co)?(Dt=co,Ce.addEventListener("message",lo,!1)):uo in no("script")?Dt=function(i){ao.appendChild(no("script"))[uo]=function(){ao.removeChild(this),Ua(i)}}:Dt=function(i){setTimeout(Ar(i),0)});var Xu={set:oa,clear:ua},Zu=function(){this.head=null,this.tail=null};Zu.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 ed=Zu,hm=Ls,fm=/ipad|iphone|ipod/i.test(hm)&&typeof Pebble!="undefined",pm=Ls,vm=/web0s(?!.*chrome)/i.test(pm),xt=ke,ho=Us,mm=Ra.f,wr=Xu.set,Sm=ed,gm=Ju,bm=fm,ym=vm,_r=Fs,fo=xt.MutationObserver||xt.WebKitMutationObserver,po=xt.document,vo=xt.process,es=xt.Promise,mo=mm(xt,"queueMicrotask"),da=mo&&mo.value,zt,kr,Pr,ts,So;if(!da){var is=new Sm,ss=function(){var i,e;for(_r&&(i=vo.domain)&&i.exit();e=is.get();)try{e()}catch(t){throw is.head&&zt(),t}i&&i.enter()};!gm&&!_r&&!ym&&fo&&po?(kr=!0,Pr=po.createTextNode(""),new fo(ss).observe(Pr,{characterData:!0}),zt=function(){Pr.data=kr=!kr}):!bm&&es&&es.resolve?(ts=es.resolve(void 0),ts.constructor=es,So=ho(ts.then,ts),zt=function(){So(ss)}):_r?zt=function(){vo.nextTick(ss)}:(wr=ho(wr,xt),zt=function(){wr(ss)}),da=function(i){is.head||zt(),is.add(i)}}var Tm=da,Em=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Fa=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},$m=ke,ui=$m.Promise,td=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Am=td,wm=Fs,_m=!Am&&!wm&&typeof window=="object"&&typeof document=="object",km=ke,wi=ui,Pm=Te,Rm=ku,Im=qu,Dm=Pe,Cm=_m,Om=td,Rr=fu,go=wi&&wi.prototype,Lm=Dm("species"),la=!1,id=Pm(km.PromiseRejectionEvent),xm=Rm("Promise",function(){var i=Im(wi),e=i!==String(wi);if(!e&&Rr===66||!(go.catch&&go.finally))return!0;if(!Rr||Rr<51||!/native code/.test(i)){var t=new wi(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Lm]=s,la=t.then(function(){})instanceof s,!la)return!0}return!e&&(Cm||Om)&&!id}),Mi={CONSTRUCTOR:xm,REJECTION_EVENT:id,SUBCLASSING:la},di={},bo=Ut,Nm=TypeError,Bm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw Nm("Bad Promise constructor");e=s,t=r}),this.resolve=bo(e),this.reject=bo(t)};di.f=function(i){return new Bm(i)};var Mm=Qe,As=Fs,$t=ke,Ui=Le,Um=Oa,Fm=xa,Vm=kv,Hm=Ut,ca=Te,Gm=ht,qm=Iv,Ym=Qu,sd=Xu.set,Va=Tm,jm=Em,zm=Fa,Wm=ed,rd=yu,ha=ui,Ha=Mi,ad=di,Vs="Promise",nd=Ha.CONSTRUCTOR,Qm=Ha.REJECTION_EVENT;Ha.SUBCLASSING;var Ir=rd.getterFor(Vs),Jm=rd.set,Km=ha&&ha.prototype,Kt=ha,Dr=Km,od=$t.TypeError,fa=$t.document,Ga=$t.process,pa=ad.f,Xm=pa,Zm=!!(fa&&fa.createEvent&&$t.dispatchEvent),ud="unhandledrejection",eS="rejectionhandled",yo=0,dd=1,tS=2,qa=1,ld=2,rs,To,iS,cd=function(i){var e;return Gm(i)&&ca(e=i.then)?e:!1},hd=function(i,e){var t=e.value,s=e.state==dd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,d,u,l;try{r?(s||(e.rejection===ld&&rS(e),e.rejection=qa),r===!0?d=t:(o&&o.enter(),d=r(t),o&&(o.exit(),l=!0)),d===i.promise?n(od("Promise-chain cycle")):(u=cd(d))?Ui(u,d,a,n):a(d)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},fd=function(i,e){i.notified||(i.notified=!0,Va(function(){for(var t=i.reactions,s;s=t.get();)hd(s,i);i.notified=!1,e&&!i.rejection&&sS(i)}))},pd=function(i,e,t){var s,r;Zm?(s=fa.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),$t.dispatchEvent(s)):s={promise:e,reason:t},!Qm&&(r=$t["on"+i])?r(s):i===ud&&jm("Unhandled promise rejection",t)},sS=function(i){Ui(sd,$t,function(){var e=i.facade,t=i.value,s=Eo(i),r;if(s&&(r=zm(function(){As?Ga.emit("unhandledRejection",t,e):pd(ud,e,t)}),i.rejection=As||Eo(i)?ld:qa,r.error))throw r.value})},Eo=function(i){return i.rejection!==qa&&!i.parent},rS=function(i){Ui(sd,$t,function(){var e=i.facade;As?Ga.emit("rejectionHandled",e):pd(eS,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=tS,fd(i,!0))},va=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw od("Promise can't be resolved itself");var s=cd(e);s?Va(function(){var r={done:!1};try{Ui(s,e,Xt(va,r,i),Xt(ei,r,i))}catch(a){ei(r,a,i)}}):(i.value=e,i.state=dd,fd(i,!1))}catch(r){ei({done:!1},r,i)}}};nd&&(Kt=function(e){qm(this,Dr),Hm(e),Ui(rs,this);var t=Ir(this);try{e(Xt(va,t),Xt(ei,t))}catch(s){ei(t,s)}},Dr=Kt.prototype,rs=function(e){Jm(this,{type:Vs,done:!1,notified:!1,parent:!1,reactions:new Wm,rejection:!1,state:yo,value:void 0})},rs.prototype=Um(Dr,"then",function(e,t){var s=Ir(this),r=pa(Ym(this,Kt));return s.parent=!0,r.ok=ca(e)?e:!0,r.fail=ca(t)&&t,r.domain=As?Ga.domain:void 0,s.state==yo?s.reactions.add(r):Va(function(){hd(r,s)}),r.promise}),To=function(){var i=new rs,e=Ir(i);this.promise=i,this.resolve=Xt(va,e),this.reject=Xt(ei,e)},ad.f=pa=function(i){return i===Kt||i===iS?new To(i):Xm(i)});Mm({global:!0,constructor:!0,wrap:!0,forced:nd},{Promise:Kt});Fm(Kt,Vs,!1,!0);Vm(Vs);var aS=Pe,vd=aS("iterator"),md=!1;try{var nS=0,$o={next:function(){return{done:!!nS++}},return:function(){md=!0}};$o[vd]=function(){return this},Array.from($o,function(){throw 2})}catch(i){}var oS=function(i,e){if(!e&&!md)return!1;var t=!1;try{var s={};s[vd]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},uS=ui,dS=oS,lS=Mi.CONSTRUCTOR,Sd=lS||!dS(function(i){uS.all(i).then(void 0,function(){})}),cS=Qe,hS=Le,fS=Ut,pS=di,vS=Fa,mS=Ba,SS=Sd;cS({target:"Promise",stat:!0,forced:SS},{all:function(e){var t=this,s=pS.f(t),r=s.resolve,a=s.reject,n=vS(function(){var o=fS(t.resolve),d=[],u=0,l=1;mS(e,function(c){var h=u++,f=!1;l++,hS(o,t,c).then(function(m){f||(f=!0,d[h]=m,--l||r(d))},a)}),--l||r(d)});return n.error&&a(n.value),s.promise}});var gS=Qe,bS=Mi.CONSTRUCTOR,Ao=ui;Ao&&Ao.prototype;gS({target:"Promise",proto:!0,forced:bS,real:!0},{catch:function(i){return this.then(void 0,i)}});var yS=Qe,TS=Le,ES=Ut,$S=di,AS=Fa,wS=Ba,_S=Sd;yS({target:"Promise",stat:!0,forced:_S},{race:function(e){var t=this,s=$S.f(t),r=s.reject,a=AS(function(){var n=ES(t.resolve);wS(e,function(o){TS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var kS=Qe,PS=Le,RS=di,IS=Mi.CONSTRUCTOR;kS({target:"Promise",stat:!0,forced:IS},{reject:function(e){var t=RS.f(this);return PS(t.reject,void 0,e),t.promise}});var DS=pt,CS=ht,OS=di,gd=function(i,e){if(DS(i),CS(e)&&e.constructor===i)return e;var t=OS.f(i),s=t.resolve;return s(e),t.promise},LS=Qe,xS=Mt,NS=Su,BS=ui,MS=Mi.CONSTRUCTOR,US=gd,FS=xS("Promise"),VS=!MS;LS({target:"Promise",stat:!0,forced:NS},{resolve:function(e){return US(VS&&this===FS?BS:this,e)}});var HS=Qe,ma=ui,GS=Me,qS=Mt,YS=Te,jS=Qu,wo=gd,zS=ma&&ma.prototype,WS=!!ma&&GS(function(){zS.finally.call({then:function(){}},function(){})});HS({target:"Promise",proto:!0,real:!0,forced:WS},{finally:function(i){var e=jS(this,qS("Promise")),t=YS(i);return this.then(t?function(s){return wo(e,i()).then(function(){return s})}:i,t?function(s){return wo(e,i()).then(function(){throw s})}:i)}});var QS=Mt,Ya=QS,JS=Ya,KS=JS("Promise","finally"),XS=KS,ZS=XS,eg=ZS,tg=eg,Hs=tg,ti;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ti||(ti={}));var si=(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:F(t)}return i},I=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class le{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(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||k(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const ig=i=>{switch(i){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1: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 F(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const sg=5,rg=5,ag=500,_o=7e3;class ng{constructor(e){this.subscription=new ae,this.loadMediaTimeoutSubscription=new ae,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===p.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.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:F(s)}break}case p.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:F(s)}break}case p.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:F(s)}break}default:F(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ig(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ae;this.subscription.add(e),this.subscription.add(H(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 L;e.add(r.pipe(Be(ag)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>sg)&&r.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),d=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<rg&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:F(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(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),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),I(this.params.desiredState.playbackState,p.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:z.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),I(this.params.desiredState.playbackState,p.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),I(this.params.desiredState.playbackState,p.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)===p.READY&&I(this.params.desiredState.playbackState,p.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];R(l);const c=sl(Object.keys(l));R(c);const h=l[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=s[e];R(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:case y.DASH_WEBM_AV1:{const l=s[e];R(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=s[e];R(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];R(l),r=si(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:D.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return F(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:d,subtitle:u}=this.params.meta;return k(d)&&(o.metadata.title=d),k(u)&&(o.metadata.subtitle=u),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===z.Applying||s.state===z.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(rl(_o).subscribe(()=>a(`timeout(${_o})`)))});Hs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class ko{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 bd extends ko{constructor(){super(),this.listeners||ko.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 yd=class{constructor(){Object.defineProperty(this,"signal",{value:new bd,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&&(yd.prototype[Symbol.toStringTag]="AbortController",bd.prototype[Symbol.toStringTag]="AbortSignal");function Td(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 og(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Td({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(u,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(u,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:(d,u)=>{const l=a&&a.prototype.isPrototypeOf(d)?d.signal:u?u.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 u&&u.signal&&delete u.signal,Promise.race([h,n(d,u)])}return n(d,u)},Request:a}}const Gs=Td({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ed=Gs?og({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ri=Gs?Ed.fetch:window.fetch;Gs?Ed.Request:window.Request;const Lt=Gs?yd:window.AbortController,yi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class _i{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return 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]=yi(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(yi),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(),d=new Lt,u=d.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:d};u.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:D.PARSER,message:"Error parsing response data",thrown:h}),h};return ri(o,{signal:u}).then(h=>{var f,m,g;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[b,v]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,v);const S=b.getReader(),A=parseInt((g=h.headers.get("Content-Length"))!==null&&g!==void 0?g:"",10)||a-r+1;l.data=new ArrayBuffer(A);const E=new Uint8Array(l.data),$=({done:C,value:Y})=>ue(this,void 0,void 0,function*(){C?this.onBigRequestProgress(l):Y&&(E.set(Y,l.loaded),l.loaded+=Y.byteLength,this.onBigRequestProgress(l),yield S==null?void 0:S.read().then($,_i.suppressStreamErrors).catch(c))});S==null||S.read().then($,_i.suppressStreamErrors).catch(c)},_i.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,d,u,l,c,h,f,m;if(!this.activeRequests.has(e)||!a)return;const g=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const b of g){const{request:v}=b,[S,A]=yi(v),E=S>=t&&A<=t+r,$=t>=S&&t+r<A,C=a.slice(S-t,Math.min(A-t+1,r));if((E||$)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=C.byteLength,v.bytesTotal=s-t),E){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(N=>N!==b)),(c=b.success)===null||c===void 0||c.call(b,C,"",e);const Y=n?Array.from(n.headers.entries()).map(([N,U])=>`${N}: ${U}`).join(`\r
|
|
7
|
+
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(v,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,Y,[])}else $&&((m=b.progress)===null||m===void 0||m.call(b,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){var a,n,o,d;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:D.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const u=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of u){const[c,h]=yi(l.request);(c>=t&&c<s||h>t&&h<=s)&&((d=l==null?void 0:l.error)===null||d===void 0||d.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[d,u]=yi(o.request);(d>=t&&d<s||u>t&&u<=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 ws{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(ws.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;ws.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const ug=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new ws(r,e,s)}}),dg=(i,e)=>{const t=new _i(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return ug(n,t)}}},!0),()=>t.destroy()};var lg=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)},cg=i=>{const e=new T(1/0),t=new L,s=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},d=l=>{var c,h,f,m,g;const b=Bi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(A=>A.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const A=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:A*1e3)!==null&&f!==void 0?f:NaN;k($)&&!isNaN($)&&e.next($)}const v=(m=b["x-delivery-type"])!==null&&m!==void 0?m:Pi.HTTP1,S=(g={1:!0,0:!1}[b["x-reused"]])!==null&&g!==void 0?g:void 0;s.next(v),r.next(S)},u=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(...g){return d(this),f(...g)},h.progress=function(...g){return u(this),m(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ai=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},hg=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ai}),!0),fg=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 We=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),d=te(r),u=new ae;return r&&u.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),d&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),d&&i.setState(l.to)},a)),u},Ft=(i,e,t)=>We(e,()=>i.loop,s=>{k(s)&&(i.loop=s)},{onError:t}),vt=(i,e,t,s)=>We(e,()=>({muted:i.muted,volume:i.volume}),r=>{k(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}),At=(i,e,t,s)=>We(e,()=>i.playbackRate,r=>{k(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),pg=i=>["__",i.language,i.label].join("|"),vg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class rt{constructor(){this.available$=new L,this.current$=new T(void 0),this.error$=new L,this.subscription=new ae,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(We(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{k(a)&&this.setInternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(We(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{k(a)&&this.setExternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(We(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(We(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(H(M(e,"addtrack"),M(e,"removetrack"),Oe(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ve((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(M(e,"change"),Oe(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),_(s=>s&&this.htmlTextTrackToITextTrack(s).id),ve()).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(M(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var d,u,l,c,h;const f=(u=(d=o.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u: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(M(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;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(rt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:pg(e),a=this.externalTracks.has(r),n=r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",isAuto:n,language:t,label:s,url:this.internalTracks.get(r).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t)))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))k(e)&&vg(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){R(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const ja=i=>{i.removeAttribute("src"),i.load()},mg=i=>{try{i.pause(),i.playbackRate=0,ja(i),i.remove()}catch(e){console.error(e)}};class Sg{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Sa=window.WeakMap?new WeakMap:new Sg,mt=i=>{let e=i.querySelector("video");const t=Boolean(e);return e?ja(e):(e=document.createElement("video"),i.appendChild(e)),Sa.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},St=i=>{const e=Sa.get(i);Sa.delete(i),e?ja(i):mg(i)};class za{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,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const $d=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Po=i=>{const e=$d(i);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===i)},gg=i=>{const e=$d(i);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},ga=3;class bg{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<ga&&(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||ga))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 Ad=(i,e,t=ga)=>{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 d=a-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=a+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const yg=1e3,Tg=i=>{const e=Is();return e.browser===Ta.Chrome&&e.device===su.Android?!0:i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0},gt=i=>{const e=E=>M(i,E).pipe(ii(void 0)),s=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>M(i,E))).pipe(_(E=>E.type==="ended"?i.readyState<2:i.readyState<3),ve()),r=H(M(i,"progress"),M(i,"timeupdate")).pipe(_(()=>Ad(i.buffered,i.currentTime))),n=Is().browser===Ta.Safari?it({play:e("play").pipe(ye()),playing:e("playing")}).pipe(ii(void 0)):e("playing"),o=M(i,"playing").pipe(Be(yg),_(()=>Tg(i))),d=M(i,"volumechange").pipe(_(()=>({muted:i.muted,volume:i.volume}))),u=M(i,"ratechange").pipe(_(()=>i.playbackRate)),l=M(i,"error").pipe(ie(()=>Boolean(i.error||i.played.length)),_(()=>{var E;const $=i.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(E=i.error)!==null&&E!==void 0?E:void 0}})),c=M(i,"timeupdate").pipe(_(()=>i.currentTime)),h=new L,f=.3;let m;c.subscribe(E=>{i.loop&&k(m)&&k(E)&&m>=i.duration-f&&E<=f&&h.next(m),m=E});const g=M(i,"enterpictureinpicture"),b=M(i,"leavepictureinpicture"),v=new T(gg(i));g.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));const S=new T(Po(i));return M(i,"fullscreenchange").pipe(_(()=>Po(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ie(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:M(i,"durationchange").pipe(_(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:d,isAudioAvailable$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}},Wa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Eg=Qe,$g=Bs,Ag=Ca,wg=Da;Eg({target:"Array",proto:!0},{at:function(e){var t=$g(this),s=Ag(t),r=wg(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var _g=Ya,kg=_g("Array","at"),Pg=kg,Rg=Pg,Ig=Rg,Dg=Ig,nt=Dg;let Qa=!1,ut={};const Cg=i=>{Qa=i},Og=()=>{ut={}},Lg=i=>{i(ut)},as=(i,e)=>{var t;Qa&&(ut.meta=(t=ut.meta)!==null&&t!==void 0?t:{},ut.meta[i]=e)};class et{constructor(e){this.name=e}next(e){var t,s;if(!Qa)return;ut.series=(t=ut.series)!==null&&t!==void 0?t:{};const r=(s=ut.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ut.series[this.name]=r}}const xg=new et("best_bitrate"),Ng=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class Bg{constructor(){this.history={}}recordSelection(e){this.history[e.id]=fe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Fi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:d,history:u})=>{var l,c,h,f;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,g=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},b=g&&Nt(g),v=s.considerPlaybackRate&&k(o)?o:1,S=i.filter(B=>!bs(B.quality)).sort((B,x)=>ps(B.quality,x.quality)?-1:1),A=(c=nt(S,-1))===null||c===void 0?void 0:c.quality,E=(h=nt(S,0))===null||h===void 0?void 0:h.quality,$=te(r)||k(r.min)&&k(r.max)&&Ks(r.max,r.min)||k(r.min)&&E&&ps(r.min,E)||k(r.max)&&A&&Ks(r.max,A),C=v*Ng(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),N=S.filter(B=>{const x=b?Ks(B.quality,b):!0,Z=k(t)&&isFinite(t)&&k(B.bitrate)?t-a>=B.bitrate*C:!0,de=s.lazyQualitySwitch&&k(s.minBufferToSwitchUp)&&d&&!bs(d.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&ps(B.quality,d.quality),ge=$||(te(r.max)||al(B.quality,r.max))&&(te(r.min)||nl(B.quality,r.min));return x&&Z&&!de&&ge})[0];N&&N.bitrate&&xg.next(N.bitrate);const U=(f=N!=null?N:S[Math.ceil((S.length-1)/2)])!==null&&f!==void 0?f:i[0],Q=U&&u&&u.history[U.id]&&fe()-u.history[U.id]<=s.trackCooldown&&(!u.last||U.id!==u.last.id);if(U!=null&&U.id&&u&&!Q&&u.recordSelection(U),Q&&(u!=null&&u.last)){const B=u.last;return u==null||u.recordSwitch(B),B}return u==null||u.recordSwitch(U),U};var Re=i=>new URL(i).hostname;const Mg=300,_s=(i,e=Mg)=>new Ds(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(cl(n=>{const o=n[0];if(!o)return;let d,u;o.contentBoxSize&&o.contentBoxSize[0]?(u=o.contentBoxSize[0].blockSize,d=o.contentBoxSize[0].inlineSize):o.contentRect&&(d=o.contentRect.width,u=o.contentRect.height),k(d)&&k(u)&&t.next({width:d,height:u})},e));return a.observe(i),()=>a.disconnect()}),Ug=5e3,Ti={};var W;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const Se=(i,e)=>new Ds(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class Ro{constructor(e){this.subscription=new ae,this.videoState=new le(W.DOWNLOADING_LIB),this.textTracksManager=new rt,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new za,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===W.DOWNLOADING_LIB||t===W.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&t!==W.STOPPED&&s!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case p.STOPPED:{switch(t){case W.STOPPED:break;case W.PLAYING:case W.PAUSED:case W.READY:this.stop();break;default:F(t)}break}case p.READY:{switch(t){case W.STOPPED:this.prepare();break;case W.PLAYING:case W.PAUSED:case W.READY:break;default:F(t)}break}case p.PLAYING:{switch(t){case W.PLAYING:break;case W.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 W.READY:this.play();break;case W.STOPPED:this.prepare();break;default:F(t)}break}case p.PAUSED:{switch(t){case W.PLAYING:this.pause(),this.liveOffset.pause();break;case W.PAUSED:break;case W.READY:this.videoState.setState(W.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case W.STOPPED:this.prepare();break;default:F(t)}break}default:F(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(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:D.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Ug);Hs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Ti.MediaPlayer=r.MediaPlayer,Ti.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(Ti.MediaPlayer,"dashjs not loaded"),R(Ti.Debug,"dashjs not loaded"),this.player=Ti.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?Wa(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=dg(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&&fg(this.player),lg(this.player),this.params.tuning.requestQuick&&hg(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,S)=>this.subscription.add(v.subscribe(S,s));r(_s(this.video),this.elementSize$),r(Se(this.player,"error").pipe(_(v=>{const S=typeof v.error=="object"?v.error.code:v.error,A=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${S}`,message:A}})),e.error$),r(Se(this.player,"playbackError").pipe(_(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(ie(({mediaType:v})=>v==="video"),_(({newQuality:v})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:A})=>A.qualityIndex===v))===null||S===void 0?void 0:S.track}));a.pipe(ie(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(ie(({to:v})=>v===W.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(We(t.videoTrack,()=>{var v,S;const A=this.player.getQualityFor("video");return(S=(v=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===A))===null||v===void 0?void 0:v.track)===null||S===void 0?void 0:S.id},v=>{var S;if(te(v))return;const A=(S=this.videoTracks.find(({track:E})=>E.id===v))===null||S===void 0?void 0:S.bitrateInfo;A&&this.player.setQualityFor("video",A.qualityIndex)},{changed$:a.pipe(_(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(We(t.autoVideoTrackSwitching,()=>{var v,S,A;return(A=(S=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||A===void 0?void 0:A.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(Se(this.player,"bufferStateChanged").pipe(ie(({mediaType:v})=>v==="video"),_(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:S}})=>{var A,E;const $=this.player.getDashMetrics(),C=$.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),Y=(A=$.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&A!==void 0?A:Pi.HTTP1,N=(E={1:!0,0:!1}[C])!==null&&E!==void 0?E:void 0;this.params.output.httpConnectionType$.next(Y),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Re(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:S,availableFrom:A}}})=>{this.isLive$.next(S),this.availableFrom$.next(A.getTime()),S||e.duration$.next(v),this.videoTracks=[];const E=this.player.getQualityFor("video");let $;for(const C of this.player.getBitrateInfoListFor("video")){const Y=C.qualityIndex.toString(10),N=Nt(C),U=C.bitrate/1e3,Q={width:C.width,height:C.height},B=this.frameRatesByFrameHeight[C.height];if(N){const x={id:Y,quality:N,bitrate:U,size:Q,fps:B};this.videoTracks.push({track:x,bitrateInfo:C}),C.qualityIndex===E&&($=x)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:C})=>C)),$&&e.currentVideoTrack$.next($),this.videoState.setState(W.STREAM_INITIALIZED),this.videoState.startTransitionTo(W.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const S=v.requestEndDate.getTime()-v.firstByteDate.getTime(),A=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(A,S)}),r(H(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Fi(this.videoTracks.map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),A=this.videoTracks.find(({track:E})=>E===S);A!=null&&A.bitrateInfo&&this.player.setQualityFor("video",A==null?void 0:A.bitrateInfo.qualityIndex,!1)}),r(it({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(ie(k))}).pipe(ie(({isLive:v})=>v),_(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(_(({time:v})=>v!=null?v:0));r(it({availableFrom:this.availableFrom$.pipe(ie(k)),currentTime:n}),({availableFrom:v,currentTime:S})=>this.params.output.liveTime$.next(v+S*1e3)),r(n.pipe(ie(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe(_(()=>Ad(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(W.PLAYING),I(t.playbackState,p.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(W.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(W.PAUSED),I(t.playbackState,p.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===W.READY&&this.videoState.setState(W.READY)}),r(this.isLive$,e.isLive$),r(_s(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0));r(o,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:l,connectionReused$:c}=cg(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(ye()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(it({isLive:this.isLive$,isShort:e.duration$.pipe(_(v=>v<60))}),({isLive:v,isShort:S})=>{const A=!v&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:A}}})}),r(n.pipe(ie(v=>v>this.params.tuning.insufficientBufferRuleMargin),ye()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ye()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ye(),ii(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(Se(this.player,"manifestLoaded"),v=>{var S,A,E,$,C,Y,N;if(!((A=(S=v.data)===null||S===void 0?void 0:S.Period)===null||A===void 0)&&A.AdaptationSet){const U=[];for(const Q of($=(E=v.data)===null||E===void 0?void 0:E.Period)===null||$===void 0?void 0:$.AdaptationSet)if(Q.contentType==="text"){const B=(C=Q.Representation)===null||C===void 0?void 0:C.id,x=new URL((Y=Q.Representation)===null||Y===void 0?void 0:Y.BaseURL,(N=v.data)===null||N===void 0?void 0:N.baseUri).toString(),Z="internal",de=Q.lang;U.push({id:B,url:x,type:Z,language:de})}t.internalTextTracks.startTransitionTo(U)}}),this.subscription.add(Ft(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:g,inFullscreen$:b}=gt(this.video);this.subscription.add(vt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(At(this.video,t.playbackRate,m,s)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(W.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(W.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=si(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(W.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(W.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){}St(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Vi=i=>{switch(i){case"mobile":return qe.Q_144P;case"lowest":return qe.Q_240P;case"low":return qe.Q_360P;case"sd":case"medium":return qe.Q_480P;case"hd":case"high":return qe.Q_720P;case"fullhd":case"full":return qe.Q_1080P;case"quadhd":case"quad":return qe.Q_1440P;case"ultrahd":case"ultra":return qe.Q_2160P}};const Io=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var wt=i=>ue(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Io(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return Io(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function _e(){return fe()}function wd(i){return _e()-i}function Do(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,d=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return d&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Fg(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function gs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,d=!1,u=0,l,c,h=!1,f="arraybuffer",m=7e3,g=2e3,b=()=>{if(d)return;R(l);const x=wd(l);let Z;if(x<g){Z=g-x,setTimeout(b,Z);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,C()};const v=x=>(a=x,B),S=x=>(c=x,B),A=()=>(f="json",B),E=()=>{if(!d){if(--u>=0){b(),s&&s();return}d=!0,c&&c(),t&&t()}},$=x=>(h=x,B),C=()=>{l=_e(),n=new r,n.open("get",i);let x=0,Z,de=0;const ge=()=>(R(l),Math.max(l,Math.max(Z||0,de||0)));if(a&&n.addEventListener("progress",P=>{const G=_e();a.updateChunk&&P.loaded>x&&(a.updateChunk(ge(),P.loaded-x),x=P.loaded,Z=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(d)return;R(n);const P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&a){const G=n.response.byteLength-x;G&&a.updateChunk&&a.updateChunk(ge(),G)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const P=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(de=_e(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=f,n.send(),B},B={withBitrateReporting:v,withParallel:$,withJSONResponse:A,withRetryCount:x=>(u=x,B),withRetryInterval:(x,Z)=>(k(x)&&(g=x),k(Z)&&(m=Z),B),withTimeout:x=>(o=x,B),withFinally:S,send:C,abort:()=>{n&&(n.abort(),n=void 0),d=!0,c&&c()}};return B}const Vg=100,Hg=2e3,Gg=500;let qg=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-Gg;if(t-e>Hg){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const d=a.bytes*n/o;r+=d,a.start=t,a.bytes-=d}}}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>Vg&&(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 Yg{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=_e(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=d=>{e._complete=1,e._responseData=d,e._downloadTime=_e()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=gs(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=_e()}_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=_e();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 ns=1e4,os=3,jg=300,zg=2e3,Wg=6e4,Qg=10,Jg=1,Kg=500;class Xg{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 qg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Do(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=Do(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||k(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=()=>{Fg(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 Yg(os,ns,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,d=null,u=null,l=!1;const c=()=>{const E=a&&(!l||l===this.rep);return E||t("Not running!"),E},h=(E,$,C)=>{d&&d.abort(),d=gs(this.urlResolver.resolve(E,!1),$,C,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(os).withFinally(()=>{d=null}).send()},f=(E,$,C)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,C,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{const $=s.playbackRate;s.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),s.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const C=_e()-1e4;let Y=0;for(let U=0;U<this.bufferStates.length;U++){const Q=this.bufferStates[U];E=Math.min(E,Q.buf),Q.ts<C&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${E} drop=${Y} jitter=${this.sourceJitter}`);let N=E-Jg;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?m(1.15):N>1?m(1.1):N>.3?m(1.05):m(1)}},v=E=>{let $;const C=()=>$&&$.start?$.start.length:0,Y=P=>$.start[P]/1e3,N=P=>$.dur[P]/1e3,U=P=>$.fragIndex+P,Q=(P,G)=>({chunkIdx:U(P),startTS:Y(P),dur:N(P),discontinuity:G}),B=()=>{let P=0;if($&&$.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=G;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let be=$.dur.length-1;for(;be>=0&&(pe-=$.dur[be],!(pe<=0));--be);P=Math.min(be,$.dur.length-1-ne),P=Math.max(P,0)}return Q(P,!0)},x=P=>{const G=C();if(!(G<=0)){if(k(P)){for(let ne=0;ne<G;ne++)if(Y(ne)>P)return Q(ne)}return B()}},Z=P=>{const G=C(),ne=P?P.chunkIdx+1:0,pe=ne-$.fragIndex;if(!(G<=0)){if(!P||pe<0||pe-G>Qg)return t(`Resync: offset=${pe} bChunks=${G} chunk=`+JSON.stringify(P)),B();if(!(pe>=G))return Q(ne-$.fragIndex,!1)}},de=(P,G,ne)=>{u&&u.abort(),u=gs(this.urlResolver.resolve(P,!0,this.lowLatency),G,ne,()=>this._retryCallback()).withTimeout(ns).withRetryCount(os).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,G)=>{de(E,ne=>{if(!c())return;$=ne;const pe=Boolean($.lowLatency);pe!==this.lowLatency&&g(pe);let be=0;for(let Ie=0;Ie<$.dur.length;++Ie)be+=$.dur[Ie];be>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,P(x(G))},()=>this._handleNetworkError())},nextChunk:Z}},S=()=>{a=!1,o&&o.abort(),d&&d.abort(),u&&u.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:C}=this.params;let Y=v(e.jidxUrl),N,U,Q,B,x=0,Z,de,ge;const P=()=>{Z&&(clearTimeout(Z),Z=void 0);const K=Math.max(Kg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=x+K,Fe=_e(),Ve=Math.min(1e4,Ee-Fe);x=Fe;const at=()=>{u||c()&&Y.seek(()=>{c()&&(x=_e(),G(),P())})};Ve>0?Z=window.setTimeout(()=>{this.paused?P():at()},Ve):at()},G=()=>{let K;for(;K=Y.nextChunk(B);)B=K,Je(K);const Ee=Y.nextChunk(Q);if(Ee){if(Q&&Ee.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}Ie(Ee)}else P()},ne=(K,Ee)=>{if(!c()||!this.sourceBuffer)return;let Fe,Ve,at;const _t=yt=>{window.setTimeout(()=>{c()&&ne(K,Ee)},yt)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),_t(100);else{const yt=_e(),Vt=$.currentTime;!this.paused&&$.buffered.length>1&&de===Vt&&yt-ge>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),de!==Vt&&(de=Vt,ge=yt);const Ke=this._getBufferSizeSec();if(Ke>30)C(`Buffered ${Ke} seconds; delaying appendBuffer`),_t(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:Ke}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(li){if(li.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Fe=this.sourceBuffer.buffered.start(0),Ve=Vt,Ve-Fe>4&&this.sourceBuffer.remove(Fe,Ve-3)),_t(1e3);else throw li}}},pe=()=>{U&&N&&(C([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(Q)]),ne(U,function(){U=null,G()}))},be=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),Ie=K=>{c()&&f(be(K),(Ee,Fe)=>{if(c()){if(Fe/=1e3,U=Ee,Q=K,n=K.startTS,Fe){const Ve=Math.min(10,K.dur/Fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}pe()}},()=>this._handleNetworkError())},Je=K=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(K),!1)))},bt=K=>{c()&&(e.cachedHeader=K,ne(K,()=>{N=!0,pe()}))};a=!0,Y.seek(K=>{if(c()){if(x=_e(),!K){P();return}B=K,!te(E)||K.startTS>E?Ie(K):(Q=K,G())}},E),e.cachedHeader?bt(e.cachedHeader):h(e.headerUrl,bt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(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=_e();if(this.chunkRateEstimator.addInterval(h,m,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:b}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,d=!0;const u=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(d&&c>o&&wd(n)<3e4)return;s(c)}d=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&u(),f},notifySwitch:c=>{const h=_e();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=gs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).withRetryCount(os).withRetryInterval(jg,zg).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;wt(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((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,o.push(d))}),o.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.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))},Wg))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const Zg=[j.PAUSED,j.PLAYING,j.READY],eb=[j.PAUSED,j.PLAYING,j.READY];class tb{constructor(e){this.subscription=new ae,this.videoState=new le(j.STOPPED),this.representations$=new T([]),this.textTracksManager=new rt,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new za,this._dashCb=r=>{var a,n,o,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,l=[];for(const c of u){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Vi(c.name))!==null&&n!==void 0?n:Nt(c.video),m=c.bitrate/1e3,g=Object.assign({},c.video);if(!f)continue;const b={id:h,quality:f,bitrate:m,size:g};l.push({track:b,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,l=(d=this.representations$.getValue().find(({representation:c})=>c===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),k(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:u,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,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(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(u)};`}),o===p.STOPPED){a!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(!n){if(eb.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;k(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((d==null?void 0:d.to)!==p.PAUSED&&u.state===z.Requested&&Zg.includes(a)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(a){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(si(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(o===p.PAUSED)this.videoState.setState(j.PAUSED);else if(o===p.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const l=d==null?void 0:d.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:o===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:o===p.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return F(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:r})};H(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(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=gt(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(it({zeroTime:this.zeroTime$.pipe(ie(k)),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(At(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(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&ol(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return F(r.to)}},t)).add(H(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(this.video)}createLiveDashPlayer(){const e=new Xg({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(),d=(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(),u=(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=!u&&k(d)?d:(a=Fi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;R(c,"Representations missing"),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;R(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=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(si(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var _d=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?Pi.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}},Ot=(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 ib=i=>{const e=document.createElement("a");return e.href=i,e.origin},sb=i=>{const e=document.createElement("a");return e.href=i,e.host};class kd{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,d,u;if(R(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=Bi(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&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(l){throw(u=this._errorCb)===null||u===void 0||u.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(sb(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 ks{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 d=0;const u=Date.now();let l=0,c=0,h=0;const f=g=>{r(ks._str2ua(g.substr(d))),d=g.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ai(m)),this._lastXhr=new kd(m,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const b=Date.now()-u;this._params.onBandwidthChange({size:g.length,duration:b,speed:8*g.length/(b/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-d>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,b,v)=>this._params.onError(g,b,v))})}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=ks._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 rb{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,d)=>{const u=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},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=ai(s)),new kd(s,t,r=>{this.attachManifest(r,t,ib(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=(u,l)=>{const c=u.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],d=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),u=>{var l,c,h,f,m,g,b,v,S,A,E,$,C,Y,N,U,Q,B,x;const Z=u.getElementsByTagName("SegmentBase")[0],de=Z&&n(Z,"indexRange").split("-"),ge=Z&&Z.getElementsByTagName("Initialization")[0],P=ge&&n(ge,"range").split("-");if(!P||!de){const Je=u.parentElement;if((Je==null?void 0:Je.getAttribute("contentType"))==="text"){const bt=(l=u.getAttribute("id"))!==null&&l!==void 0?l:void 0,K=(s?s+"/":"")+((m=(f=(h=(c=u.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=(g=Je.getAttribute("lang"))!==null&&g!==void 0?g:void 0;K&&d.push({id:bt,url:K,language:Ee})}return}const G=.1,ne=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),pe=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let be;const Ie=(S=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&S!==void 0?S:void 0;be=Ie?Wa(Ie):void 0,o.push({width:Number((A=u.attributes.getNamedItem("width"))===null||A===void 0?void 0:A.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:ne,baseURL:pe,failoverHosts:t,indexFrom:Number(de[0]),indexTo:Number(de[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(C=($=u.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&C!==void 0?C:void 0,mimeType:(N=(Y=u.attributes.getNamedItem("mimeType"))===null||Y===void 0?void 0:Y.value)!==null&&N!==void 0?N:void 0,fps:be,bufferSize:G*ne/8,bufferLength:G,name:(Q=(U=u.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&Q!==void 0?Q:void 0,id:(x=(B=u.attributes.getNamedItem("id"))===null||B===void 0?void 0:B.value)!==null&&x!==void 0?x:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}d.forEach(({id:u,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),u&&h.setAttribute("id",u),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((u,l)=>l.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_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 d=n.getUint32(a,!1),u=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=u+(n.getUint32(a,!1)&2147483647),m=d+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:d/o,toTime:m/o,fromOffset:u,toOffset:f-1}),u=f,d=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 u=this._findRef(this._video.currentTime);if(!u||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(u.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(u.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(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}o()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ks({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-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),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?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,d)=>this._stream.remove(o,d)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,d)=>this._stream.remove(o,d)),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||te(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 J;(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"})(J||(J={}));const ab=[J.PAUSED,J.PLAYING];class nb{constructor(e){this.videoState=new le(J.STOPPED),this.subscription=new ae,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new rt,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,a,n;const o=[];for(const d of t){const u=(a=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&a!==void 0?a:d.height.toString(10),l=(n=d.name&&Vi(d.name))!==null&&n!==void 0?n:Nt(d),c=d.bandwidth/1e3,h={width:d.width,height:d.height},f=d.fps;if(!l)continue;const m={id:u,quality:l,bitrate:c,size:h,fps:f};o.push({track:m,representation:d})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const l=u.id||`${u.language}_${Date.now()}`;d.push({id:l,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(J.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 R(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===p.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&ab.includes(t)&&this.seek(n.position,n.forcePrecise),t){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_LOADED),this.prepare();return;case J.MANIFEST_LOADED:this.videoState.startTransitionTo(J.INITIAL_REPRESENTATION_SELECTED);return;case J.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(J.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case J.METADATA_LOADED:this.videoState.startTransitionTo(J.READY),this.dash.updateRefsForCurrentTime();return;case J.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case J.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),H(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new bg(this.video),this.dash=new rb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),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:D.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:D.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:o},a=gt(this.video),n=(o,d)=>this.subscription.add(o.subscribe(d,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$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{te(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===J.PLAYING||this.videoState.getState()===J.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(At(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)===J.READY&&this.videoState.setState(J.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(J.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(_(({id:o,message:d,thrown:u})=>({id:`DashLite_${o}`,category:D.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(H(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe(_(()=>{var o,d,u;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(),g=this.elementSize$.getValue(),b=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let v;if(!b&&k(f))v=f;else{const S=Ot(this.video.buffered,this.video.currentTime*1e3),A=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(S/A,1);v=(d=Fi(c.map(({track:$})=>$),{container:g,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:$})=>$===l))===null||o===void 0?void 0:o.track}))===null||d===void 0?void 0:d.id}return k(v)?(u=c.find(({track:S})=>S.id===v))===null||u===void 0?void 0:u.representation:void 0}),ve()).subscribe(this.currentRepresentation$,s)).add(it({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(ie(o=>o.to===J.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(ie(k))}).pipe(ye()).subscribe(()=>this.videoState.setState(J.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(ie(k),ve((o,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=d.height:o===d)).subscribe(o=>{const d=Ot(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Re(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:d,reused:u}=_d(o);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),ii(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(ie(k)).subscribe(this.handleRepresentationPlay,s)).add(H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return F(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var Ae;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Ae||(Ae={}));var Ps;(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"})(Ps||(Ps={}));var Ne;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ne||(Ne={}));var ee;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(ee||(ee={}));var ni;(function(i){i.MP4="mp4",i.WEBM="webm"})(ni||(ni={}));var ba=(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 ob=(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)},ub=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=ub?ob:window.requestIdleCallback;var Cr,Or;let Pd=!1;try{Pd=Is().browser===Ta.Safari&&parseInt((Or=(Cr=navigator.userAgent.match(/Version\/(\d+)/))===null||Cr===void 0?void 0:Cr[1])!==null&&Or!==void 0?Or:"",10)<16}catch(i){console.error(i)}class db{constructor(e){this.bufferFull$=new L,this.error$=new L,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:D.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;Pd&&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),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation: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"||this.error$.next({id:`BufferTaskQueue:${s}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:F(t)}}}var Oo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Rd=new TextDecoder("ascii"),Id=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=Rd.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}},lb=i=>Rd.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",cb=(i,e,t)=>{const s=Id(i),r=[];let a=0;const n=()=>{const g=s.contents.getUint32(a);return a+=4,g};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const u=n(),l=n(),c=n(),h=n()&4294967295;let f=l/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+c;for(let g=0;g<h;g++){const b=n(),v=b>>>31,S=b<<1>>>1,A=n();if(n(),v!==0)throw new Error("Unsupported multilevel sidx");const E=A/u*1e3;r.push({status:ee.NONE,time:{from:f,to:f+E},byte:{from:m,to:m+S-1}}),f+=E,m+=S}return r},hb=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=Id(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},fb={validateData:lb,parseInit:()=>null,getIndexRange:()=>{},parseSegments:cb,parseFeedableSegmentChunk:hb};var w;(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"})(w||(w={}));var O;(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"})(O||(O={}));const Lo={[w.EBML]:{type:O.Master},[w.EBMLVersion]:{type:O.UnsignedInteger},[w.EBMLReadVersion]:{type:O.UnsignedInteger},[w.EBMLMaxIDLength]:{type:O.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:O.UnsignedInteger},[w.DocType]:{type:O.String},[w.DocTypeVersion]:{type:O.UnsignedInteger},[w.DocTypeReadVersion]:{type:O.UnsignedInteger},[w.Void]:{type:O.Binary},[w.Segment]:{type:O.Master},[w.SeekHead]:{type:O.Master},[w.Seek]:{type:O.Master},[w.SeekID]:{type:O.Binary},[w.SeekPosition]:{type:O.UnsignedInteger},[w.Info]:{type:O.Master},[w.TimestampScale]:{type:O.UnsignedInteger},[w.Duration]:{type:O.Float},[w.Tracks]:{type:O.Master},[w.Chapters]:{type:O.Master},[w.Cluster]:{type:O.Master},[w.Timestamp]:{type:O.UnsignedInteger},[w.SilentTracks]:{type:O.Master},[w.SilentTrackNumber]:{type:O.UnsignedInteger},[w.Position]:{type:O.UnsignedInteger},[w.PrevSize]:{type:O.UnsignedInteger},[w.SimpleBlock]:{type:O.Binary},[w.BlockGroup]:{type:O.Master},[w.EncryptedBlock]:{type:O.Binary},[w.Attachments]:{type:O.Master},[w.Tags]:{type:O.Master},[w.Cues]:{type:O.Master},[w.CuePoint]:{type:O.Master},[w.CueTime]:{type:O.UnsignedInteger},[w.CueTrackPositions]:{type:O.Master},[w.CueTrack]:{type:O.UnsignedInteger},[w.CueClusterPosition]:{type:O.UnsignedInteger},[w.CueRelativePosition]:{type:O.UnsignedInteger},[w.CueDuration]:{type:O.UnsignedInteger},[w.CueBlockNumber]:{type:O.UnsignedInteger},[w.CueCodecState]:{type:O.UnsignedInteger},[w.CueReference]:{type:O.Master},[w.CueRefTime]:{type:O.UnsignedInteger}},Dd=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=Rs(i,t),r=s in Lo,a=r?Lo[s].type:O.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 d=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,l=Rs(d),c=u*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}},Rs=(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},dt=(i,e)=>{switch(e){case O.SignedInteger:return i.getInt8(0);case O.UnsignedInteger:return Rs(i);case O.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case O.String:return new TextDecoder("ascii").decode(i);case O.UTF8:return new TextDecoder("utf-8").decode(i);case O.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case O.Master:return i;case O.Binary:return i;default:F(e)}},Hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Dd(s);if(!e(r))return;r.type===O.Master&&Hi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},pb=i=>{if(i.getUint32(0)!==w.EBML)return!1;let e,t,s;const r=Dd(i);return Hi(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=dt(o,n):a===w.DocType?t=dt(o,n):a===w.DocTypeReadVersion&&(s=dt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Cd=[w.Info,w.SeekHead,w.Tracks,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],vb=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],mb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,d,u;return Hi(i,({tag:l,type:c,value:h,valueSize:f})=>{if(l===w.SeekID){const m=dt(h,c);u=Rs(m)}else l!==w.SeekPosition&&(u=void 0);return l===w.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===w.Info?a=!0:l===w.SeekHead?n=!0:l===w.TimestampScale?s=dt(h,c):l===w.Duration?r=dt(h,c):l===w.SeekPosition&&u===w.Cues?d=dt(h,c):a&&n&&Cd.includes(l)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(r,"Failed to parse webm Segment duration"),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:d}},Sb=i=>{if(te(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},gb=(i,e)=>{let t=!1,s=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return Hi(i,({tag:o,type:d,value:u})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=dt(u,d));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=dt(u,d));break;default:t&&Cd.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,d)=>{const{time:u,position:l}=o,c=a[d+1];return{status:ee.NONE,time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},bb=i=>{let e=0,t=!1;try{Hi(i,s=>s.tag===w.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):vb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},yb={validateData:pb,parseInit:mb,getIndexRange:Sb,parseSegments:gb,parseFeedableSegmentChunk:bb};class xo{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:d=!1}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.error$=new L,this.gaps=[],this.subscription=new ae,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Lt,this.destroyAbortController=new Lt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=je(this.destroyAbortController.signal,function(u){return ze(this,arguments,function*(){const l=this.representations.get(u);R(l,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new db(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Oo(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield V(this.loadInit(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id);if(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield V(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;k(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield yield V(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=je(this.destroyAbortController.signal,function(u){return ze(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield V(void 0);this.switchingToRepresentationId=u;const l=this.representations.get(u);R(l,`No such representation ${u}`);let c=this.initData.get(u);if(te(c)?yield yield V(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield V(c)),c=this.initData.get(u),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield V(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield V(this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal));const h=this.getCurrentPosition();k(h)&&this.maintain(h)})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case ni.MP4:this.containerParser=fb;break;case ni.WEBM:this.containerParser=yb;break;default:F(s)}this.initData=new Map(r.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(r.map(u=>[u.id,u])),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 Lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(R(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Ot(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)&&Oo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ot(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))u="high";else{const l=nt(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===ee.FED&&!o.length&&Ot(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=nt(s,-1);d&&d.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}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(d=>d.time.from<=e&&d.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const g=h<=s&&f>=s,b=h>s||g||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=s+v||f<=s+v;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&b&&S&&this.sourceBuffer&&!ba(this.sourceBuffer.buffered,s))&&b&&S});if(r===-1)return[];if(t!==Ne.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=u||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===ee.NONE||h.status===ee.PARTIALLY_EJECTED)d.push(h);else break}return d}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 Ne.BYTE_RANGE:{r=t.segmentReference.url,a={from:nt(e,0).byte.from,to:nt(e,-1).byte.to};break}case Ne.TEMPLATE:{const u=nt(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),n=[u];break}default:F(o)}for(const u of n)u.status=ee.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield je(d,function(){return ze(this,arguments,function*(){const u=un(this.failedDownloads,this.tuning.downloadBackoff);yield yield V(new Promise(l=>setTimeout(l,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(u,l)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,a?a.from:0,l,d)}catch(c){this.error$.next({id:"SegmentFeeding",category:D.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(s=Ot((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:D.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=ee.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===ee.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=u===Ne.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 b=f?h.byte.from-s:0,v=f?h.byte.to-s:e.byteLength,S=b<r,A=v<=r;if(h.status===ee.DOWNLOADING&&S&&A){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(m,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(C=>{if(a.aborted)n();else if(C)c.fedBytes+=$.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Co(()=>Hs(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?je(this.destroyAbortController.signal,function(){return ze(this,arguments,function*(){const o=un(this.failedDownloads,this.tuning.downloadBackoff);yield yield V(new Promise(d=>setTimeout(d,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:d,segments:u}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:D.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||te(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const d=u=>{var l;a=Math.min(a,u.time.from),n=Math.max(n,u.time.to);const c="size"in u?(l=u.size)!==null&&l!==void 0?l:0:u.byte.to-u.byte.from;r+=c};for(const u of this.segments.values())for(const l of u){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.FED&&d(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const u of this.segments.values())for(const l of u){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===ee.FED&&d(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===ee.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 u=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+u&&c.status===ee.FED&&d(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=Co(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(te(this.sourceBuffer)||te(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!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),d=e.some(l=>l.from-t<=n&&l.to+t>=o),u=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);d||(u.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var Zt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Zt||(Zt={}));class Tb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new Lt,this.subscription=new ae,this.fetchManifest=je(this.abortAllController.signal,function(r){return ze(this,arguments,function*(){let a=r;this.requestQuic&&(a=ai(a));const n=yield yield V(ri(a,{signal:this.abortAllController.signal}).catch(Ei));return n?(this.onHeadersReceived(n.headers),yield V(n.text())):yield V(null)})}.bind(this)),this.fetch=je(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Zt.HEADER:Zt.PARAM,range:n,onProgress:o,priority:d="auto",signal:u,measureThroughput:l=!0}={}){var c,h,f,m;return ze(this,arguments,function*(){let g=r;const b=new Headers;if(n)switch(a){case Zt.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Zt.PARAM:{const P=new URL(g,location.href);P.searchParams.append("bytes",`${n.from}-${n.to}`),g=P.toString();break}default:F(a)}this.requestQuic&&(g=ai(g));let v=this.abortAllController.signal;if(u){const P=new Lt;if(this.subscription.add(H(M(this.abortAllController.signal,"abort"),M(u,"abort")).subscribe(()=>{try{P.abort()}catch(G){Ei(G)}})),this.abortAllController.signal.aborted||u.aborted)try{P.abort()}catch(G){Ei(G)}v=P.signal}const S=fe(),A=yield yield V(ri(g,{priority:d,headers:b,signal:v}).catch(Ei)),E=fe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(E-S),!A)return yield V(null);if(!A.ok||!A.body)return yield V(Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`)));this.onHeadersReceived(A.headers);const $=parseInt((h=A.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!$){const P=yield yield V(A.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(P.byteLength,fe()-E),o==null||o(new DataView(P),P.byteLength),yield V(P)}if(!o&&!l)return yield V(A.arrayBuffer());const[C,Y]=A.body.tee(),N=C.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(Y));let U=0;const Q=new ArrayBuffer($),B=new Uint8Array(Q),x=new DataView(Q);let Z=!1;const de=P=>{Z=!0,Ei(P)},ge=je(v,function({done:P,value:G}){return ze(this,arguments,function*(){if(U===0&&this.lastRequestFirstBytes$.next(fe()-S),v.aborted)return yield V(void 0);!P&&G&&(B.set(G,U),U+=G.byteLength,o==null||o(x,U),yield yield V(N==null?void 0:N.read().then(ge,de)))})}.bind(this));return yield yield V(N==null?void 0:N.read().then(ge,de)),yield V(Z?null:Q)})}.bind(this)),this.fetchByteRangeRepresentation=je(this.abortAllController.signal,function(r,a,n){var o;return ze(this,arguments,function*(){if(r.type!==Ne.BYTE_RANGE)return yield V(null);const{from:d,to:u}=r.initRange;let l=d,c=u,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=u+1===f,h&&(l=Math.min(f,d),c=Math.max(m,u))),l=Math.min(l,0);const g=yield yield V(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!g)return yield V(null);const b=new DataView(g,d-l,u-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),S=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!S)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(g,S.from-l,S.to-S.from+1);else{const $=yield yield V(this.fetch(r.url,{range:S,priority:n,measureThroughput:!1}));if(!$)return yield V(null);A=new DataView($)}const E=a.parseSegments(A,v,S);return yield V({dataView:new DataView(g),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=je(this.abortAllController.signal,function(r,a){return ze(this,arguments,function*(){if(r.type!==Ne.TEMPLATE)return yield V(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield V(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield V(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:ee.NONE,size:void 0}));return yield V({segments:d,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=_d(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 Ne.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ne.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:F(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ei=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var Eb=ht,$b=Di,Ab=Pe,wb=Ab("match"),_b=function(i){var e;return Eb(i)&&((e=i[wb])!==void 0?!!e:$b(i)=="RegExp")},kb=Ni,Pb=String,Rb=function(i){if(kb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Pb(i)},Ib=pt,Db=function(){var i=Ib(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},Cb=Le,Ob=st,Lb=Os,xb=Db,No=RegExp.prototype,Nb=function(i){var e=i.flags;return e===void 0&&!("flags"in No)&&!Ob(i,"flags")&&Lb(No,i)?Cb(xb,i):e},Ja=Ue,Bb=Bs,Mb=Math.floor,Lr=Ja("".charAt),Ub=Ja("".replace),xr=Ja("".slice),Fb=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vb=/\$([$&'`]|\d{1,2})/g,Hb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,d=Vb;return r!==void 0&&(r=Bb(r),d=Fb),Ub(a,d,function(u,l){var c;switch(Lr(l,0)){case"$":return"$";case"&":return i;case"`":return xr(e,0,t);case"'":return xr(e,n);case"<":c=r[xr(l,1,-1)];break;default:var h=+l;if(h===0)return u;if(h>o){var f=Mb(h/10);return f===0?u:f<=o?s[f-1]===void 0?Lr(l,1):s[f-1]+Lr(l,1):u}c=s[h-1]}return c===void 0?"":c})},Gb=Qe,qb=Le,Ka=Ue,Bo=Ea,Yb=Te,jb=Ci,zb=_b,Wt=Rb,Wb=Ns,Qb=Nb,Jb=Hb,Kb=Pe,Xb=Kb("replace"),Zb=TypeError,Od=Ka("".indexOf),ey=Ka("".replace),Mo=Ka("".slice),ty=Math.max,Uo=function(i,e,t){return t>i.length?-1:e===""?t:Od(i,e,t)};Gb({target:"String",proto:!0},{replaceAll:function(e,t){var s=Bo(this),r,a,n,o,d,u,l,c,h,f=0,m=0,g="";if(!jb(e)){if(r=zb(e),r&&(a=Wt(Bo(Qb(e))),!~Od(a,"g")))throw Zb("`.replaceAll` does not allow non-global regexes");if(n=Wb(e,Xb),n)return qb(n,e,s,t);if(r)return ey(Wt(s),e,t)}for(o=Wt(s),d=Wt(e),u=Yb(t),u||(t=Wt(t)),l=d.length,c=ty(1,l),f=Uo(o,d,0);f!==-1;)h=u?Wt(t(d,f,o)):Jb(d,o,f,[],void 0,t),g+=Mo(o,m,f)+h,m=f+l,f=Uo(o,d,f+c);return m<o.length&&(g+=Mo(o,m)),g}});var iy=Ya,sy=iy("String","replaceAll"),ry=sy,ay=ry,ny=ay,oy=ny,Fo=oy;const Vo=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const d=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(d)?0:d)*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=Fo(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=Fo(t,n,(o,d)=>te(a)?o:te(d)?a:a.padStart(parseInt(d,10),"0"))}return t},uy=(i,e)=>{var t,s,r,a,n,o,d,u,l,c,h,f,m,g,b,v,S,A,E,$,C,Y,N,U,Q,B,x,Z,de,ge,P,G,ne,pe,be,Ie,Je,bt,K,Ee;const Ve=new DOMParser().parseFromString(i,"application/xml"),at={video:[],audio:[],text:[]},_t=Ve.children[0],yt=_t.getElementsByTagName("Period")[0],Vt=yt.children;let Ke;const li=_t.getAttribute("mediaPresentationDuration"),Xa=yt.getAttribute("duration");if(li)Ke=Vo(li);else if(Xa){const He=Vo(Xa);k(He)&&(Ke=He)}let Fd=0;const Ys=(s=(t=_t.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Vd=Ys.includes(Ps.WEBM_AS_IN_FFMPEG)||Ys.includes(Ps.WEBM_AS_IN_SPEC)?ni.WEBM:ni.MP4;for(const He of Vt){const Gi=He.getAttribute("mimeType"),Hd=He.getAttribute("codecs"),Za=(r=He.getAttribute("contentType"))!==null&&r!==void 0?r:Gi==null?void 0:Gi.split("/")[0],Gd=(n=(a=He.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],en=He.querySelectorAll("Representation"),qd=He.querySelector("SegmentTemplate");if(Za===Ae.TEXT){for(const me of en){const kt=me.getAttribute("id")||"",qi=He.getAttribute("lang"),Ht=(u=(d=(o=me.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",js=new URL(Ht,e).toString();at[Ae.TEXT].push({id:kt,lang:qi,kind:Ae.TEXT,url:js})}continue}for(const me of en){const kt=(l=me.getAttribute("mimeType"))!==null&&l!==void 0?l:Gi,qi=(h=(c=me.getAttribute("codecs"))!==null&&c!==void 0?c:Hd)!==null&&h!==void 0?h:"",Ht=(m=(f=me.getAttribute("contentType"))!==null&&f!==void 0?f:kt==null?void 0:kt.split("/")[0])!==null&&m!==void 0?m:Za,js=(b=(g=He.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&b!==void 0?b:[],Yd=parseInt((v=me.getAttribute("width"))!==null&&v!==void 0?v:"",10),tn=parseInt((S=me.getAttribute("height"))!==null&&S!==void 0?S:"",10),sn=parseInt((A=me.getAttribute("bandwidth"))!==null&&A!==void 0?A:"",10)/1e3,rn=(E=me.getAttribute("frameRate"))!==null&&E!==void 0?E:"",jd=($=me.getAttribute("quality"))!==null&&$!==void 0?$:void 0,zd=rn?Wa(rn):void 0,Wd=(C=me.getAttribute("id"))!==null&&C!==void 0?C:(Fd++).toString(10),Qd=Ht==="video"?`${tn}p`:Ht==="audio"?`${sn}Kbps`:qi,Jd=`${Wd}@${Qd}`,Kd=(U=(N=(Y=me.querySelector("BaseURL"))===null||Y===void 0?void 0:Y.textContent)===null||N===void 0?void 0:N.trim())!==null&&U!==void 0?U:"",an=new URL(Kd,e).toString(),Xd=[...Ys,...Gd,...js];let zs;const Zd=me.querySelector("SegmentBase"),Pt=(Q=me.querySelector("SegmentTemplate"))!==null&&Q!==void 0?Q:qd;if(Zd){const ci=(x=(B=me.querySelector("SegmentBase Initialization"))===null||B===void 0?void 0:B.getAttribute("range"))!==null&&x!==void 0?x:"",[hi,Qs]=ci.split("-").map(Rt=>parseInt(Rt,10)),fi={from:hi,to:Qs},pi=(Z=me.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[Js,Yi]=pi?pi.split("-").map(Rt=>parseInt(Rt,10)):[],vi=pi?{from:Js,to:Yi}:void 0;zs={type:Ne.BYTE_RANGE,url:an,initRange:fi,indexRange:vi}}else if(Pt){const ci={representationId:(de=me.getAttribute("id"))!==null&&de!==void 0?de:void 0,bandwidth:(ge=me.getAttribute("bandwidth"))!==null&&ge!==void 0?ge:void 0},hi=parseInt((P=Pt.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),Qs=(G=Pt.getAttribute("initialization"))!==null&&G!==void 0?G:"",fi=Pt.getAttribute("media"),pi=(pe=parseInt((ne=Pt.getAttribute("startNumber"))!==null&&ne!==void 0?ne:"",10))!==null&&pe!==void 0?pe:1,Js=Nr(Qs,ci);if(!fi)throw new ReferenceError("No media attribute in SegmentTemplate");const Yi=(be=Pt.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],vi=[];if(Yi.length){let Rt=pi,It=0;for(const mi of Yi){const Gt=parseInt((Ie=mi.getAttribute("d"))!==null&&Ie!==void 0?Ie:"",10)*1e3,Si=parseInt((Je=mi.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,gi=(K=parseInt((bt=mi.getAttribute("t"))!==null&&bt!==void 0?bt:"",10))!==null&&K!==void 0?K:void 0;for(let nn=0;nn<Si+1;nn++){const el=Nr(fi,Object.assign(Object.assign({},ci),{segmentNumber:Rt.toString(10),segmentTime:gi.toString(10)})),tl=gi?gi/hi:It;It+=Gt/hi;const il=It;Rt++,vi.push({time:{from:tl,to:il},url:el})}}}else if(k(Ke)){const It=parseInt((Ee=Pt.getAttribute("duration"))!==null&&Ee!==void 0?Ee:"",10)/hi*1e3,mi=Math.ceil(Ke/It);let Gt=0;for(let Si=1;Si<mi;Si++){const gi=Nr(fi,Object.assign(Object.assign({},ci),{segmentNumber:Si.toString(10),segmentTime:Gt.toString(10)}));vi.push({time:{from:Gt,to:Gt+It},url:gi}),Gt+=It}}zs={type:Ne.TEMPLATE,baseUrl:an,initUrl:Js,segments:vi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ht||!kt)continue;const Ws={video:Ae.VIDEO,audio:Ae.AUDIO,text:Ae.TEXT}[Ht];Ws&&at[Ws].push({id:Jd,kind:Ws,segmentReference:zs,profiles:Xd,duration:Ke,bitrate:sn,mime:kt,codecs:qi,width:Yd,height:tn,fps:zd,quality:jd})}}return{duration:Ke,container:Vd,representations:at}},dy=["timeupdate","progress","play","seeked","stalled","waiting"];var xe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(xe||(xe={}));let ly=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ae,this.state$=new le(xe.NONE),this.currentVideoRepresentation$=new T(void 0),this.error$=new L,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new Lt,this.initManifest=je(this.destroyController.signal,function(t,s){return ze(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_READY);const r=yield yield V(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield V(void 0);let a;try{a=uy(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield V(void 0);const n=({kind:o,mime:d,codecs:u})=>{var l,c,h;return Boolean(((l=t.canPlayType)===null||l===void 0?void 0:l.call(t,d))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${d}; codecs="${u}"`))||o===Ae.TEXT)};this.manifest=Object.assign(Object.assign({},a),{representations:Bi(Object.entries(a.representations).map(([o,d])=>[o,d.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=je(this.destroyController.signal,function(t,s){return ze(this,arguments,function*(){R(this.manifest),R(this.element),this.state$.startTransitionTo(xe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new xo(Ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(s)&&(this.audioBufferManager=new xo(Ae.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=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(H(this.forceEnded$,it({allBuffersFull:a,someBufferEnded:n}).pipe(ie(({allBuffersFull:o,someBufferEnded:d})=>o&&d))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield V(new Promise(o=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",o)}))),k(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&k(s)?yield yield V(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield V(this.videoBufferManager.startWith(t)),this.state$.setState(xe.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=ul(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Tb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(xe.RUNNING),this.subscription.add(H(...dy.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ba(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={[Ae.VIDEO]:this.videoBufferManager,[Ae.AUDIO]:this.audioBufferManager,[Ae.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;R(this.element),R(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=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),ba(this.element.buffered,d)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(d),(o=this.audioBufferManager)===null||o===void 0||o.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(xe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const 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 ce;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ce||(ce={}));const cy=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Vi(a):void 0)!==null&&n!==void 0?n:Nt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},hy=({id:i,bitrate:e})=>({id:i,bitrate:e}),fy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),py=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=nt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:nt(i,-1)};class vy{constructor(e){this.subscription=new ae,this.videoState=new le(ce.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new rt,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Bg,this.textTracks=[],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===z.Requested&&(r==null?void 0:r.to)!==p.PAUSED&&t!==ce.STOPPED&&s!==p.STOPPED&&this.seek(a.position,a.forcePrecise),s===p.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(t){case ce.STOPPED:this.videoState.startTransitionTo(ce.READY),this.prepare();return;case ce.READY:s===p.PAUSED?(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case ce.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}}},this.params=e,this.video=mt(e.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 ly({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=gt(this.video),r=u=>{e.error$.next({id:"DashVKProvider",category:D.WTF,message:"DashVKProvider internal logic error",thrown:u})},a=(u,l)=>this.subscription.add(u.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(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(ie(k),ye()),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(At(this.video,t.playbackRate,s.playbackRateState$,r)),a(_s(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),I(t.playbackState,p.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var l;if(u===xe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((b,v)=>v.bitrate-b.bitrate),f=Array.from(c.video).sort((b,v)=>v.bitrate-b.bitrate),m=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(const b of h){const v=hy(b);v&&this.audioTracks.push({track:v,representation:b})}for(const b of f){const v=cy(b);if(v){this.videoTracks.push({track:v,representation:b});const S=!this.params.tuning.isAudioDisabled&&py(h,f,b);S&&this.audioRepresentations.set(b.id,S)}}for(const b of m){const v=fy(b);v&&this.textTracks.push({track:v,representation:b})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const g=this.selectVideoRepresentation();R(g),this.player.initRepresentations(g.id,(l=this.audioRepresentations.get(g.id))===null||l===void 0?void 0:l.id)}else u===xe.REPRESENTATIOS_READY&&(this.videoState.setState(ce.READY),this.player.initBuffer())},r));const n=u=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),l=this.player.state$.getTransition();if(u!==xe.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Ae.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Ae.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(u=>{var l;return u&&((l=this.videoTracks.find(({representation:{id:c}})=>c===u))===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:u})=>u===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const d=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:v}})=>v===d))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=Ot(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(u&&!o&&(s=(t=this.audioRepresentations.get(u.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),g=Fi(this.videoTracks.map(({track:v})=>v),{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}),b=o?g!=null?g:u:u!=null?u:g;return b&&((n=this.videoTracks.find(({track:v})=>v===b))===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.player.destroy(),this.params.output.element$.next(void 0),St(this.video)}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const my=5e3,Ze={};var X;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const $i=(i,e)=>new Ds(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class Sy{constructor(e){this.subscription=new ae,this.videoState=new le(X.INITIALIZING),this.textTracksManager=new rt,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!==X.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:F(t)}break;case p.READY:switch(t){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:F(t)}break;case p.PLAYING:switch(t){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:F(t)}break;case p.PAUSED:switch(t){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case X.PLAYING:this.pause();break;default:F(t)}break;default:F(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(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.params.output.element$.next(void 0),St(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),my);Hs(import("hls.js").then(r=>{e||(Ze.Hls=r.default,Ze.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(Ze.Hls,"hls.js not loaded"),this.hls=new Ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){R(Ze.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=gt(this.video),a=(u,l)=>this.subscription.add(u.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$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),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(At(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add($i(this.hls,Ze.Events.ERROR).subscribe(u=>{var l;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:D.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(l=u.err)===null||l===void 0?void 0:l.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),I(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),I(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),a($i(this.hls,Ze.Events.MANIFEST_PARSED).pipe(_(({levels:u})=>u.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:g,height:b}=c,v=(f=Vi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Nt({width:g,height:b});if(!v)return l;const S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:m.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:g,height:b},fps:S};return this.trackLevels.set(m,{track:A,level:c}),l.push(A),l},[]))),t.availableVideoTracks$),a($i(this.hls,Ze.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const l=[];for(const c of u.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,g="internal";l.push({id:h,url:f,language:m,type:g})}e.internalTextTracks.startTransitionTo(l)}}),a($i(this.hls,Ze.Events.LEVEL_LOADING).pipe(_(({url:u})=>Re(u))),t.hostname$),this.subscription.add(We(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const n=u=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===u))===null||l===void 0?void 0:l.track},o=$i(this.hls,Ze.Events.LEVEL_SWITCHED).pipe(_(({level:u})=>n(this.hls.levels[u])));o.pipe(ie(k)).subscribe(t.currentVideoTrack$,s),this.subscription.add(We(e.videoTrack,()=>{var u;return(u=n(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var l;if(te(u))return;const c=(l=this.trackLevels.get(u))===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(_(u=>u==null?void 0:u.id)),onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(X.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(X.PLAYING),(yield wt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:t})))||(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(X.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(X.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const Ho="X-Playback-Duration";var Go=i=>ue(void 0,void 0,void 0,function*(){const e=yield ri(i,{method:"HEAD"});return e.headers.has(Ho)?parseInt(e.headers.get(Ho),10):void 0});const gy=i=>{let e=null;if(i.QUALITY&&(e=Vi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Nt({width:t,height:s})}return e!=null?e:null},Ld=(i,e=i)=>ue(void 0,void 0,void 0,function*(){var t;const a=(yield(yield ri(i)).text()).split(`
|
|
8
|
+
`),n=[];for(let o=0;o<a.length;o++){const u=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const l=Bi(u[1].split(",").map(v=>v.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=gy(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 g;if(l.RESOLUTION){const[v,S]=l.RESOLUTION.split("x").map(A=>parseInt(A,10));v&&S&&(g={width:v,height:S})}const b=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:b,bandwidth:f,size:g,fps:m})}return n});var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(se||(se={}));class by{constructor(e){var t;this.subscription=new ae,this.videoState=new le(se.STOPPED),this.textTracksManager=new rt,this.manifests$=new T([]),this.liveOffset=new za,this.manifestStartTime$=new T(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o||d){const c=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested){this.videoState.startTransitionTo(se.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case se.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return F(r)}},this.params=e,this.video=mt(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:qe.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Ld(si(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),this.maxSeekBackTime$=new T((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",d=this.manifests$.getValue();if(!d)return;const u=a?"master":o;return a&&!n&&r.startTransitionTo("master"),d.find(l=>l.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=gt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),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(At(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),I(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&k(u.to)){const c=u.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),d&&d.from===se.CHANGING_MANIFEST&&this.videoState.setState(d.to),o&&o.state===z.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,d,u;const l=(u=(d=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||d===void 0?void 0:d.call(o))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(l||void 0)},s)),this.subscription.add(it({startTime:this.manifestStartTime$.pipe(ie(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),s)),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:h})=>({id:d,quality:u,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Oe(["init"])).pipe(Be(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();if(te(e))return;const t=si(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Go(t).then(s=>{var r;if(!te(s))this.maxSeekBackTime$.next(s);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(te(a)||!isFinite(a))try{ri(t).then(n=>n.text()).then(n=>{var o;const d=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(d){const u=new URL(d,t).toString();Go(u).then(l=>{te(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(oe||(oe={}));class yy{constructor(e){this.subscription=new ae,this.videoState=new le(oe.STOPPED),this.textTracksManager=new rt,this.manifests$=new T([]),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===p.STOPPED){s!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),u.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&u.state===z.Requested&&this.seek(u.position),s){case oe.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return F(s)}},this.params=e,this.video=mt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:qe.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)),Ld(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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",d=this.manifests$.getValue();if(!d)return;const u=a?"master":o;return a&&!n&&r.startTransitionTo("master"),d.find(l=>l.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=gt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(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(At(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),I(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&k(u.to)){const c=u.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),d&&d.from===oe.CHANGING_MANIFEST&&this.videoState.setState(d.to),o.state===z.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:h})=>({id:d,quality:u,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();te(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));class Ty{constructor(e){this.subscription=new ae,this.videoState=new le(he.STOPPED),this.trackUrls={},this.textTracksManager=new rt,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(n){const{currentTime:d}=this.video;this.prepare(),o.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==p.PAUSED&&o.state===z.Requested&&this.seek(o.position),t){case he.READY:s===p.READY?I(this.params.desiredState.playbackState,p.READY):s===p.PAUSED?(this.videoState.setState(he.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case he.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(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:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=gt(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),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(At(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),I(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),I(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===he.READY&&this.videoState.setState(he.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&k(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),St(this.video)}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();R(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];R(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=ai(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Re(r))}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const qo=["stun:videostun.mycdn.me:80"],Ey=1e3,$y=3,Br=()=>null;class Ay{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Br,this.externalStopCallback=Br,this.externalErrorCallback=Br,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:qo}]};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:D.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),Ey)}normalizeOptions(e={}){const t={stunServerList:qo,maxRetryNumber:$y,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(re||(re={}));class wy{constructor(e){this.videoState=new le(re.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case re.READY:s===p.PAUSED?(this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return F(t)}},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=mt(e.container),this.liveStreamClient=new Ay(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),St(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(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=gt(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)===re.READY&&this.videoState.setState(re.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(re.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 re.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case re.READY:break;case re.PAUSED:t.playbackState.setState(p.PAUSED);break;case re.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return F(n.to)}},s)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Be(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:qe.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(re.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){wt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Yo{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 Mr,Ur,Fr,Vr,Hr,Gr,us,qr,ds,Yr,ls,jr,cs,zr,hs,Wr,fs,Qr;const xd=Is().device===su.Android,Et=document.createElement("video"),_y='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ky='video/mp4; codecs="hev1.1.6.L93.B0"',Nd='video/webm; codecs="vp09.00.10.08"',Bd='video/webm; codecs="av01.0.00M.08"',Py='audio/mp4; codecs="mp4a.40.2"',Ry='audio/webm; codecs="opus"',Ge={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Ur=(Mr=window.SourceBuffer)===null||Mr===void 0?void 0:Mr.prototype)===null||Ur===void 0?void 0:Ur.appendBuffer)),hls:Boolean(((Fr=Et.canPlayType)===null||Fr===void 0?void 0:Fr.call(Et,"application/x-mpegurl"))||((Vr=Et.canPlayType)===null||Vr===void 0?void 0:Vr.call(Et,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},De={mp4:Boolean((Hr=Et.canPlayType)===null||Hr===void 0?void 0:Hr.call(Et,"video/mp4")),webm:Boolean((Gr=Et.canPlayType)===null||Gr===void 0?void 0:Gr.call(Et,"video/webm")),cmaf:!0},tt={h264:Boolean((qr=(us=window.MediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||qr===void 0?void 0:qr.call(us,_y)),h265:Boolean((Yr=(ds=window.MediaSource)===null||ds===void 0?void 0:ds.isTypeSupported)===null||Yr===void 0?void 0:Yr.call(ds,ky)),vp9:Boolean((jr=(ls=window.MediaSource)===null||ls===void 0?void 0:ls.isTypeSupported)===null||jr===void 0?void 0:jr.call(ls,Nd)),av1:Boolean((zr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||zr===void 0?void 0:zr.call(cs,Bd)),aac:Boolean((Wr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||Wr===void 0?void 0:Wr.call(hs,Py)),opus:Boolean((Qr=(fs=window.MediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||Qr===void 0?void 0:Qr.call(fs,Ry))},Qt=(tt.h264||tt.h265)&&tt.aac;var ot;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ot||(ot={}));let Ct;const Iy=()=>ue(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Bd})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Nd})}))]);Ct={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{Iy()}catch(i){console.error(i)}const qs=Ge.hls&&De.mp4,Dy=()=>Object.keys(tt).filter(i=>tt[i]),Cy=(i,e=!1)=>i.filter(t=>{switch(t){case y.DASH:return Ge.mse&&De.mp4&&Qt;case y.DASH_SEP:return Ge.mse&&De.mp4&&Qt;case y.DASH_WEBM:return Ge.mse&&De.webm&&tt.vp9&&tt.opus;case y.DASH_WEBM_AV1:return Ge.mse&&De.webm&&tt.av1&&tt.opus;case y.DASH_LIVE:return Ge.mse&&De.mp4&&Qt;case y.DASH_LIVE_CMAF:return Ge.mse&&De.mp4&&Qt&&De.cmaf;case y.DASH_ONDEMAND:return Ge.mse&&De.mp4&&Qt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return qs||e&&Ge.mse&&De.mp4&&Qt;case y.MPEG:return De.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ge.webrtc&&Ge.ws&&tt.h264&&(De.mp4||De.webm);default:return F(t)}}),Jr=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case ot.VP9:return[e,t];case ot.AV1:return[t,e];case ot.NONE:return[];case ot.SMOOTH:return Ct?Ct[t].smooth?[t,e]:Ct[e].smooth?[e,t]:[t,e]:[e,t];case ot.POWER_EFFICIENT:return Ct?Ct[t].powerEfficient?[t,e]:Ct[e].powerEfficient?[e,t]:[t,e]:[e,t];default:F(i)}return[e,t]},Oy=(i=ot.VP9)=>xd?[y.MPEG,...Jr(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:qs?[...Jr(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...Jr(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],Ly=()=>xd?[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],jo=i=>i?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var xy=i=>new Ds(e=>{const t=new ae,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:u,to:l})=>`${u}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(_(({type:u})=>u!==void 0)),n=new L;let o=0,d="unknown";return t.add(s.subscribe(u=>{o&&window.clearTimeout(o),d=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(a.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const zo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Ny={cacheDuration:12e4},By={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},My={maxPausedTime:3e4},Wo={maxPausedTime:3e4};class Uy{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new T(void 0),liveTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0)},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Cy([...Ly(),...Oy(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(o=>k(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.screenFormatsIterator=new Yo(a);const n=[...jo(!0),...jo(!1)];this.chromecastFormatsIterator=new Yo(n.filter(o=>k(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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(te(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,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!==z.None;this.params.desiredState.seekState.setState({state:z.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 we.SCREEN:return this.createScreenProvider(t);case we.CHROMECAST:return this.createChromecastProvider(t);default:return F(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 R(o),new nb(Object.assign(Object.assign({},n),{source:o,config:Ny}))}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Ro(Object.assign(Object.assign({},n),{source:o,format:e,config:Wo})):new vy(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Ro(Object.assign(Object.assign({},n),{source:o,format:e,config:Wo}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),qs||!this.params.tuning.useHlsJs?new yy(Object.assign(Object.assign({},n),{source:o})):new Sy(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new by(Object.assign(Object.assign({},n),{source:o,config:My}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new Ty(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new tb(Object.assign(Object.assign({},n),{source:o,config:By}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new wy({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 F(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 R(o),new ng({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()?we.CHROMECAST:we.SCREEN}chooseFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case we.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return F(e)}}skipFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.next();case we.CHROMECAST:return this.chromecastFormatsIterator.next();default:return F(e)}}handleNoFormatsError(e){switch(e){case we.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case we.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return F(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 Bi(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,s=0;return e.add(H(this.providerOutput.error$,xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:zo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(r=>({id:`ProviderHangup:${r}`,category:D.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ie(({to:a})=>a===p.PLAYING),ye()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===we.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(we.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===D.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<zo.providerErrorLimit;o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:we.SCREEN)}})),e}}const ya=(i,e,t)=>t*e+(1-t)*i,Md=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Fy=(i,e,t,s)=>{let r=0,a=t;const n=Md(i,e),o=e<s?e:s;for(let d=0;d<o;d++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class Ud{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 T(e.initial),this.debounced$=new T(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new et(`raw_${s}`),this.smoothedSeries$=new et(`smoothed_${s}`),this.reportedSeries$=new et(`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)&&(te(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 Vy extends Ud{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ya(this.slow,e,this.params.emaAlphaSlow),this.fast=ya(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Hy extends Ud{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Md(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ya(this.emaSmoothed,e,this.params.emaAlpha);const s=Fy(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 Vy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Hy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Gy=5e3,Jo="one_video_throughput",Ko="one_video_rtt",ct=window.navigator.connection,Xo=()=>{const i=ct==null?void 0:ct.downlink;if(k(i)&&i!==10)return i*1e3},Zo=()=>{const i=ct==null?void 0:ct.rtt;if(k(i)&&i!==3e3)return i},eu=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class ki{constructor(e){var t,s;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ki.load(Jo)||(e.useBrowserEstimation?Xo():void 0)||Gy,a=(s=(t=ki.load(Ko))!==null&&t!==void 0?t:e.useBrowserEstimation?Zo():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(eu(r,a,e.rttPenaltyRequestSize)),this.throughput=Qo.getSmoothedValue(r,-1,e),this.rtt=Qo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const d=Xo();d&&this.throughput.next(d);const u=Zo();k(u)&&this.rtt.next(u)};ct&&"onchange"in ct&&this.subscription.add(M(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Xs.set(Jo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Xs.set(Ko,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(it({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>eu(n,o,e.rttPenaltyRequestSize)),ie(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=fe();const r=new ae;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(M(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=fe()}));break;case 1:case 0:r.add(M(e,"loadstart").subscribe(()=>{t=0,s=fe()}));break}r.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=fe(),d=n-t,u=o-s;this.addRawSpeed(d,u,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=fe();let a=0,n=fe();const o=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:l})=>ue(this,void 0,void 0,function*(){u?(this.addRawSpeed(s,fe()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&fe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,fe()-n,this.concurrentDownloads.size),a=0,n=fe()),yield t==null?void 0:t.read().then(d,o))});this.concurrentDownloads.add(e),t==null||t.read().then(d,o)}addRawSpeed(e,t,s=1){if(ki.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=Xs.get(e);if(k(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const tu={configName:["core"],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,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:ot.VP9,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}},qy=i=>{const e={};for(const t of Object.keys(tu)){const s=tu[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?t==="configName"?e[t]=[...r,...s]: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 iu=({seekState:i,position$:e})=>H(i.stateChangeEnded$.pipe(_(({to:t})=>{var s;return t.state===z.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ie(k)),e.pipe(ie(()=>i.getState().state===z.None))),Yy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return R(e,`Wrong container or containerId {${i.container}}`),e};class Ky{constructor(e={configName:[]}){if(this.subscription=new ae,this.logger=new dl,this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(p.STOPPED),seekState:new le({state:z.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([]),internalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),atLiveEdge$:new T(void 0),liveTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(Tt.NONE),chromecastState$:new T($e.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0)},this.events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Lg},this.initLogs(),this.tuning=qy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new pl({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ki(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 d=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),u=`Player.${String(s)}`,l=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:D.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=Yy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Uy({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(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==p.PLAYING&&e.startTransitionTo(p.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.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){R(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;R(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(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(te(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===z.None?void 0:t.position;return k(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(H(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(ie(({from:e})=>e===p.STOPPED),ye()).subscribe(()=>{this.initedAt=fe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:z.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,d)=>bs(o)?1:bs(d)?-1:ps(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const d of n)d.fps&&(o[d.quality]=d.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(it({isLive:e.providerOutput.isLive$,position:iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o})=>n&&o>-ll),ve()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),ve()).subscribe(this.info.volume$)).add(iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(ii(!0)),e.providerOutput.seekedEvent$.pipe(ii(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:D.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"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(),_(n=>n!=null?n:fe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ye(),_(()=>fe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ye(),_(()=>fe()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new T(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ie(({to:n})=>n===p.PLAYING),ye()).subscribe(()=>s.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,s).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(d=n==null?void 0:n.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let l;u===$e.CONNECTED?l=Tt.SECOND_SCREEN:d?n?l=Tt.PIP:o?l=Tt.FULLSCREEN:l=Tt.INLINE:l=Tt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ae;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ie(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=Fi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(H(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),Og(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Cg(s)),this.providerContainer.current$.subscribe(({type:s})=>as("provider",s)),t.duration$.subscribe(s=>as("duration",s)),t.availableVideoTracks$.pipe(ie(s=>!!s.length),ye()).subscribe(s=>as("tracks",s)),this.events.fatalError$.subscribe(new et("fatalError")),this.events.managedError$.subscribe(new et("managedError")),t.position$.subscribe(new et("position")),t.currentVideoTrack$.pipe(_(s=>s==null?void 0:s.quality)).subscribe(new et("quality")),this.info.currentBuffer$.subscribe(new et("buffer")),t.isBuffering$.subscribe(new et("isBuffering"))].forEach(s=>this.subscription.add(s)),as("codecs",Dy())}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=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})});this.subscription.add(H(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const Xy=`@vkontakte/videoplayer-core@${hl}`;export{$e as ChromecastState,Pi as HttpConnectionType,tT as Observable,p as PlaybackState,Ky as Player,Xy as SDK_VERSION,iT as Subject,sT as Subscription,Tt as Surface,hl as VERSION,rT as ValueSubject,y as VideoFormat,aT as VideoQuality};
|