@vkontakte/videoplayer-core 2.0.98-dev.489417ae.0 → 2.0.98-dev.508d1c24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.98-dev.489417ae.0
3
- * Thu, 15 Feb 2024 17:01:30 GMT
2
+ * @vkontakte/videoplayer-core v2.0.98-dev.508d1c24.0
3
+ * Thu, 15 Feb 2024 19:37:08 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
5
5
  */
6
- import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as I,ErrorCategory as R,isNullable as W,fromEvent as V,assertNever as z,merge as G,tap as Bs,map as P,observableFrom as We,filterChanged as ye,assertNonNullable as D,debounce as lt,getHighestQuality as fc,timeout as pc,getCurrentBrowser as jr,CurrentClientBrowser as Xn,combine as Be,once as _e,mapTo as ss,filter as oe,now as he,assertNotEmptyArray as mc,videoSizeToQuality as ci,isInvariantQuality as Ii,isHigher as ts,isLower as $r,isHigherOrEqual as An,isLowerOrEqual as Tu,Observable as Yr,debounceFn as vc,interval as Ri,VideoQuality as ft,videoQualityToHeight as gc,abortable as fe,getExponentialDelay as Ls,throttle as Sc,isIOS as bc,CurrentClientDevice as yc,safeStorage as ya,fillWithDefault as Tc,Logger as Ec}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as WE,Subject as QE,Subscription as KE,ValueSubject as JE,VideoQuality as XE}from"@vkontakte/videoplayer-shared/es2015.esm.js";const $c="2.0.98-dev.489417ae.0";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Ye;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ye||(Ye={}));var Ne;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ne||(Ne={}));var Ms;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ms||(Ms={}));var ie;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ie||(ie={}));var ni;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(ni||(ni={}));function J(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function _(s){return this instanceof _?(this.v=s,this):new _(s)}function pe(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(p,S){a.push([h,f,p,S])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(p){c(a[0][3],p)}}function u(h){h.value instanceof _?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Ac=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class wc{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ne.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new T(Ne.NOT_AVAILABLE),this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=I((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Ac("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){I(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(V(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return z(r.sessionState)}})).add(G(V(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Bs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),P(r=>r.castState)),We([i.getCastState()])).pipe(ye(),P(kc),Bs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ne.CONNECTED,o=I(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();D(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(W(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ne.CONNECTED?I(this.connection$.getValue())?Ne.CONNECTED:Ne.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const kc=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ne.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ne.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ne.CONNECTING;case cast.framework.CastState.CONNECTED:return Ne.CONNECTED;default:return z(s)}};var Ta=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function zr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bt=function(s){try{return!!s()}catch(e){return!0}},_c=bt,qr=!_c(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Eu=qr,$u=Function.prototype,wn=$u.call,Pc=Eu&&$u.bind.bind(wn,wn),yt=Eu?Pc:function(s){return function(){return wn.apply(s,arguments)}},Au=yt,Dc=Au({}.toString),Ic=Au("".slice),Hs=function(s){return Ic(Dc(s),8,-1)},Rc=yt,Lc=bt,xc=Hs,Ea=Object,Cc=Rc("".split),Oc=Lc(function(){return!Ea("z").propertyIsEnumerable(0)})?function(s){return xc(s)=="String"?Cc(s,""):Ea(s)}:Ea,Gs=function(s){return s==null},Bc=Gs,Mc=TypeError,Zn=function(s){if(Bc(s))throw Mc("Can't call method on "+s);return s},Nc=Oc,Fc=Zn,js=function(s){return Nc(Fc(s))},us={},er=function(s){return s&&s.Math==Math&&s},Ve=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof Ta=="object"&&Ta)||function(){return this}()||Ta||Function("return this")(),kn=typeof document=="object"&&document.all,Uc=typeof kn=="undefined"&&kn!==void 0,wu={all:kn,IS_HTMLDDA:Uc},ku=wu,Vc=ku.all,Re=ku.IS_HTMLDDA?function(s){return typeof s=="function"||s===Vc}:function(s){return typeof s=="function"},Hc=Ve,Gc=Re,Io=Hc.WeakMap,jc=Gc(Io)&&/native code/.test(String(Io)),Ro=Re,_u=wu,Yc=_u.all,ei=_u.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ro(s)||s===Yc}:function(s){return typeof s=="object"?s!==null:Ro(s)},zc=bt,hi=!zc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Oi={},qc=Ve,Lo=ei,_n=qc.document,Wc=Lo(_n)&&Lo(_n.createElement),eo=function(s){return Wc?_n.createElement(s):{}},Qc=hi,Kc=bt,Jc=eo,Pu=!Qc&&!Kc(function(){return Object.defineProperty(Jc("div"),"a",{get:function(){return 7}}).a!=7}),Xc=hi,Zc=bt,Du=Xc&&Zc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),eh=ei,th=String,ih=TypeError,ti=function(s){if(eh(s))return s;throw ih(th(s)+" is not an object")},sh=qr,tr=Function.prototype.call,ct=sh?tr.bind(tr):function(){return tr.apply(tr,arguments)},to={},$a=to,Aa=Ve,rh=Re,xo=function(s){return rh(s)?s:void 0},Bi=function(s,e){return arguments.length<2?xo($a[s])||xo(Aa[s]):$a[s]&&$a[s][e]||Aa[s]&&Aa[s][e]},ah=yt,Wr=ah({}.isPrototypeOf),Qr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Iu=Ve,wa=Qr,Co=Iu.process,Oo=Iu.Deno,Bo=Co&&Co.versions||Oo&&Oo.version,Mo=Bo&&Bo.v8,wt,Pr;Mo&&(wt=Mo.split("."),Pr=wt[0]>0&&wt[0]<4?1:+(wt[0]+wt[1]));!Pr&&wa&&(wt=wa.match(/Edge\/(\d+)/),(!wt||wt[1]>=74)&&(wt=wa.match(/Chrome\/(\d+)/),wt&&(Pr=+wt[1])));var Ru=Pr,No=Ru,nh=bt,oh=Ve,dh=oh.String,Lu=!!Object.getOwnPropertySymbols&&!nh(function(){var s=Symbol();return!dh(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&No&&No<41}),uh=Lu,xu=uh&&!Symbol.sham&&typeof Symbol.iterator=="symbol",lh=Bi,ch=Re,hh=Wr,fh=xu,ph=Object,Cu=fh?function(s){return typeof s=="symbol"}:function(s){var e=lh("Symbol");return ch(e)&&hh(e.prototype,ph(s))},mh=String,Kr=function(s){try{return mh(s)}catch(e){return"Object"}},vh=Re,gh=Kr,Sh=TypeError,Mi=function(s){if(vh(s))return s;throw Sh(gh(s)+" is not a function")},bh=Mi,yh=Gs,Jr=function(s,e){var t=s[e];return yh(t)?void 0:bh(t)},ka=ct,_a=Re,Pa=ei,Th=TypeError,Eh=function(s,e){var t,i;if(e==="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s))||_a(t=s.valueOf)&&!Pa(i=ka(t,s))||e!=="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s)))return i;throw Th("Can't convert object to primitive value")},Ou={exports:{}},$h=!0,Fo=Ve,Ah=Object.defineProperty,wh=function(s,e){try{Ah(Fo,s,{value:e,configurable:!0,writable:!0})}catch(t){Fo[s]=e}return e},kh=Ve,_h=wh,Uo="__core-js_shared__",Ph=kh[Uo]||_h(Uo,{}),io=Ph,Vo=io;(Ou.exports=function(s,e){return Vo[s]||(Vo[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Bu=Ou.exports,Dh=Zn,Ih=Object,Xr=function(s){return Ih(Dh(s))},Rh=yt,Lh=Xr,xh=Rh({}.hasOwnProperty),Mt=Object.hasOwn||function(e,t){return xh(Lh(e),t)},Ch=yt,Oh=0,Bh=Math.random(),Mh=Ch(1 .toString),Mu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Mh(++Oh+Bh,36)},Nh=Ve,Fh=Bu,Ho=Mt,Uh=Mu,Vh=Lu,Hh=xu,Ki=Nh.Symbol,Da=Fh("wks"),Gh=Hh?Ki.for||Ki:Ki&&Ki.withoutSetter||Uh,Ke=function(s){return Ho(Da,s)||(Da[s]=Vh&&Ho(Ki,s)?Ki[s]:Gh("Symbol."+s)),Da[s]},jh=ct,Go=ei,jo=Cu,Yh=Jr,zh=Eh,qh=Ke,Wh=TypeError,Qh=qh("toPrimitive"),Kh=function(s,e){if(!Go(s)||jo(s))return s;var t=Yh(s,Qh),i;if(t){if(e===void 0&&(e="default"),i=jh(t,s,e),!Go(i)||jo(i))return i;throw Wh("Can't convert object to primitive value")}return e===void 0&&(e="number"),zh(s,e)},Jh=Kh,Xh=Cu,so=function(s){var e=Jh(s,"string");return Xh(e)?e:e+""},Zh=hi,ef=Pu,tf=Du,ir=ti,Yo=so,sf=TypeError,Ia=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,Ra="enumerable",La="configurable",xa="writable";Oi.f=Zh?tf?function(e,t,i){if(ir(e),t=Yo(t),ir(i),typeof e=="function"&&t==="prototype"&&"value"in i&&xa in i&&!i[xa]){var r=rf(e,t);r&&r[xa]&&(e[t]=i.value,i={configurable:La in i?i[La]:r[La],enumerable:Ra in i?i[Ra]:r[Ra],writable:!1})}return Ia(e,t,i)}:Ia:function(e,t,i){if(ir(e),t=Yo(t),ir(i),ef)try{return Ia(e,t,i)}catch(r){}if("get"in i||"set"in i)throw sf("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Zr=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},af=hi,nf=Oi,of=Zr,Ys=af?function(s,e,t){return nf.f(s,e,of(1,t))}:function(s,e,t){return s[e]=t,s},df=Bu,uf=Mu,zo=df("keys"),ro=function(s){return zo[s]||(zo[s]=uf(s))},ao={},lf=jc,Nu=Ve,cf=ei,hf=Ys,Ca=Mt,Oa=io,ff=ro,pf=ao,qo="Object already initialized",Pn=Nu.TypeError,mf=Nu.WeakMap,Dr,Ns,Ir,vf=function(s){return Ir(s)?Ns(s):Dr(s,{})},gf=function(s){return function(e){var t;if(!cf(e)||(t=Ns(e)).type!==s)throw Pn("Incompatible receiver, "+s+" required");return t}};if(lf||Oa.state){var It=Oa.state||(Oa.state=new mf);It.get=It.get,It.has=It.has,It.set=It.set,Dr=function(s,e){if(It.has(s))throw Pn(qo);return e.facade=s,It.set(s,e),e},Ns=function(s){return It.get(s)||{}},Ir=function(s){return It.has(s)}}else{var Hi=ff("state");pf[Hi]=!0,Dr=function(s,e){if(Ca(s,Hi))throw Pn(qo);return e.facade=s,hf(s,Hi,e),e},Ns=function(s){return Ca(s,Hi)?s[Hi]:{}},Ir=function(s){return Ca(s,Hi)}}var Fu={set:Dr,get:Ns,has:Ir,enforce:vf,getterFor:gf},Sf=qr,Uu=Function.prototype,Wo=Uu.apply,Qo=Uu.call,Vu=typeof Reflect=="object"&&Reflect.apply||(Sf?Qo.bind(Wo):function(){return Qo.apply(Wo,arguments)}),bf=Hs,yf=yt,Hu=function(s){if(bf(s)==="Function")return yf(s)},no={},Gu={},ju={}.propertyIsEnumerable,Yu=Object.getOwnPropertyDescriptor,Tf=Yu&&!ju.call({1:2},1);Gu.f=Tf?function(e){var t=Yu(this,e);return!!t&&t.enumerable}:ju;var Ef=hi,$f=ct,Af=Gu,wf=Zr,kf=js,_f=so,Pf=Mt,Df=Pu,Ko=Object.getOwnPropertyDescriptor;no.f=Ef?Ko:function(e,t){if(e=kf(e),t=_f(t),Df)try{return Ko(e,t)}catch(i){}if(Pf(e,t))return wf(!$f(Af.f,e,t),e[t])};var If=bt,Rf=Re,Lf=/#|\.prototype\./,zs=function(s,e){var t=Cf[xf(s)];return t==Bf?!0:t==Of?!1:Rf(e)?If(e):!!e},xf=zs.normalize=function(s){return String(s).replace(Lf,".").toLowerCase()},Cf=zs.data={},Of=zs.NATIVE="N",Bf=zs.POLYFILL="P",zu=zs,Jo=Hu,Mf=Mi,Nf=qr,Ff=Jo(Jo.bind),ea=function(s,e){return Mf(s),e===void 0?s:Nf?Ff(s,e):function(){return s.apply(e,arguments)}},sr=Ve,Uf=Vu,Vf=Hu,Hf=Re,Gf=no.f,jf=zu,Gi=to,Yf=ea,ji=Ys,Xo=Mt,zf=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Uf(s,this,arguments)};return e.prototype=s.prototype,e},_t=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?sr:r?sr[t]:(sr[t]||{}).prototype,o=i?Gi:Gi[t]||ji(Gi,t,{})[t],u=o.prototype,d,l,c,h,f,p,S,b,g;for(h in e)d=jf(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Xo(n,h),p=o[h],l&&(s.dontCallGetSet?(g=Gf(n,h),S=g&&g.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof p==typeof f)&&(s.bind&&l?b=Yf(f,sr):s.wrap&&l?b=zf(f):a&&Hf(f)?b=Vf(f):b=f,(s.sham||f&&f.sham||p&&p.sham)&&ji(b,"sham",!0),ji(o,h,b),a&&(c=t+"Prototype",Xo(Gi,c)||ji(Gi,c,{}),ji(Gi[c],h,f),s.real&&u&&(d||!u[h])&&ji(u,h,f)))},Dn=hi,qf=Mt,qu=Function.prototype,Wf=Dn&&Object.getOwnPropertyDescriptor,oo=qf(qu,"name"),Qf=oo&&function(){}.name==="something",Kf=oo&&(!Dn||Dn&&Wf(qu,"name").configurable),Jf={EXISTS:oo,PROPER:Qf,CONFIGURABLE:Kf},Wu={},Xf=Math.ceil,Zf=Math.floor,ep=Math.trunc||function(e){var t=+e;return(t>0?Zf:Xf)(t)},tp=ep,uo=function(s){var e=+s;return e!==e||e===0?0:tp(e)},ip=uo,sp=Math.max,rp=Math.min,ap=function(s,e){var t=ip(s);return t<0?sp(t+e,0):rp(t,e)},np=uo,op=Math.min,dp=function(s){return s>0?op(np(s),9007199254740991):0},up=dp,lo=function(s){return up(s.length)},lp=js,cp=ap,hp=lo,Zo=function(s){return function(e,t,i){var r=lp(e),a=hp(r),n=cp(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fp={includes:Zo(!0),indexOf:Zo(!1)},pp=yt,Ba=Mt,mp=js,vp=fp.indexOf,gp=ao,ed=pp([].push),Sp=function(s,e){var t=mp(s),i=0,r=[],a;for(a in t)!Ba(gp,a)&&Ba(t,a)&&ed(r,a);for(;e.length>i;)Ba(t,a=e[i++])&&(~vp(r,a)||ed(r,a));return r},Qu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bp=Sp,yp=Qu,Tp=Object.keys||function(e){return bp(e,yp)},Ep=hi,$p=Du,Ap=Oi,wp=ti,kp=js,_p=Tp;Wu.f=Ep&&!$p?Object.defineProperties:function(e,t){wp(e);for(var i=kp(t),r=_p(t),a=r.length,n=0,o;a>n;)Ap.f(e,o=r[n++],i[o]);return e};var Pp=Bi,Ku=Pp("document","documentElement"),Dp=ti,Ip=Wu,td=Qu,Rp=ao,Lp=Ku,xp=eo,Cp=ro,id=">",sd="<",In="prototype",Rn="script",Ju=Cp("IE_PROTO"),Ma=function(){},Xu=function(s){return sd+Rn+id+s+sd+"/"+Rn+id},rd=function(s){s.write(Xu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Op=function(){var s=xp("iframe"),e="java"+Rn+":",t;return s.style.display="none",Lp.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Xu("document.F=Object")),t.close(),t.F},rr,Ar=function(){try{rr=new ActiveXObject("htmlfile")}catch(e){}Ar=typeof document!="undefined"?document.domain&&rr?rd(rr):Op():rd(rr);for(var s=td.length;s--;)delete Ar[In][td[s]];return Ar()};Rp[Ju]=!0;var Zu=Object.create||function(e,t){var i;return e!==null?(Ma[In]=Dp(e),i=new Ma,Ma[In]=null,i[Ju]=e):i=Ar(),t===void 0?i:Ip.f(i,t)},Bp=bt,Mp=!Bp(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Np=Mt,Fp=Re,Up=Xr,Vp=ro,Hp=Mp,ad=Vp("IE_PROTO"),Ln=Object,Gp=Ln.prototype,el=Hp?Ln.getPrototypeOf:function(s){var e=Up(s);if(Np(e,ad))return e[ad];var t=e.constructor;return Fp(t)&&e instanceof t?t.prototype:e instanceof Ln?Gp:null},jp=Ys,co=function(s,e,t,i){return i&&i.enumerable?s[e]=t:jp(s,e,t),s},Yp=bt,zp=Re,qp=ei,Wp=Zu,nd=el,Qp=co,Kp=Ke,xn=Kp("iterator"),tl=!1,Jt,Na,Fa;[].keys&&(Fa=[].keys(),"next"in Fa?(Na=nd(nd(Fa)),Na!==Object.prototype&&(Jt=Na)):tl=!0);var Jp=!qp(Jt)||Yp(function(){var s={};return Jt[xn].call(s)!==s});Jp?Jt={}:Jt=Wp(Jt);zp(Jt[xn])||Qp(Jt,xn,function(){return this});var il={IteratorPrototype:Jt,BUGGY_SAFARI_ITERATORS:tl},Xp=Ke,Zp=Xp("toStringTag"),sl={};sl[Zp]="z";var ho=String(sl)==="[object z]",em=ho,tm=Re,wr=Hs,im=Ke,sm=im("toStringTag"),rm=Object,am=wr(function(){return arguments}())=="Arguments",nm=function(s,e){try{return s[e]}catch(t){}},qs=em?wr:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=nm(e=rm(s),sm))=="string"?t:am?wr(e):(i=wr(e))=="Object"&&tm(e.callee)?"Arguments":i},om=ho,dm=qs,um=om?{}.toString:function(){return"[object "+dm(this)+"]"},lm=ho,cm=Oi.f,hm=Ys,fm=Mt,pm=um,mm=Ke,od=mm("toStringTag"),fo=function(s,e,t,i){if(s){var r=t?s:s.prototype;fm(r,od)||cm(r,od,{configurable:!0,value:e}),i&&!lm&&hm(r,"toString",pm)}},vm=il.IteratorPrototype,gm=Zu,Sm=Zr,bm=fo,ym=us,Tm=function(){return this},Em=function(s,e,t,i){var r=e+" Iterator";return s.prototype=gm(vm,{next:Sm(+!i,t)}),bm(s,r,!1,!0),ym[r]=Tm,s},$m=_t,Am=ct,rl=Jf,wm=Em,km=el,_m=fo,dd=co,Pm=Ke,ud=us,al=il,Dm=rl.PROPER;rl.CONFIGURABLE;al.IteratorPrototype;var ar=al.BUGGY_SAFARI_ITERATORS,Ua=Pm("iterator"),ld="keys",nr="values",cd="entries",Im=function(){return this},Rm=function(s,e,t,i,r,a,n){wm(t,e,i);var o=function(g){if(g===r&&h)return h;if(!ar&&g in l)return l[g];switch(g){case ld:return function(){return new t(this,g)};case nr:return function(){return new t(this,g)};case cd:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ua]||l["@@iterator"]||r&&l[r],h=!ar&&c||o(r),f=e=="Array"&&l.entries||c,p,S,b;if(f&&(p=km(f.call(new s)),p!==Object.prototype&&p.next&&(_m(p,u,!0,!0),ud[u]=Im)),Dm&&r==nr&&c&&c.name!==nr&&(d=!0,h=function(){return Am(c,this)}),r)if(S={values:o(nr),keys:a?h:o(ld),entries:o(cd)},n)for(b in S)(ar||d||!(b in l))&&dd(l,b,S[b]);else $m({target:e,proto:!0,forced:ar||d},S);return n&&l[Ua]!==h&&dd(l,Ua,h,{name:r}),ud[e]=h,S},Lm=function(s,e){return{value:s,done:e}},xm=js,hd=us,nl=Fu;Oi.f;var Cm=Rm,or=Lm,ol="Array Iterator",Om=nl.set,Bm=nl.getterFor(ol);Cm(Array,"Array",function(s,e){Om(this,{type:ol,target:xm(s),index:0,kind:e})},function(){var s=Bm(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,or(void 0,!0)):t=="keys"?or(i,!1):t=="values"?or(e[i],!1):or([i,e[i]],!1)},"values");hd.Arguments=hd.Array;var Mm=Ke,Nm=us,Fm=Mm("iterator"),Um=Array.prototype,Vm=function(s){return s!==void 0&&(Nm.Array===s||Um[Fm]===s)},Hm=qs,fd=Jr,Gm=Gs,jm=us,Ym=Ke,zm=Ym("iterator"),dl=function(s){if(!Gm(s))return fd(s,zm)||fd(s,"@@iterator")||jm[Hm(s)]},qm=ct,Wm=Mi,Qm=ti,Km=Kr,Jm=dl,Xm=TypeError,Zm=function(s,e){var t=arguments.length<2?Jm(s):e;if(Wm(t))return Qm(qm(t,s));throw Xm(Km(s)+" is not iterable")},ev=ct,pd=ti,tv=Jr,iv=function(s,e,t){var i,r;pd(s);try{if(i=tv(s,"return"),!i){if(e==="throw")throw t;return t}i=ev(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pd(i),t},sv=ea,rv=ct,av=ti,nv=Kr,ov=Vm,dv=lo,md=Wr,uv=Zm,lv=dl,vd=iv,cv=TypeError,kr=function(s,e){this.stopped=s,this.result=e},gd=kr.prototype,po=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=sv(e,i),d,l,c,h,f,p,S,b=function(y){return d&&vd(d,"normal",y),new kr(!0,y)},g=function(y){return r?(av(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=lv(s),!l)throw cv(nv(s)+" is not iterable");if(ov(l)){for(c=0,h=dv(s);h>c;c++)if(f=g(s[c]),f&&md(gd,f))return f;return new kr(!1)}d=uv(s,l)}for(p=a?s.next:d.next;!(S=rv(p,d)).done;){try{f=g(S.value)}catch(y){vd(d,"throw",y)}if(typeof f=="object"&&f&&md(gd,f))return f}return new kr(!1)},hv=so,fv=Oi,pv=Zr,mv=function(s,e,t){var i=hv(e);i in s?fv.f(s,i,pv(0,t)):s[i]=t},vv=_t,gv=po,Sv=mv;vv({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gv(e,function(i,r){Sv(t,i,r)},{AS_ENTRIES:!0}),t}});var bv=to,yv=bv.Object.fromEntries,Tv={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},Ev=Tv,$v=Ve,Av=qs,wv=Ys,Sd=us,kv=Ke,bd=kv("toStringTag");for(var Va in Ev){var yd=$v[Va],Ha=yd&&yd.prototype;Ha&&Av(Ha)!==bd&&wv(Ha,bd,Va),Sd[Va]=Sd.Array}var _v=yv,Pv=_v,Dv=Pv,Iv=Dv,Li=zr(Iv),Rv=Hs,ta=typeof process!="undefined"&&Rv(process)=="process",Lv=Oi,xv=function(s,e,t){return Lv.f(s,e,t)},Cv=Bi,Ov=xv,Bv=Ke,Mv=hi,Td=Bv("species"),Nv=function(s){var e=Cv(s);Mv&&e&&!e[Td]&&Ov(e,Td,{configurable:!0,get:function(){return this}})},Fv=Wr,Uv=TypeError,Vv=function(s,e){if(Fv(e,s))return s;throw Uv("Incorrect invocation")},Hv=yt,Gv=Re,Cn=io,jv=Hv(Function.toString);Gv(Cn.inspectSource)||(Cn.inspectSource=function(s){return jv(s)});var ul=Cn.inspectSource,Yv=yt,zv=bt,ll=Re,qv=qs,Wv=Bi,Qv=ul,cl=function(){},Kv=[],hl=Wv("Reflect","construct"),mo=/^\s*(?:class|function)\b/,Jv=Yv(mo.exec),Xv=!mo.exec(cl),As=function(e){if(!ll(e))return!1;try{return hl(cl,Kv,e),!0}catch(t){return!1}},fl=function(e){if(!ll(e))return!1;switch(qv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Xv||!!Jv(mo,Qv(e))}catch(t){return!0}};fl.sham=!0;var Zv=!hl||zv(function(){var s;return As(As.call)||!As(Object)||!As(function(){s=!0})||s})?fl:As,eg=Zv,tg=Kr,ig=TypeError,sg=function(s){if(eg(s))return s;throw ig(tg(s)+" is not a constructor")},Ed=ti,rg=sg,ag=Gs,ng=Ke,og=ng("species"),pl=function(s,e){var t=Ed(s).constructor,i;return t===void 0||ag(i=Ed(t)[og])?e:rg(i)},dg=yt,ug=dg([].slice),lg=TypeError,cg=function(s,e){if(s<e)throw lg("Not enough arguments");return s},hg=Qr,ml=/(?:ipad|iphone|ipod).*applewebkit/i.test(hg),ut=Ve,fg=Vu,pg=ea,$d=Re,mg=Mt,vl=bt,Ad=Ku,vg=ug,wd=eo,gg=cg,Sg=ml,bg=ta,On=ut.setImmediate,Bn=ut.clearImmediate,yg=ut.process,Ga=ut.Dispatch,Tg=ut.Function,kd=ut.MessageChannel,Eg=ut.String,ja=0,xs={},_d="onreadystatechange",Fs,wi,Ya,za;vl(function(){Fs=ut.location});var vo=function(s){if(mg(xs,s)){var e=xs[s];delete xs[s],e()}},qa=function(s){return function(){vo(s)}},Pd=function(s){vo(s.data)},Dd=function(s){ut.postMessage(Eg(s),Fs.protocol+"//"+Fs.host)};(!On||!Bn)&&(On=function(e){gg(arguments.length,1);var t=$d(e)?e:Tg(e),i=vg(arguments,1);return xs[++ja]=function(){fg(t,void 0,i)},wi(ja),ja},Bn=function(e){delete xs[e]},bg?wi=function(s){yg.nextTick(qa(s))}:Ga&&Ga.now?wi=function(s){Ga.now(qa(s))}:kd&&!Sg?(Ya=new kd,za=Ya.port2,Ya.port1.onmessage=Pd,wi=pg(za.postMessage,za)):ut.addEventListener&&$d(ut.postMessage)&&!ut.importScripts&&Fs&&Fs.protocol!=="file:"&&!vl(Dd)?(wi=Dd,ut.addEventListener("message",Pd,!1)):_d in wd("script")?wi=function(s){Ad.appendChild(wd("script"))[_d]=function(){Ad.removeChild(this),vo(s)}}:wi=function(s){setTimeout(qa(s),0)});var gl={set:On,clear:Bn},Sl=function(){this.head=null,this.tail=null};Sl.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var bl=Sl,$g=Qr,Ag=/ipad|iphone|ipod/i.test($g)&&typeof Pebble!="undefined",wg=Qr,kg=/web0s(?!.*chrome)/i.test(wg),xi=Ve,Id=ea,_g=no.f,Wa=gl.set,Pg=bl,Dg=ml,Ig=Ag,Rg=kg,Qa=ta,Rd=xi.MutationObserver||xi.WebKitMutationObserver,Ld=xi.document,xd=xi.process,dr=xi.Promise,Cd=_g(xi,"queueMicrotask"),Mn=Cd&&Cd.value,Yi,Ka,Ja,ur,Od;if(!Mn){var lr=new Pg,cr=function(){var s,e;for(Qa&&(s=xd.domain)&&s.exit();e=lr.get();)try{e()}catch(t){throw lr.head&&Yi(),t}s&&s.enter()};!Dg&&!Qa&&!Rg&&Rd&&Ld?(Ka=!0,Ja=Ld.createTextNode(""),new Rd(cr).observe(Ja,{characterData:!0}),Yi=function(){Ja.data=Ka=!Ka}):!Ig&&dr&&dr.resolve?(ur=dr.resolve(void 0),ur.constructor=dr,Od=Id(ur.then,ur),Yi=function(){Od(cr)}):Qa?Yi=function(){xd.nextTick(cr)}:(Wa=Id(Wa,xi),Yi=function(){Wa(cr)}),Mn=function(s){lr.head||Yi(),lr.add(s)}}var Lg=Mn,xg=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},go=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Cg=Ve,ls=Cg.Promise,yl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Og=yl,Bg=ta,Mg=!Og&&!Bg&&typeof window=="object"&&typeof document=="object",Ng=Ve,Cs=ls,Fg=Re,Ug=zu,Vg=ul,Hg=Ke,Gg=Mg,jg=yl,Xa=Ru,Bd=Cs&&Cs.prototype,Yg=Hg("species"),Nn=!1,Tl=Fg(Ng.PromiseRejectionEvent),zg=Ug("Promise",function(){var s=Vg(Cs),e=s!==String(Cs);if(!e&&Xa===66||!(Bd.catch&&Bd.finally))return!0;if(!Xa||Xa<51||!/native code/.test(s)){var t=new Cs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Yg]=i,Nn=t.then(function(){})instanceof i,!Nn)return!0}return!e&&(Gg||jg)&&!Tl}),Ws={CONSTRUCTOR:zg,REJECTION_EVENT:Tl,SUBCLASSING:Nn},cs={},Md=Mi,qg=TypeError,Wg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw qg("Bad Promise constructor");e=i,t=r}),this.resolve=Md(e),this.reject=Md(t)};cs.f=function(s){return new Wg(s)};var Qg=_t,Rr=ta,ui=Ve,Qs=ct,Kg=co,Jg=fo,Xg=Nv,Zg=Mi,Fn=Re,eS=ei,tS=Vv,iS=pl,El=gl.set,So=Lg,sS=xg,rS=go,aS=bl,$l=Fu,Un=ls,bo=Ws,Al=cs,ia="Promise",wl=bo.CONSTRUCTOR,nS=bo.REJECTION_EVENT;bo.SUBCLASSING;var Za=$l.getterFor(ia),oS=$l.set,dS=Un&&Un.prototype,Ji=Un,en=dS,kl=ui.TypeError,Vn=ui.document,yo=ui.process,Hn=Al.f,uS=Hn,lS=!!(Vn&&Vn.createEvent&&ui.dispatchEvent),_l="unhandledrejection",cS="rejectionhandled",Nd=0,Pl=1,hS=2,To=1,Dl=2,hr,Fd,fS,Il=function(s){var e;return eS(s)&&Fn(e=s.then)?e:!1},Rl=function(s,e){var t=e.value,i=e.state==Pl,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Dl&&mS(e),e.rejection=To),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(kl("Promise-chain cycle")):(d=Il(u))?Qs(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Ll=function(s,e){s.notified||(s.notified=!0,So(function(){for(var t=s.reactions,i;i=t.get();)Rl(i,s);s.notified=!1,e&&!s.rejection&&pS(s)}))},xl=function(s,e,t){var i,r;lS?(i=Vn.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!nS&&(r=ui["on"+s])?r(i):s===_l&&sS("Unhandled promise rejection",t)},pS=function(s){Qs(El,ui,function(){var e=s.facade,t=s.value,i=Ud(s),r;if(i&&(r=rS(function(){Rr?yo.emit("unhandledRejection",t,e):xl(_l,e,t)}),s.rejection=Rr||Ud(s)?Dl:To,r.error))throw r.value})},Ud=function(s){return s.rejection!==To&&!s.parent},mS=function(s){Qs(El,ui,function(){var e=s.facade;Rr?yo.emit("rejectionHandled",e):xl(cS,e,s.value)})},Xi=function(s,e,t){return function(i){s(e,i,t)}},is=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=hS,Ll(s,!0))},Gn=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw kl("Promise can't be resolved itself");var i=Il(e);i?So(function(){var r={done:!1};try{Qs(i,e,Xi(Gn,r,s),Xi(is,r,s))}catch(a){is(r,a,s)}}):(s.value=e,s.state=Pl,Ll(s,!1))}catch(r){is({done:!1},r,s)}}};wl&&(Ji=function(e){tS(this,en),Zg(e),Qs(hr,this);var t=Za(this);try{e(Xi(Gn,t),Xi(is,t))}catch(i){is(t,i)}},en=Ji.prototype,hr=function(e){oS(this,{type:ia,done:!1,notified:!1,parent:!1,reactions:new aS,rejection:!1,state:Nd,value:void 0})},hr.prototype=Kg(en,"then",function(e,t){var i=Za(this),r=Hn(iS(this,Ji));return i.parent=!0,r.ok=Fn(e)?e:!0,r.fail=Fn(t)&&t,r.domain=Rr?yo.domain:void 0,i.state==Nd?i.reactions.add(r):So(function(){Rl(r,i)}),r.promise}),Fd=function(){var s=new hr,e=Za(s);this.promise=s,this.resolve=Xi(Gn,e),this.reject=Xi(is,e)},Al.f=Hn=function(s){return s===Ji||s===fS?new Fd(s):uS(s)});Qg({global:!0,constructor:!0,wrap:!0,forced:wl},{Promise:Ji});Jg(Ji,ia,!1,!0);Xg(ia);var vS=Ke,Cl=vS("iterator"),Ol=!1;try{var gS=0,Vd={next:function(){return{done:!!gS++}},return:function(){Ol=!0}};Vd[Cl]=function(){return this},Array.from(Vd,function(){throw 2})}catch(s){}var SS=function(s,e){if(!e&&!Ol)return!1;var t=!1;try{var i={};i[Cl]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},bS=ls,yS=SS,TS=Ws.CONSTRUCTOR,Bl=TS||!yS(function(s){bS.all(s).then(void 0,function(){})}),ES=_t,$S=ct,AS=Mi,wS=cs,kS=go,_S=po,PS=Bl;ES({target:"Promise",stat:!0,forced:PS},{all:function(e){var t=this,i=wS.f(t),r=i.resolve,a=i.reject,n=kS(function(){var o=AS(t.resolve),u=[],d=0,l=1;_S(e,function(c){var h=d++,f=!1;l++,$S(o,t,c).then(function(p){f||(f=!0,u[h]=p,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var DS=_t,IS=Ws.CONSTRUCTOR,Hd=ls;Hd&&Hd.prototype;DS({target:"Promise",proto:!0,forced:IS,real:!0},{catch:function(s){return this.then(void 0,s)}});var RS=_t,LS=ct,xS=Mi,CS=cs,OS=go,BS=po,MS=Bl;RS({target:"Promise",stat:!0,forced:MS},{race:function(e){var t=this,i=CS.f(t),r=i.reject,a=OS(function(){var n=xS(t.resolve);BS(e,function(o){LS(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var NS=_t,FS=ct,US=cs,VS=Ws.CONSTRUCTOR;NS({target:"Promise",stat:!0,forced:VS},{reject:function(e){var t=US.f(this);return FS(t.reject,void 0,e),t.promise}});var HS=ti,GS=ei,jS=cs,Ml=function(s,e){if(HS(s),GS(e)&&e.constructor===s)return e;var t=jS.f(s),i=t.resolve;return i(e),t.promise},YS=_t,zS=Bi,qS=$h,WS=ls,QS=Ws.CONSTRUCTOR,KS=Ml,JS=zS("Promise"),XS=!QS;YS({target:"Promise",stat:!0,forced:qS},{resolve:function(e){return KS(XS&&this===JS?WS:this,e)}});var ZS=_t,jn=ls,eb=bt,tb=Bi,ib=Re,sb=pl,Gd=Ml,rb=jn&&jn.prototype,ab=!!jn&&eb(function(){rb.finally.call({then:function(){}},function(){})});ZS({target:"Promise",proto:!0,real:!0,forced:ab},{finally:function(s){var e=sb(this,tb("Promise")),t=ib(s);return this.then(t?function(i){return Gd(e,s()).then(function(){return i})}:s,t?function(i){return Gd(e,s()).then(function(){throw i})}:s)}});var nb=Bi,Eo=nb,ob=Eo,db=ob("Promise","finally"),ub=db,lb=ub,cb=lb,hb=cb,Ks=zr(hb),Te;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var qe=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:z(t)}return s};const Lr=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:z(e)}};var L=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class me{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=G(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=G(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||I(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const fb=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return z(s)}};var ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ee||(ee={}));const pb=5,mb=5,vb=500,jd=7e3;class gb{constructor(e){this.subscription=new ce,this.loadMediaTimeoutSubscription=new ce,this.videoState=new me(ee.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===m.STOPPED){i!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===ie.Requested&&i!==ee.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case ee.PLAYING:case ee.PAUSED:case ee.READY:break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PLAYING:{switch(i){case ee.PLAYING:break;case ee.PAUSED:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.READY:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PAUSED:{switch(i){case ee.PLAYING:this.videoState.startTransitionTo(ee.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ee.PAUSED:break;case ee.READY:this.videoState.startTransitionTo(ee.PAUSED),this.videoState.setState(ee.PAUSED);break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}default:z(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fb(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 ce;this.subscription.add(e),this.subscription.add(G(this.videoState.stateChangeStarted$.pipe(P(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(P(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new O;e.add(r.pipe(lt(vb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(V(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===ie.Applying||Math.abs(o-a)>pb)&&r.next(o),a=o})),e.add(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<mb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(this.params.desiredState.playbackState,m.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:z(n)}}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=G(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ie.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===ee.PAUSED||e===ee.PLAYING)&&(this.videoState.setState(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===ee.PLAYING||e===ee.PAUSED)&&(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===ee.READY&&this.videoState.setState(ee.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==ee.STOPPED&&this.videoState.setState(ee.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];D(l);const c=fc(Object.keys(l));D(c);const h=l[c];D(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];D(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];D(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];D(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];D(l),r=qe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return I(u)&&(o.metadata.title=u),I(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ie.Applying||i.state===ie.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(pc(jd).subscribe(()=>a(`timeout(${jd})`)))});Ks(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ie.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:R.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Sb=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},bb=s=>{const e=new T(1/0),t=new O,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,p,S;const b=Li(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const v=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:v*1e3)!==null&&f!==void 0?f:NaN;I($)&&!isNaN($)&&e.next($)}const g=(p=b["x-delivery-type"])!==null&&p!==void 0?p:Ms.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(g),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,p=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),p(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},li=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},yb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:li}),!0),Tb=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const kt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=W(r),d=new ce;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},fi=(s,e,t)=>kt(e,()=>s.loop,i=>{I(i)&&(s.loop=i)},{onError:t}),Nt=(s,e,t,i)=>kt(e,()=>({muted:s.muted,volume:s.volume}),r=>{I(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ii=(s,e,t,i)=>kt(e,()=>s.playbackRate,r=>{I(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Eb=s=>["__",s.language,s.label].join("|"),$b=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pt{constructor(){this.available$=new O,this.current$=new T(void 0),this.error$=new O,this.subscription=new ce,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(kt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{I(a)&&this.setInternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(kt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{I(a)&&this.setExternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(kt(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(kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(V(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(G(V(e,"addtrack"),V(e,"removetrack"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ye((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(G(V(e,"change"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),P(i=>i&&this.htmlTextTrackToITextTrack(i).id),ye()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(V(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(V(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;I(t.align)&&(r.align=t.align),I(t.position)&&(r.position=t.position),I(t.size)&&(r.size=t.size),I(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Eb(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(W(e)||!$b(t,e))&&(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){D(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){D(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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 $o=s=>{s.removeAttribute("src"),s.load()},Ab=s=>{try{s.pause(),s.playbackRate=0,$o(s),s.remove()}catch(e){console.error(e)}};class wb{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 Yn=window.WeakMap?new WeakMap:new wb,Ft=s=>{let e=s.querySelector("video");const t=!!e;return e?$o(e):(e=document.createElement("video"),s.appendChild(e)),Yn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ut=s=>{const e=Yn.get(s);Yn.delete(s),e?$o(s):Ab(s)};class Js{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 Nl=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Yd=s=>{const e=Nl(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},kb=s=>{const e=Nl(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},zn=3;class _b{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<zn&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||zn))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Fl=(s,e,t=zn)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Vt=s=>{const e=v=>V(s,v).pipe(ss(void 0)),i=G(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>V(s,v))).pipe(P(v=>v.type==="ended"?s.readyState<2:s.readyState<3),ye()),r=G(V(s,"progress"),V(s,"timeupdate")).pipe(P(()=>Fl(s.buffered,s.currentTime))),n=jr().browser===Xn.Safari?Be({play:e("play").pipe(_e()),playing:e("playing")}).pipe(ss(void 0)):e("playing"),o=V(s,"volumechange").pipe(P(()=>({muted:s.muted,volume:s.volume}))),u=V(s,"ratechange").pipe(P(()=>s.playbackRate)),d=V(s,"error").pipe(oe(()=>!!(s.error||s.played.length)),P(()=>{var v;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=V(s,"timeupdate").pipe(P(()=>s.currentTime)),c=new O,h=.3;let f;l.subscribe(v=>{s.loop&&I(f)&&I(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const p=V(s,"enterpictureinpicture"),S=V(s,"leavepictureinpicture"),b=new T(kb(s));p.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const g=new T(Yd(s));return V(s,"fullscreenchange").pipe(P(()=>Yd(s))).subscribe(g),{playing$:n,pause$:e("pause").pipe(oe(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:V(s,"durationchange").pipe(P(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:g}},sa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Pb=_t,Db=Xr,Ib=lo,Rb=uo;Pb({target:"Array",proto:!0},{at:function(e){var t=Db(this),i=Ib(t),r=Rb(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Lb=Eo,xb=Lb("Array","at"),Cb=xb,Ob=Cb,Bb=Ob,Mb=Bb,Oe=zr(Mb);let Ao=!1,Kt={};const Nb=s=>{Ao=s},Fb=()=>{Kt={}},Ub=s=>{s(Kt)},fr=(s,e)=>{var t;Ao&&(Kt.meta=(t=Kt.meta)!==null&&t!==void 0?t:{},Kt.meta[s]=e)};class xt{constructor(e){this.name=e}next(e){var t,i;if(!Ao)return;Kt.series=(t=Kt.series)!==null&&t!==void 0?t:{};const r=(i=Kt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Kt.series[this.name]=r}}var _i;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(_i||(_i={}));const Vb=new xt("best_bitrate"),Hb=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Ul{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gb='Assertion "ABR Tracks is empty array" failed',Ni=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,p,S,b;mc(s,Gb);const g=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},v=y&&ci(y),E=i.considerPlaybackRate&&I(o)?o:1,$=s.filter(N=>!Ii(N.quality)).sort((N,C)=>ts(N.quality,C.quality)?-1:1),x=(f=Oe($,-1))===null||f===void 0?void 0:f.quality,j=(p=Oe($,0))===null||p===void 0?void 0:p.quality,K=W(r)||I(r.min)&&I(r.max)&&$r(r.max,r.min)||I(r.min)&&j&&ts(r.min,j)||I(r.max)&&x&&$r(r.max,x),H=E*Hb(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(N=>(v?$r(N.quality,v):!0)?(I(t)&&isFinite(t)&&I(N.bitrate)?t-a>=N.bitrate*H:!0)?i.lazyQualitySwitch&&I(i.minBufferToSwitchUp)&&u&&!Ii(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ts(N.quality,u.quality)?(q[N.quality]=_i.Buffer,!1):!!l&&An(N.quality,l)?(q[N.quality]=_i.DroppedFramesLimit,!1):K||(W(r.max)||Tu(N.quality,r.max))&&(W(r.min)||An(N.quality,r.min))?!0:(q[N.quality]=_i.FitsQualityLimits,!1):(q[N.quality]=_i.FitsThroughput,!1):(q[N.quality]=_i.FitsContainer,!1))[0];B&&B.bitrate&&Vb.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
6
+ import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as I,ErrorCategory as R,isNullable as W,fromEvent as V,assertNever as z,merge as G,tap as Bs,map as P,observableFrom as We,filterChanged as ye,assertNonNullable as D,debounce as lt,getHighestQuality as fc,timeout as pc,getCurrentBrowser as jr,CurrentClientBrowser as Xn,combine as Be,once as _e,mapTo as ss,filter as oe,now as he,assertNotEmptyArray as mc,videoSizeToQuality as ci,isInvariantQuality as Ii,isHigher as ts,isLower as $r,isHigherOrEqual as An,isLowerOrEqual as Tu,Observable as Yr,debounceFn as vc,interval as Ri,VideoQuality as ft,videoQualityToHeight as gc,abortable as fe,getExponentialDelay as Ls,throttle as Sc,isIOS as bc,CurrentClientDevice as yc,safeStorage as ya,fillWithDefault as Tc,Logger as Ec}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as WE,Subject as QE,Subscription as KE,ValueSubject as JE,VideoQuality as XE}from"@vkontakte/videoplayer-shared/es2015.esm.js";const $c="2.0.98-dev.508d1c24.0";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Ye;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ye||(Ye={}));var Ne;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ne||(Ne={}));var Ms;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ms||(Ms={}));var ie;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ie||(ie={}));var ni;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(ni||(ni={}));function J(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function _(s){return this instanceof _?(this.v=s,this):new _(s)}function pe(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(p,S){a.push([h,f,p,S])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(p){c(a[0][3],p)}}function u(h){h.value instanceof _?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Ac=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class wc{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ne.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new T(Ne.NOT_AVAILABLE),this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=I((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Ac("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){I(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(V(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return z(r.sessionState)}})).add(G(V(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Bs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),P(r=>r.castState)),We([i.getCastState()])).pipe(ye(),P(kc),Bs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ne.CONNECTED,o=I(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();D(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(W(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ne.CONNECTED?I(this.connection$.getValue())?Ne.CONNECTED:Ne.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const kc=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ne.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ne.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ne.CONNECTING;case cast.framework.CastState.CONNECTED:return Ne.CONNECTED;default:return z(s)}};var Ta=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function zr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bt=function(s){try{return!!s()}catch(e){return!0}},_c=bt,qr=!_c(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Eu=qr,$u=Function.prototype,wn=$u.call,Pc=Eu&&$u.bind.bind(wn,wn),yt=Eu?Pc:function(s){return function(){return wn.apply(s,arguments)}},Au=yt,Dc=Au({}.toString),Ic=Au("".slice),Hs=function(s){return Ic(Dc(s),8,-1)},Rc=yt,Lc=bt,xc=Hs,Ea=Object,Cc=Rc("".split),Oc=Lc(function(){return!Ea("z").propertyIsEnumerable(0)})?function(s){return xc(s)=="String"?Cc(s,""):Ea(s)}:Ea,Gs=function(s){return s==null},Bc=Gs,Mc=TypeError,Zn=function(s){if(Bc(s))throw Mc("Can't call method on "+s);return s},Nc=Oc,Fc=Zn,js=function(s){return Nc(Fc(s))},us={},er=function(s){return s&&s.Math==Math&&s},Ve=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof Ta=="object"&&Ta)||function(){return this}()||Ta||Function("return this")(),kn=typeof document=="object"&&document.all,Uc=typeof kn=="undefined"&&kn!==void 0,wu={all:kn,IS_HTMLDDA:Uc},ku=wu,Vc=ku.all,Re=ku.IS_HTMLDDA?function(s){return typeof s=="function"||s===Vc}:function(s){return typeof s=="function"},Hc=Ve,Gc=Re,Io=Hc.WeakMap,jc=Gc(Io)&&/native code/.test(String(Io)),Ro=Re,_u=wu,Yc=_u.all,ei=_u.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ro(s)||s===Yc}:function(s){return typeof s=="object"?s!==null:Ro(s)},zc=bt,hi=!zc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Oi={},qc=Ve,Lo=ei,_n=qc.document,Wc=Lo(_n)&&Lo(_n.createElement),eo=function(s){return Wc?_n.createElement(s):{}},Qc=hi,Kc=bt,Jc=eo,Pu=!Qc&&!Kc(function(){return Object.defineProperty(Jc("div"),"a",{get:function(){return 7}}).a!=7}),Xc=hi,Zc=bt,Du=Xc&&Zc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),eh=ei,th=String,ih=TypeError,ti=function(s){if(eh(s))return s;throw ih(th(s)+" is not an object")},sh=qr,tr=Function.prototype.call,ct=sh?tr.bind(tr):function(){return tr.apply(tr,arguments)},to={},$a=to,Aa=Ve,rh=Re,xo=function(s){return rh(s)?s:void 0},Bi=function(s,e){return arguments.length<2?xo($a[s])||xo(Aa[s]):$a[s]&&$a[s][e]||Aa[s]&&Aa[s][e]},ah=yt,Wr=ah({}.isPrototypeOf),Qr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Iu=Ve,wa=Qr,Co=Iu.process,Oo=Iu.Deno,Bo=Co&&Co.versions||Oo&&Oo.version,Mo=Bo&&Bo.v8,wt,Pr;Mo&&(wt=Mo.split("."),Pr=wt[0]>0&&wt[0]<4?1:+(wt[0]+wt[1]));!Pr&&wa&&(wt=wa.match(/Edge\/(\d+)/),(!wt||wt[1]>=74)&&(wt=wa.match(/Chrome\/(\d+)/),wt&&(Pr=+wt[1])));var Ru=Pr,No=Ru,nh=bt,oh=Ve,dh=oh.String,Lu=!!Object.getOwnPropertySymbols&&!nh(function(){var s=Symbol();return!dh(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&No&&No<41}),uh=Lu,xu=uh&&!Symbol.sham&&typeof Symbol.iterator=="symbol",lh=Bi,ch=Re,hh=Wr,fh=xu,ph=Object,Cu=fh?function(s){return typeof s=="symbol"}:function(s){var e=lh("Symbol");return ch(e)&&hh(e.prototype,ph(s))},mh=String,Kr=function(s){try{return mh(s)}catch(e){return"Object"}},vh=Re,gh=Kr,Sh=TypeError,Mi=function(s){if(vh(s))return s;throw Sh(gh(s)+" is not a function")},bh=Mi,yh=Gs,Jr=function(s,e){var t=s[e];return yh(t)?void 0:bh(t)},ka=ct,_a=Re,Pa=ei,Th=TypeError,Eh=function(s,e){var t,i;if(e==="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s))||_a(t=s.valueOf)&&!Pa(i=ka(t,s))||e!=="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s)))return i;throw Th("Can't convert object to primitive value")},Ou={exports:{}},$h=!0,Fo=Ve,Ah=Object.defineProperty,wh=function(s,e){try{Ah(Fo,s,{value:e,configurable:!0,writable:!0})}catch(t){Fo[s]=e}return e},kh=Ve,_h=wh,Uo="__core-js_shared__",Ph=kh[Uo]||_h(Uo,{}),io=Ph,Vo=io;(Ou.exports=function(s,e){return Vo[s]||(Vo[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Bu=Ou.exports,Dh=Zn,Ih=Object,Xr=function(s){return Ih(Dh(s))},Rh=yt,Lh=Xr,xh=Rh({}.hasOwnProperty),Mt=Object.hasOwn||function(e,t){return xh(Lh(e),t)},Ch=yt,Oh=0,Bh=Math.random(),Mh=Ch(1 .toString),Mu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Mh(++Oh+Bh,36)},Nh=Ve,Fh=Bu,Ho=Mt,Uh=Mu,Vh=Lu,Hh=xu,Ki=Nh.Symbol,Da=Fh("wks"),Gh=Hh?Ki.for||Ki:Ki&&Ki.withoutSetter||Uh,Ke=function(s){return Ho(Da,s)||(Da[s]=Vh&&Ho(Ki,s)?Ki[s]:Gh("Symbol."+s)),Da[s]},jh=ct,Go=ei,jo=Cu,Yh=Jr,zh=Eh,qh=Ke,Wh=TypeError,Qh=qh("toPrimitive"),Kh=function(s,e){if(!Go(s)||jo(s))return s;var t=Yh(s,Qh),i;if(t){if(e===void 0&&(e="default"),i=jh(t,s,e),!Go(i)||jo(i))return i;throw Wh("Can't convert object to primitive value")}return e===void 0&&(e="number"),zh(s,e)},Jh=Kh,Xh=Cu,so=function(s){var e=Jh(s,"string");return Xh(e)?e:e+""},Zh=hi,ef=Pu,tf=Du,ir=ti,Yo=so,sf=TypeError,Ia=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,Ra="enumerable",La="configurable",xa="writable";Oi.f=Zh?tf?function(e,t,i){if(ir(e),t=Yo(t),ir(i),typeof e=="function"&&t==="prototype"&&"value"in i&&xa in i&&!i[xa]){var r=rf(e,t);r&&r[xa]&&(e[t]=i.value,i={configurable:La in i?i[La]:r[La],enumerable:Ra in i?i[Ra]:r[Ra],writable:!1})}return Ia(e,t,i)}:Ia:function(e,t,i){if(ir(e),t=Yo(t),ir(i),ef)try{return Ia(e,t,i)}catch(r){}if("get"in i||"set"in i)throw sf("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Zr=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},af=hi,nf=Oi,of=Zr,Ys=af?function(s,e,t){return nf.f(s,e,of(1,t))}:function(s,e,t){return s[e]=t,s},df=Bu,uf=Mu,zo=df("keys"),ro=function(s){return zo[s]||(zo[s]=uf(s))},ao={},lf=jc,Nu=Ve,cf=ei,hf=Ys,Ca=Mt,Oa=io,ff=ro,pf=ao,qo="Object already initialized",Pn=Nu.TypeError,mf=Nu.WeakMap,Dr,Ns,Ir,vf=function(s){return Ir(s)?Ns(s):Dr(s,{})},gf=function(s){return function(e){var t;if(!cf(e)||(t=Ns(e)).type!==s)throw Pn("Incompatible receiver, "+s+" required");return t}};if(lf||Oa.state){var It=Oa.state||(Oa.state=new mf);It.get=It.get,It.has=It.has,It.set=It.set,Dr=function(s,e){if(It.has(s))throw Pn(qo);return e.facade=s,It.set(s,e),e},Ns=function(s){return It.get(s)||{}},Ir=function(s){return It.has(s)}}else{var Hi=ff("state");pf[Hi]=!0,Dr=function(s,e){if(Ca(s,Hi))throw Pn(qo);return e.facade=s,hf(s,Hi,e),e},Ns=function(s){return Ca(s,Hi)?s[Hi]:{}},Ir=function(s){return Ca(s,Hi)}}var Fu={set:Dr,get:Ns,has:Ir,enforce:vf,getterFor:gf},Sf=qr,Uu=Function.prototype,Wo=Uu.apply,Qo=Uu.call,Vu=typeof Reflect=="object"&&Reflect.apply||(Sf?Qo.bind(Wo):function(){return Qo.apply(Wo,arguments)}),bf=Hs,yf=yt,Hu=function(s){if(bf(s)==="Function")return yf(s)},no={},Gu={},ju={}.propertyIsEnumerable,Yu=Object.getOwnPropertyDescriptor,Tf=Yu&&!ju.call({1:2},1);Gu.f=Tf?function(e){var t=Yu(this,e);return!!t&&t.enumerable}:ju;var Ef=hi,$f=ct,Af=Gu,wf=Zr,kf=js,_f=so,Pf=Mt,Df=Pu,Ko=Object.getOwnPropertyDescriptor;no.f=Ef?Ko:function(e,t){if(e=kf(e),t=_f(t),Df)try{return Ko(e,t)}catch(i){}if(Pf(e,t))return wf(!$f(Af.f,e,t),e[t])};var If=bt,Rf=Re,Lf=/#|\.prototype\./,zs=function(s,e){var t=Cf[xf(s)];return t==Bf?!0:t==Of?!1:Rf(e)?If(e):!!e},xf=zs.normalize=function(s){return String(s).replace(Lf,".").toLowerCase()},Cf=zs.data={},Of=zs.NATIVE="N",Bf=zs.POLYFILL="P",zu=zs,Jo=Hu,Mf=Mi,Nf=qr,Ff=Jo(Jo.bind),ea=function(s,e){return Mf(s),e===void 0?s:Nf?Ff(s,e):function(){return s.apply(e,arguments)}},sr=Ve,Uf=Vu,Vf=Hu,Hf=Re,Gf=no.f,jf=zu,Gi=to,Yf=ea,ji=Ys,Xo=Mt,zf=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Uf(s,this,arguments)};return e.prototype=s.prototype,e},_t=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?sr:r?sr[t]:(sr[t]||{}).prototype,o=i?Gi:Gi[t]||ji(Gi,t,{})[t],u=o.prototype,d,l,c,h,f,p,S,b,g;for(h in e)d=jf(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Xo(n,h),p=o[h],l&&(s.dontCallGetSet?(g=Gf(n,h),S=g&&g.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof p==typeof f)&&(s.bind&&l?b=Yf(f,sr):s.wrap&&l?b=zf(f):a&&Hf(f)?b=Vf(f):b=f,(s.sham||f&&f.sham||p&&p.sham)&&ji(b,"sham",!0),ji(o,h,b),a&&(c=t+"Prototype",Xo(Gi,c)||ji(Gi,c,{}),ji(Gi[c],h,f),s.real&&u&&(d||!u[h])&&ji(u,h,f)))},Dn=hi,qf=Mt,qu=Function.prototype,Wf=Dn&&Object.getOwnPropertyDescriptor,oo=qf(qu,"name"),Qf=oo&&function(){}.name==="something",Kf=oo&&(!Dn||Dn&&Wf(qu,"name").configurable),Jf={EXISTS:oo,PROPER:Qf,CONFIGURABLE:Kf},Wu={},Xf=Math.ceil,Zf=Math.floor,ep=Math.trunc||function(e){var t=+e;return(t>0?Zf:Xf)(t)},tp=ep,uo=function(s){var e=+s;return e!==e||e===0?0:tp(e)},ip=uo,sp=Math.max,rp=Math.min,ap=function(s,e){var t=ip(s);return t<0?sp(t+e,0):rp(t,e)},np=uo,op=Math.min,dp=function(s){return s>0?op(np(s),9007199254740991):0},up=dp,lo=function(s){return up(s.length)},lp=js,cp=ap,hp=lo,Zo=function(s){return function(e,t,i){var r=lp(e),a=hp(r),n=cp(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fp={includes:Zo(!0),indexOf:Zo(!1)},pp=yt,Ba=Mt,mp=js,vp=fp.indexOf,gp=ao,ed=pp([].push),Sp=function(s,e){var t=mp(s),i=0,r=[],a;for(a in t)!Ba(gp,a)&&Ba(t,a)&&ed(r,a);for(;e.length>i;)Ba(t,a=e[i++])&&(~vp(r,a)||ed(r,a));return r},Qu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bp=Sp,yp=Qu,Tp=Object.keys||function(e){return bp(e,yp)},Ep=hi,$p=Du,Ap=Oi,wp=ti,kp=js,_p=Tp;Wu.f=Ep&&!$p?Object.defineProperties:function(e,t){wp(e);for(var i=kp(t),r=_p(t),a=r.length,n=0,o;a>n;)Ap.f(e,o=r[n++],i[o]);return e};var Pp=Bi,Ku=Pp("document","documentElement"),Dp=ti,Ip=Wu,td=Qu,Rp=ao,Lp=Ku,xp=eo,Cp=ro,id=">",sd="<",In="prototype",Rn="script",Ju=Cp("IE_PROTO"),Ma=function(){},Xu=function(s){return sd+Rn+id+s+sd+"/"+Rn+id},rd=function(s){s.write(Xu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Op=function(){var s=xp("iframe"),e="java"+Rn+":",t;return s.style.display="none",Lp.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Xu("document.F=Object")),t.close(),t.F},rr,Ar=function(){try{rr=new ActiveXObject("htmlfile")}catch(e){}Ar=typeof document!="undefined"?document.domain&&rr?rd(rr):Op():rd(rr);for(var s=td.length;s--;)delete Ar[In][td[s]];return Ar()};Rp[Ju]=!0;var Zu=Object.create||function(e,t){var i;return e!==null?(Ma[In]=Dp(e),i=new Ma,Ma[In]=null,i[Ju]=e):i=Ar(),t===void 0?i:Ip.f(i,t)},Bp=bt,Mp=!Bp(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Np=Mt,Fp=Re,Up=Xr,Vp=ro,Hp=Mp,ad=Vp("IE_PROTO"),Ln=Object,Gp=Ln.prototype,el=Hp?Ln.getPrototypeOf:function(s){var e=Up(s);if(Np(e,ad))return e[ad];var t=e.constructor;return Fp(t)&&e instanceof t?t.prototype:e instanceof Ln?Gp:null},jp=Ys,co=function(s,e,t,i){return i&&i.enumerable?s[e]=t:jp(s,e,t),s},Yp=bt,zp=Re,qp=ei,Wp=Zu,nd=el,Qp=co,Kp=Ke,xn=Kp("iterator"),tl=!1,Jt,Na,Fa;[].keys&&(Fa=[].keys(),"next"in Fa?(Na=nd(nd(Fa)),Na!==Object.prototype&&(Jt=Na)):tl=!0);var Jp=!qp(Jt)||Yp(function(){var s={};return Jt[xn].call(s)!==s});Jp?Jt={}:Jt=Wp(Jt);zp(Jt[xn])||Qp(Jt,xn,function(){return this});var il={IteratorPrototype:Jt,BUGGY_SAFARI_ITERATORS:tl},Xp=Ke,Zp=Xp("toStringTag"),sl={};sl[Zp]="z";var ho=String(sl)==="[object z]",em=ho,tm=Re,wr=Hs,im=Ke,sm=im("toStringTag"),rm=Object,am=wr(function(){return arguments}())=="Arguments",nm=function(s,e){try{return s[e]}catch(t){}},qs=em?wr:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=nm(e=rm(s),sm))=="string"?t:am?wr(e):(i=wr(e))=="Object"&&tm(e.callee)?"Arguments":i},om=ho,dm=qs,um=om?{}.toString:function(){return"[object "+dm(this)+"]"},lm=ho,cm=Oi.f,hm=Ys,fm=Mt,pm=um,mm=Ke,od=mm("toStringTag"),fo=function(s,e,t,i){if(s){var r=t?s:s.prototype;fm(r,od)||cm(r,od,{configurable:!0,value:e}),i&&!lm&&hm(r,"toString",pm)}},vm=il.IteratorPrototype,gm=Zu,Sm=Zr,bm=fo,ym=us,Tm=function(){return this},Em=function(s,e,t,i){var r=e+" Iterator";return s.prototype=gm(vm,{next:Sm(+!i,t)}),bm(s,r,!1,!0),ym[r]=Tm,s},$m=_t,Am=ct,rl=Jf,wm=Em,km=el,_m=fo,dd=co,Pm=Ke,ud=us,al=il,Dm=rl.PROPER;rl.CONFIGURABLE;al.IteratorPrototype;var ar=al.BUGGY_SAFARI_ITERATORS,Ua=Pm("iterator"),ld="keys",nr="values",cd="entries",Im=function(){return this},Rm=function(s,e,t,i,r,a,n){wm(t,e,i);var o=function(g){if(g===r&&h)return h;if(!ar&&g in l)return l[g];switch(g){case ld:return function(){return new t(this,g)};case nr:return function(){return new t(this,g)};case cd:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ua]||l["@@iterator"]||r&&l[r],h=!ar&&c||o(r),f=e=="Array"&&l.entries||c,p,S,b;if(f&&(p=km(f.call(new s)),p!==Object.prototype&&p.next&&(_m(p,u,!0,!0),ud[u]=Im)),Dm&&r==nr&&c&&c.name!==nr&&(d=!0,h=function(){return Am(c,this)}),r)if(S={values:o(nr),keys:a?h:o(ld),entries:o(cd)},n)for(b in S)(ar||d||!(b in l))&&dd(l,b,S[b]);else $m({target:e,proto:!0,forced:ar||d},S);return n&&l[Ua]!==h&&dd(l,Ua,h,{name:r}),ud[e]=h,S},Lm=function(s,e){return{value:s,done:e}},xm=js,hd=us,nl=Fu;Oi.f;var Cm=Rm,or=Lm,ol="Array Iterator",Om=nl.set,Bm=nl.getterFor(ol);Cm(Array,"Array",function(s,e){Om(this,{type:ol,target:xm(s),index:0,kind:e})},function(){var s=Bm(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,or(void 0,!0)):t=="keys"?or(i,!1):t=="values"?or(e[i],!1):or([i,e[i]],!1)},"values");hd.Arguments=hd.Array;var Mm=Ke,Nm=us,Fm=Mm("iterator"),Um=Array.prototype,Vm=function(s){return s!==void 0&&(Nm.Array===s||Um[Fm]===s)},Hm=qs,fd=Jr,Gm=Gs,jm=us,Ym=Ke,zm=Ym("iterator"),dl=function(s){if(!Gm(s))return fd(s,zm)||fd(s,"@@iterator")||jm[Hm(s)]},qm=ct,Wm=Mi,Qm=ti,Km=Kr,Jm=dl,Xm=TypeError,Zm=function(s,e){var t=arguments.length<2?Jm(s):e;if(Wm(t))return Qm(qm(t,s));throw Xm(Km(s)+" is not iterable")},ev=ct,pd=ti,tv=Jr,iv=function(s,e,t){var i,r;pd(s);try{if(i=tv(s,"return"),!i){if(e==="throw")throw t;return t}i=ev(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pd(i),t},sv=ea,rv=ct,av=ti,nv=Kr,ov=Vm,dv=lo,md=Wr,uv=Zm,lv=dl,vd=iv,cv=TypeError,kr=function(s,e){this.stopped=s,this.result=e},gd=kr.prototype,po=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=sv(e,i),d,l,c,h,f,p,S,b=function(y){return d&&vd(d,"normal",y),new kr(!0,y)},g=function(y){return r?(av(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=lv(s),!l)throw cv(nv(s)+" is not iterable");if(ov(l)){for(c=0,h=dv(s);h>c;c++)if(f=g(s[c]),f&&md(gd,f))return f;return new kr(!1)}d=uv(s,l)}for(p=a?s.next:d.next;!(S=rv(p,d)).done;){try{f=g(S.value)}catch(y){vd(d,"throw",y)}if(typeof f=="object"&&f&&md(gd,f))return f}return new kr(!1)},hv=so,fv=Oi,pv=Zr,mv=function(s,e,t){var i=hv(e);i in s?fv.f(s,i,pv(0,t)):s[i]=t},vv=_t,gv=po,Sv=mv;vv({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gv(e,function(i,r){Sv(t,i,r)},{AS_ENTRIES:!0}),t}});var bv=to,yv=bv.Object.fromEntries,Tv={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},Ev=Tv,$v=Ve,Av=qs,wv=Ys,Sd=us,kv=Ke,bd=kv("toStringTag");for(var Va in Ev){var yd=$v[Va],Ha=yd&&yd.prototype;Ha&&Av(Ha)!==bd&&wv(Ha,bd,Va),Sd[Va]=Sd.Array}var _v=yv,Pv=_v,Dv=Pv,Iv=Dv,Li=zr(Iv),Rv=Hs,ta=typeof process!="undefined"&&Rv(process)=="process",Lv=Oi,xv=function(s,e,t){return Lv.f(s,e,t)},Cv=Bi,Ov=xv,Bv=Ke,Mv=hi,Td=Bv("species"),Nv=function(s){var e=Cv(s);Mv&&e&&!e[Td]&&Ov(e,Td,{configurable:!0,get:function(){return this}})},Fv=Wr,Uv=TypeError,Vv=function(s,e){if(Fv(e,s))return s;throw Uv("Incorrect invocation")},Hv=yt,Gv=Re,Cn=io,jv=Hv(Function.toString);Gv(Cn.inspectSource)||(Cn.inspectSource=function(s){return jv(s)});var ul=Cn.inspectSource,Yv=yt,zv=bt,ll=Re,qv=qs,Wv=Bi,Qv=ul,cl=function(){},Kv=[],hl=Wv("Reflect","construct"),mo=/^\s*(?:class|function)\b/,Jv=Yv(mo.exec),Xv=!mo.exec(cl),As=function(e){if(!ll(e))return!1;try{return hl(cl,Kv,e),!0}catch(t){return!1}},fl=function(e){if(!ll(e))return!1;switch(qv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Xv||!!Jv(mo,Qv(e))}catch(t){return!0}};fl.sham=!0;var Zv=!hl||zv(function(){var s;return As(As.call)||!As(Object)||!As(function(){s=!0})||s})?fl:As,eg=Zv,tg=Kr,ig=TypeError,sg=function(s){if(eg(s))return s;throw ig(tg(s)+" is not a constructor")},Ed=ti,rg=sg,ag=Gs,ng=Ke,og=ng("species"),pl=function(s,e){var t=Ed(s).constructor,i;return t===void 0||ag(i=Ed(t)[og])?e:rg(i)},dg=yt,ug=dg([].slice),lg=TypeError,cg=function(s,e){if(s<e)throw lg("Not enough arguments");return s},hg=Qr,ml=/(?:ipad|iphone|ipod).*applewebkit/i.test(hg),ut=Ve,fg=Vu,pg=ea,$d=Re,mg=Mt,vl=bt,Ad=Ku,vg=ug,wd=eo,gg=cg,Sg=ml,bg=ta,On=ut.setImmediate,Bn=ut.clearImmediate,yg=ut.process,Ga=ut.Dispatch,Tg=ut.Function,kd=ut.MessageChannel,Eg=ut.String,ja=0,xs={},_d="onreadystatechange",Fs,wi,Ya,za;vl(function(){Fs=ut.location});var vo=function(s){if(mg(xs,s)){var e=xs[s];delete xs[s],e()}},qa=function(s){return function(){vo(s)}},Pd=function(s){vo(s.data)},Dd=function(s){ut.postMessage(Eg(s),Fs.protocol+"//"+Fs.host)};(!On||!Bn)&&(On=function(e){gg(arguments.length,1);var t=$d(e)?e:Tg(e),i=vg(arguments,1);return xs[++ja]=function(){fg(t,void 0,i)},wi(ja),ja},Bn=function(e){delete xs[e]},bg?wi=function(s){yg.nextTick(qa(s))}:Ga&&Ga.now?wi=function(s){Ga.now(qa(s))}:kd&&!Sg?(Ya=new kd,za=Ya.port2,Ya.port1.onmessage=Pd,wi=pg(za.postMessage,za)):ut.addEventListener&&$d(ut.postMessage)&&!ut.importScripts&&Fs&&Fs.protocol!=="file:"&&!vl(Dd)?(wi=Dd,ut.addEventListener("message",Pd,!1)):_d in wd("script")?wi=function(s){Ad.appendChild(wd("script"))[_d]=function(){Ad.removeChild(this),vo(s)}}:wi=function(s){setTimeout(qa(s),0)});var gl={set:On,clear:Bn},Sl=function(){this.head=null,this.tail=null};Sl.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var bl=Sl,$g=Qr,Ag=/ipad|iphone|ipod/i.test($g)&&typeof Pebble!="undefined",wg=Qr,kg=/web0s(?!.*chrome)/i.test(wg),xi=Ve,Id=ea,_g=no.f,Wa=gl.set,Pg=bl,Dg=ml,Ig=Ag,Rg=kg,Qa=ta,Rd=xi.MutationObserver||xi.WebKitMutationObserver,Ld=xi.document,xd=xi.process,dr=xi.Promise,Cd=_g(xi,"queueMicrotask"),Mn=Cd&&Cd.value,Yi,Ka,Ja,ur,Od;if(!Mn){var lr=new Pg,cr=function(){var s,e;for(Qa&&(s=xd.domain)&&s.exit();e=lr.get();)try{e()}catch(t){throw lr.head&&Yi(),t}s&&s.enter()};!Dg&&!Qa&&!Rg&&Rd&&Ld?(Ka=!0,Ja=Ld.createTextNode(""),new Rd(cr).observe(Ja,{characterData:!0}),Yi=function(){Ja.data=Ka=!Ka}):!Ig&&dr&&dr.resolve?(ur=dr.resolve(void 0),ur.constructor=dr,Od=Id(ur.then,ur),Yi=function(){Od(cr)}):Qa?Yi=function(){xd.nextTick(cr)}:(Wa=Id(Wa,xi),Yi=function(){Wa(cr)}),Mn=function(s){lr.head||Yi(),lr.add(s)}}var Lg=Mn,xg=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},go=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Cg=Ve,ls=Cg.Promise,yl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Og=yl,Bg=ta,Mg=!Og&&!Bg&&typeof window=="object"&&typeof document=="object",Ng=Ve,Cs=ls,Fg=Re,Ug=zu,Vg=ul,Hg=Ke,Gg=Mg,jg=yl,Xa=Ru,Bd=Cs&&Cs.prototype,Yg=Hg("species"),Nn=!1,Tl=Fg(Ng.PromiseRejectionEvent),zg=Ug("Promise",function(){var s=Vg(Cs),e=s!==String(Cs);if(!e&&Xa===66||!(Bd.catch&&Bd.finally))return!0;if(!Xa||Xa<51||!/native code/.test(s)){var t=new Cs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Yg]=i,Nn=t.then(function(){})instanceof i,!Nn)return!0}return!e&&(Gg||jg)&&!Tl}),Ws={CONSTRUCTOR:zg,REJECTION_EVENT:Tl,SUBCLASSING:Nn},cs={},Md=Mi,qg=TypeError,Wg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw qg("Bad Promise constructor");e=i,t=r}),this.resolve=Md(e),this.reject=Md(t)};cs.f=function(s){return new Wg(s)};var Qg=_t,Rr=ta,ui=Ve,Qs=ct,Kg=co,Jg=fo,Xg=Nv,Zg=Mi,Fn=Re,eS=ei,tS=Vv,iS=pl,El=gl.set,So=Lg,sS=xg,rS=go,aS=bl,$l=Fu,Un=ls,bo=Ws,Al=cs,ia="Promise",wl=bo.CONSTRUCTOR,nS=bo.REJECTION_EVENT;bo.SUBCLASSING;var Za=$l.getterFor(ia),oS=$l.set,dS=Un&&Un.prototype,Ji=Un,en=dS,kl=ui.TypeError,Vn=ui.document,yo=ui.process,Hn=Al.f,uS=Hn,lS=!!(Vn&&Vn.createEvent&&ui.dispatchEvent),_l="unhandledrejection",cS="rejectionhandled",Nd=0,Pl=1,hS=2,To=1,Dl=2,hr,Fd,fS,Il=function(s){var e;return eS(s)&&Fn(e=s.then)?e:!1},Rl=function(s,e){var t=e.value,i=e.state==Pl,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Dl&&mS(e),e.rejection=To),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(kl("Promise-chain cycle")):(d=Il(u))?Qs(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Ll=function(s,e){s.notified||(s.notified=!0,So(function(){for(var t=s.reactions,i;i=t.get();)Rl(i,s);s.notified=!1,e&&!s.rejection&&pS(s)}))},xl=function(s,e,t){var i,r;lS?(i=Vn.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!nS&&(r=ui["on"+s])?r(i):s===_l&&sS("Unhandled promise rejection",t)},pS=function(s){Qs(El,ui,function(){var e=s.facade,t=s.value,i=Ud(s),r;if(i&&(r=rS(function(){Rr?yo.emit("unhandledRejection",t,e):xl(_l,e,t)}),s.rejection=Rr||Ud(s)?Dl:To,r.error))throw r.value})},Ud=function(s){return s.rejection!==To&&!s.parent},mS=function(s){Qs(El,ui,function(){var e=s.facade;Rr?yo.emit("rejectionHandled",e):xl(cS,e,s.value)})},Xi=function(s,e,t){return function(i){s(e,i,t)}},is=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=hS,Ll(s,!0))},Gn=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw kl("Promise can't be resolved itself");var i=Il(e);i?So(function(){var r={done:!1};try{Qs(i,e,Xi(Gn,r,s),Xi(is,r,s))}catch(a){is(r,a,s)}}):(s.value=e,s.state=Pl,Ll(s,!1))}catch(r){is({done:!1},r,s)}}};wl&&(Ji=function(e){tS(this,en),Zg(e),Qs(hr,this);var t=Za(this);try{e(Xi(Gn,t),Xi(is,t))}catch(i){is(t,i)}},en=Ji.prototype,hr=function(e){oS(this,{type:ia,done:!1,notified:!1,parent:!1,reactions:new aS,rejection:!1,state:Nd,value:void 0})},hr.prototype=Kg(en,"then",function(e,t){var i=Za(this),r=Hn(iS(this,Ji));return i.parent=!0,r.ok=Fn(e)?e:!0,r.fail=Fn(t)&&t,r.domain=Rr?yo.domain:void 0,i.state==Nd?i.reactions.add(r):So(function(){Rl(r,i)}),r.promise}),Fd=function(){var s=new hr,e=Za(s);this.promise=s,this.resolve=Xi(Gn,e),this.reject=Xi(is,e)},Al.f=Hn=function(s){return s===Ji||s===fS?new Fd(s):uS(s)});Qg({global:!0,constructor:!0,wrap:!0,forced:wl},{Promise:Ji});Jg(Ji,ia,!1,!0);Xg(ia);var vS=Ke,Cl=vS("iterator"),Ol=!1;try{var gS=0,Vd={next:function(){return{done:!!gS++}},return:function(){Ol=!0}};Vd[Cl]=function(){return this},Array.from(Vd,function(){throw 2})}catch(s){}var SS=function(s,e){if(!e&&!Ol)return!1;var t=!1;try{var i={};i[Cl]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},bS=ls,yS=SS,TS=Ws.CONSTRUCTOR,Bl=TS||!yS(function(s){bS.all(s).then(void 0,function(){})}),ES=_t,$S=ct,AS=Mi,wS=cs,kS=go,_S=po,PS=Bl;ES({target:"Promise",stat:!0,forced:PS},{all:function(e){var t=this,i=wS.f(t),r=i.resolve,a=i.reject,n=kS(function(){var o=AS(t.resolve),u=[],d=0,l=1;_S(e,function(c){var h=d++,f=!1;l++,$S(o,t,c).then(function(p){f||(f=!0,u[h]=p,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var DS=_t,IS=Ws.CONSTRUCTOR,Hd=ls;Hd&&Hd.prototype;DS({target:"Promise",proto:!0,forced:IS,real:!0},{catch:function(s){return this.then(void 0,s)}});var RS=_t,LS=ct,xS=Mi,CS=cs,OS=go,BS=po,MS=Bl;RS({target:"Promise",stat:!0,forced:MS},{race:function(e){var t=this,i=CS.f(t),r=i.reject,a=OS(function(){var n=xS(t.resolve);BS(e,function(o){LS(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var NS=_t,FS=ct,US=cs,VS=Ws.CONSTRUCTOR;NS({target:"Promise",stat:!0,forced:VS},{reject:function(e){var t=US.f(this);return FS(t.reject,void 0,e),t.promise}});var HS=ti,GS=ei,jS=cs,Ml=function(s,e){if(HS(s),GS(e)&&e.constructor===s)return e;var t=jS.f(s),i=t.resolve;return i(e),t.promise},YS=_t,zS=Bi,qS=$h,WS=ls,QS=Ws.CONSTRUCTOR,KS=Ml,JS=zS("Promise"),XS=!QS;YS({target:"Promise",stat:!0,forced:qS},{resolve:function(e){return KS(XS&&this===JS?WS:this,e)}});var ZS=_t,jn=ls,eb=bt,tb=Bi,ib=Re,sb=pl,Gd=Ml,rb=jn&&jn.prototype,ab=!!jn&&eb(function(){rb.finally.call({then:function(){}},function(){})});ZS({target:"Promise",proto:!0,real:!0,forced:ab},{finally:function(s){var e=sb(this,tb("Promise")),t=ib(s);return this.then(t?function(i){return Gd(e,s()).then(function(){return i})}:s,t?function(i){return Gd(e,s()).then(function(){throw i})}:s)}});var nb=Bi,Eo=nb,ob=Eo,db=ob("Promise","finally"),ub=db,lb=ub,cb=lb,hb=cb,Ks=zr(hb),Te;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var qe=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:z(t)}return s};const Lr=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:z(e)}};var L=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class me{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=G(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=G(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||I(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const fb=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return z(s)}};var ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ee||(ee={}));const pb=5,mb=5,vb=500,jd=7e3;class gb{constructor(e){this.subscription=new ce,this.loadMediaTimeoutSubscription=new ce,this.videoState=new me(ee.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===m.STOPPED){i!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===ie.Requested&&i!==ee.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case ee.PLAYING:case ee.PAUSED:case ee.READY:break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PLAYING:{switch(i){case ee.PLAYING:break;case ee.PAUSED:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.READY:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PAUSED:{switch(i){case ee.PLAYING:this.videoState.startTransitionTo(ee.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ee.PAUSED:break;case ee.READY:this.videoState.startTransitionTo(ee.PAUSED),this.videoState.setState(ee.PAUSED);break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}default:z(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fb(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 ce;this.subscription.add(e),this.subscription.add(G(this.videoState.stateChangeStarted$.pipe(P(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(P(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new O;e.add(r.pipe(lt(vb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(V(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===ie.Applying||Math.abs(o-a)>pb)&&r.next(o),a=o})),e.add(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<mb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(this.params.desiredState.playbackState,m.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:z(n)}}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=G(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ie.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===ee.PAUSED||e===ee.PLAYING)&&(this.videoState.setState(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===ee.PLAYING||e===ee.PAUSED)&&(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===ee.READY&&this.videoState.setState(ee.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==ee.STOPPED&&this.videoState.setState(ee.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];D(l);const c=fc(Object.keys(l));D(c);const h=l[c];D(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];D(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];D(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];D(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];D(l),r=qe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return I(u)&&(o.metadata.title=u),I(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ie.Applying||i.state===ie.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(pc(jd).subscribe(()=>a(`timeout(${jd})`)))});Ks(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ie.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:R.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Sb=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},bb=s=>{const e=new T(1/0),t=new O,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,p,S;const b=Li(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const v=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:v*1e3)!==null&&f!==void 0?f:NaN;I($)&&!isNaN($)&&e.next($)}const g=(p=b["x-delivery-type"])!==null&&p!==void 0?p:Ms.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(g),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,p=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),p(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},li=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},yb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:li}),!0),Tb=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const kt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=W(r),d=new ce;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},fi=(s,e,t)=>kt(e,()=>s.loop,i=>{I(i)&&(s.loop=i)},{onError:t}),Nt=(s,e,t,i)=>kt(e,()=>({muted:s.muted,volume:s.volume}),r=>{I(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ii=(s,e,t,i)=>kt(e,()=>s.playbackRate,r=>{I(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Eb=s=>["__",s.language,s.label].join("|"),$b=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pt{constructor(){this.available$=new O,this.current$=new T(void 0),this.error$=new O,this.subscription=new ce,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(kt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{I(a)&&this.setInternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(kt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{I(a)&&this.setExternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(kt(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(kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(V(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(G(V(e,"addtrack"),V(e,"removetrack"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ye((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(G(V(e,"change"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),P(i=>i&&this.htmlTextTrackToITextTrack(i).id),ye()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(V(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(V(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;I(t.align)&&(r.align=t.align),I(t.position)&&(r.position=t.position),I(t.size)&&(r.size=t.size),I(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Eb(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(W(e)||!$b(t,e))&&(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){D(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){D(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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 $o=s=>{s.removeAttribute("src"),s.load()},Ab=s=>{try{s.pause(),s.playbackRate=0,$o(s),s.remove()}catch(e){console.error(e)}};class wb{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 Yn=window.WeakMap?new WeakMap:new wb,Ft=s=>{let e=s.querySelector("video");const t=!!e;return e?$o(e):(e=document.createElement("video"),s.appendChild(e)),Yn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ut=s=>{const e=Yn.get(s);Yn.delete(s),e?$o(s):Ab(s)};class Js{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 Nl=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Yd=s=>{const e=Nl(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},kb=s=>{const e=Nl(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},zn=3;class _b{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<zn&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||zn))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Fl=(s,e,t=zn)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Vt=s=>{const e=v=>V(s,v).pipe(ss(void 0)),i=G(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>V(s,v))).pipe(P(v=>v.type==="ended"?s.readyState<2:s.readyState<3),ye()),r=G(V(s,"progress"),V(s,"timeupdate")).pipe(P(()=>Fl(s.buffered,s.currentTime))),n=jr().browser===Xn.Safari?Be({play:e("play").pipe(_e()),playing:e("playing")}).pipe(ss(void 0)):e("playing"),o=V(s,"volumechange").pipe(P(()=>({muted:s.muted,volume:s.volume}))),u=V(s,"ratechange").pipe(P(()=>s.playbackRate)),d=V(s,"error").pipe(oe(()=>!!(s.error||s.played.length)),P(()=>{var v;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=V(s,"timeupdate").pipe(P(()=>s.currentTime)),c=new O,h=.3;let f;l.subscribe(v=>{s.loop&&I(f)&&I(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const p=V(s,"enterpictureinpicture"),S=V(s,"leavepictureinpicture"),b=new T(kb(s));p.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const g=new T(Yd(s));return V(s,"fullscreenchange").pipe(P(()=>Yd(s))).subscribe(g),{playing$:n,pause$:e("pause").pipe(oe(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:V(s,"durationchange").pipe(P(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:g}},sa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Pb=_t,Db=Xr,Ib=lo,Rb=uo;Pb({target:"Array",proto:!0},{at:function(e){var t=Db(this),i=Ib(t),r=Rb(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Lb=Eo,xb=Lb("Array","at"),Cb=xb,Ob=Cb,Bb=Ob,Mb=Bb,Oe=zr(Mb);let Ao=!1,Kt={};const Nb=s=>{Ao=s},Fb=()=>{Kt={}},Ub=s=>{s(Kt)},fr=(s,e)=>{var t;Ao&&(Kt.meta=(t=Kt.meta)!==null&&t!==void 0?t:{},Kt.meta[s]=e)};class xt{constructor(e){this.name=e}next(e){var t,i;if(!Ao)return;Kt.series=(t=Kt.series)!==null&&t!==void 0?t:{};const r=(i=Kt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Kt.series[this.name]=r}}var _i;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(_i||(_i={}));const Vb=new xt("best_bitrate"),Hb=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Ul{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gb='Assertion "ABR Tracks is empty array" failed',Ni=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,p,S,b;mc(s,Gb);const g=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},v=y&&ci(y),E=i.considerPlaybackRate&&I(o)?o:1,$=s.filter(N=>!Ii(N.quality)).sort((N,C)=>ts(N.quality,C.quality)?-1:1),x=(f=Oe($,-1))===null||f===void 0?void 0:f.quality,j=(p=Oe($,0))===null||p===void 0?void 0:p.quality,K=W(r)||I(r.min)&&I(r.max)&&$r(r.max,r.min)||I(r.min)&&j&&ts(r.min,j)||I(r.max)&&x&&$r(r.max,x),H=E*Hb(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(N=>(v?$r(N.quality,v):!0)?(I(t)&&isFinite(t)&&I(N.bitrate)?t-a>=N.bitrate*H:!0)?i.lazyQualitySwitch&&I(i.minBufferToSwitchUp)&&u&&!Ii(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ts(N.quality,u.quality)?(q[N.quality]=_i.Buffer,!1):!!l&&An(N.quality,l)?(q[N.quality]=_i.DroppedFramesLimit,!1):K||(W(r.max)||Tu(N.quality,r.max))&&(W(r.min)||An(N.quality,r.min))?!0:(q[N.quality]=_i.FitsQualityLimits,!1):(q[N.quality]=_i.FitsThroughput,!1):(q[N.quality]=_i.FitsContainer,!1))[0];B&&B.bitrate&&Vb.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
7
7
  [available tracks]
8
8
  ${s.map(N=>`{ id: ${N.id}, quality: ${N.quality}, bitrate: ${N.bitrate} }`).join(`
9
9
  `)}
@@ -42,5 +42,5 @@ precision highp float;
42
42
  #define GLSLIFY 1
43
43
  #endif
44
44
  #define PI 3.14159265358979323846264
45
- varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Zl{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new H0(this.params.fov,this.params.orientation),this.cameraRotationManager=new G0(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(j0,this.gl.VERTEX_SHADER),i=this.createShader(Y0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let ec=class{constructor(e){this.subscription=new ce,this.videoState=new me(Ae.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==Ae.STOPPED&&n!==m.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===m.STOPPED){a!==Ae.STOPPED&&(this.videoState.startTransitionTo(Ae.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(Ae.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case Ae.STOPPED:this.videoState.startTransitionTo(Ae.READY),this.prepare();return;case Ae.READY:n===m.PAUSED?(this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case Ae.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(Ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Ae.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new V0({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(P(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ae.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ae.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===pt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=Ky(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=Qy(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&Jy(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=Xy(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===pt.REPRESENTATIOS_READY&&(this.videoState.setState(Ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==pt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Fe.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Fe.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ye(),P(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=Ni(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}},z0=class extends ec{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ue;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ue||(Ue={}));var Lt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(Lt||(Lt={}));var Ur;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Ur||(Ur={}));var gt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(gt||(gt={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var os;(function(s){s.MP4="mp4",s.WEBM="webm"})(os||(os={}));var Vr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Vr||(Vr={}));var we;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(we||(we={}));var on,dn;let tc=!1;try{tc=jr().browser===Xn.Safari&&parseInt((dn=(on=navigator.userAgent.match(/Version\/(\d+)/))===null||on===void 0?void 0:on[1])!==null&&dn!==void 0?dn:"",10)<16}catch(s){console.error(s)}class q0{constructor(e){this.bufferFull$=new O,this.error$=new O,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return J(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let i;tc&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.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:z(t)}}}class Tt{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class ic extends Tt{}class W0 extends Tt{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Q0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class K0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class J0 extends Tt{constructor(e){super(e),this.data=this.content}}class ri extends Tt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class X0 extends ri{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class Z0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class eT extends Tt{parseChildrenBoxes(){return pi(this.content)}}var Di;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Di||(Di={}));class tT extends ri{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Di.MONOSCOPIC;break;case 1:this.stereoMode=Di.TOP_BOTTOM;break;case 2:this.stereoMode=Di.LEFT_RIGHT;break;case 3:this.stereoMode=Di.STEREO_CUSTOM;break;case 4:this.stereoMode=Di.RIGHT_LEFT;break}this.cursor+=1}}class iT extends ri{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class sT extends ri{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class rT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class aT extends ri{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class nT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class oT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class dT extends ri{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class uT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class lT extends ri{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class cT extends ri{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class hT extends ri{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const fT={ftyp:W0,moov:Q0,moof:K0,mdat:J0,sidx:X0,trak:Z0,mdia:rT,mfhd:dT,tkhd:aT,traf:uT,tfhd:lT,tfdt:cT,trun:hT,minf:nT,sv3d:eT,st3d:tT,prhd:iT,proj:oT,equi:sT,unknown:ic};class pT{createBox(e,t){const i=fT[e];return i?new i(t):new ic(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return na.createBox(i,new DataView(e.buffer,e.byteOffset))}}const na=new pT;function Rs(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:na.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Wn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Rs(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function pi(s){const e=[];let t=0;for(;t<s.byteLength;){const i=na.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const mT=new TextDecoder("ascii"),vT=s=>mT.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",gT=s=>{const e=na.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},ST=s=>{const e=Wn(s,"mdat"),t=Wn(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},bT=(s,e)=>{const t=Wn(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},yT=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Rs(s,"sv3d")){e.is3dVideo=!0;const i=Rs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Rs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Rs(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},TT={validateData:vT,parseInit:yT,getIndexRange:()=>{},parseSegments:gT,parseFeedableSegmentChunk:ST,getSegmentEndTime:bT};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var U;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(U||(U={}));const ru={[k.EBML]:{type:U.Master},[k.EBMLVersion]:{type:U.UnsignedInteger},[k.EBMLReadVersion]:{type:U.UnsignedInteger},[k.EBMLMaxIDLength]:{type:U.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:U.UnsignedInteger},[k.DocType]:{type:U.String},[k.DocTypeVersion]:{type:U.UnsignedInteger},[k.DocTypeReadVersion]:{type:U.UnsignedInteger},[k.Void]:{type:U.Binary},[k.Segment]:{type:U.Master},[k.SeekHead]:{type:U.Master},[k.Seek]:{type:U.Master},[k.SeekID]:{type:U.Binary},[k.SeekPosition]:{type:U.UnsignedInteger},[k.Info]:{type:U.Master},[k.TimestampScale]:{type:U.UnsignedInteger},[k.Duration]:{type:U.Float},[k.Tracks]:{type:U.Master},[k.TrackEntry]:{type:U.Master},[k.Video]:{type:U.Master},[k.Projection]:{type:U.Master},[k.ProjectionType]:{type:U.UnsignedInteger},[k.ProjectionPrivate]:{type:U.Master},[k.Chapters]:{type:U.Master},[k.Cluster]:{type:U.Master},[k.Timestamp]:{type:U.UnsignedInteger},[k.SilentTracks]:{type:U.Master},[k.SilentTrackNumber]:{type:U.UnsignedInteger},[k.Position]:{type:U.UnsignedInteger},[k.PrevSize]:{type:U.UnsignedInteger},[k.SimpleBlock]:{type:U.Binary},[k.BlockGroup]:{type:U.Master},[k.EncryptedBlock]:{type:U.Binary},[k.Attachments]:{type:U.Master},[k.Tags]:{type:U.Master},[k.Cues]:{type:U.Master},[k.CuePoint]:{type:U.Master},[k.CueTime]:{type:U.UnsignedInteger},[k.CueTrackPositions]:{type:U.Master},[k.CueTrack]:{type:U.UnsignedInteger},[k.CueClusterPosition]:{type:U.UnsignedInteger},[k.CueRelativePosition]:{type:U.UnsignedInteger},[k.CueDuration]:{type:U.UnsignedInteger},[k.CueBlockNumber]:{type:U.UnsignedInteger},[k.CueCodecState]:{type:U.UnsignedInteger},[k.CueReference]:{type:U.Master},[k.CueRefTime]:{type:U.UnsignedInteger}},sc=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Hr(s,t),r=i in ru,a=r?ru[i].type:U.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=Hr(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Hr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ot=(s,e)=>{switch(e){case U.SignedInteger:return s.getInt8(0);case U.UnsignedInteger:return Hr(s);case U.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case U.String:return new TextDecoder("ascii").decode(s);case U.UTF8:return new TextDecoder("utf-8").decode(s);case U.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case U.Master:return s;case U.Binary:return s;default:z(e)}},ds=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=sc(i);if(!e(r))return;r.type===U.Master&&ds(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},ET=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=sc(s);return ds(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Ot(o,n):a===k.DocType?t=Ot(o,n):a===k.DocTypeReadVersion&&(i=Ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},rc=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],$T=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],AT=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ds(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===k.SeekID){const b=Ot(p,f);d=Hr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Ot(p,f):h===k.Duration?r=Ot(p,f):h===k.SeekPosition&&d===k.Cues?u=Ot(p,f):h===k.Tracks?ds(p,({tag:b,type:g,value:y})=>b===k.ProjectionType?(l=Ot(y,g)===1,!1):!0):a&&n&&rc.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},wT=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kT=(s,e)=>{let t=!1,i=!1;const r=o=>I(o.time)&&I(o.position),a=[];let n;return ds(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=Ot(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Ot(d,u));break;default:t&&rc.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},_T=s=>{let e=0,t=!1;try{ds(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):$T.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},PT={validateData:ET,parseInit:AT,getIndexRange:wT,parseSegments:kT,parseFeedableSegmentChunk:_T},au=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Qi=(s,e)=>{let t=s;t=Fr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Fr(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},DT=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,g,y,v,E,$,x,j,K,H,q,Q,B,M,X,N,C,Y,se,ve,Ee,Le,Je,ht,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=au(ps);else if(ms){const $e=au(ms);I($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let oa=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],da=vi.includes(Ur.WEBM_AS_IN_FFMPEG)||vi.includes(Ur.WEBM_AS_IN_SPEC)?os.WEBM:os.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ua=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],la=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),ca=$e.querySelector("SegmentTemplate");if(gs===Ue.TEXT){for(const Z of Ss){const Ce=Z.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=Z.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");xe[Ue.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Ue.TEXT,url:gi})}continue}for(const Z of Ss){const Ce=(l=Z.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=Z.getAttribute("codecs"))!==null&&c!==void 0?c:ua)!==null&&h!==void 0?h:"",it=(p=(f=Z.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((g=Z.getAttribute("width"))!==null&&g!==void 0?g:"",10),bs=parseInt((y=Z.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((v=Z.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ts=(E=Z.getAttribute("frameRate"))!==null&&E!==void 0?E:"",ha=($=Z.getAttribute("quality"))!==null&&$!==void 0?$:void 0,fa=Ts?sa(Ts):void 0,pa=(x=Z.getAttribute("id"))!==null&&x!==void 0?x:(oa++).toString(10),ma=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,va=`${pa}@${ma}`,ga=(H=(K=(j=Z.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ga,e).toString(),Sa=[...vi,...la,...gi];let bi;const ba=Z.querySelector("SegmentBase"),je=(q=Z.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:ca;if(ba){const st=(B=(Q=Z.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=Z.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:gt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(X=Z.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(N=Z.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=Qi(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0,$i="",nt=0;if(Wt.length){let ot=Et,De=0;for(const At of Wt){const et=parseInt((Le=At.getAttribute("d"))!==null&&Le!==void 0?Le:"",10),Dt=parseInt((Je=At.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,Qt=parseInt((ht=At.getAttribute("t"))!==null&&ht!==void 0?ht:"",10);De=Number.isFinite(Qt)?Qt:De;const $s=et/rt*1e3,Ui=De/rt*1e3;for(let Vi=0;Vi<Dt+1;Vi++){const cc=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:(De+Vi*et).toString(10)})),Do=(Ui!=null?Ui:0)+Vi*$s,hc=Do+$s;ot++,$t.push({time:{from:Do,to:hc},url:cc})}De+=(Dt+1)*et,at+=(Dt+1)*$s}nt=De/rt*1e3,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:De.toString(10)}))}else if(I(Ge)){const De=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,At=Math.ceil(Ge/De);let et=0;for(let Dt=1;Dt<At;Dt++){const Qt=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:Dt.toString(10),segmentTime:et.toString(10)}));$t.push({time:{from:et,to:et+De},url:Qt}),et+=De}nt=et,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:At.toString(10),segmentTime:et.toString(10)}))}const Ai={time:{from:nt,to:1/0},url:$i};bi={type:gt.TEMPLATE,baseUrl:Es,segmentTemplateUrl:Ze,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t,nextSegmentBeyondManifest:Ai,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Ue.VIDEO,audio:Ue.AUDIO,text:Ue.TEXT}[it];yi&&xe[yi].push({id:va,kind:yi,segmentReference:bi,profiles:Sa,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:fa,quality:ha})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:da,representations:xe}},IT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},RT=({id:s,bitrate:e})=>({id:s,bitrate:e}),LT=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},xT=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),nu=s=>"size"in s,qi=s=>s.type===gt.TEMPLATE,Qn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class ou{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new O,this.gaps=[],this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){const h=this.representations.get(c);D(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new q0(this.sourceBuffer),this.subscription.add(V(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(V(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Mr(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield _(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),S=this.parsedInitData.get(h.id);if(D(f,"No init buffer for starting representation"),D(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(p,h),yield yield _(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);D(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(W(p)||W(f)?yield yield _(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield _(p)),f=this.segments.get(c),D(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const S=this.getCurrentPosition();I(S)&&(this.isLive||(f.forEach(b=>b.status=te.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(c){var h;return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield _(void 0);for(const y of this.representations.keys()){const v=c.find(x=>x.id===y);v&&this.representations.set(y,v);const E=this.representations.get(y);if(!E||!qi(E.segmentReference))return yield _(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,p=this.representations.get(f);D(p);const S=this.segments.get(f);D(S,"No segments for starting representation");const b=this.initData.get(f);if(D(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield _(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield _(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(S,p),yield yield _(this.sourceBufferTaskQueue.append(b,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case os.MP4:this.containerParser=TT;break;case os.WEBM:this.containerParser=PT;break;default:z(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=tt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Mr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Oe(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Oe(i,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;I(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!qi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!qi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Qi(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:te.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==gt.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){t.segmentReference.type===gt.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return J(this,void 0,void 0,function*(){e.status=te.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield fe(o,function(){return pe(this,arguments,function*(){const l=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(c=>setTimeout(c,l)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=te.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Qn(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}})}loadByteRangeSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=te.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield fe(n,function(){return pe(this,arguments,function*(){const u=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Qn(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(qi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Oe(e,0).byte.from,to:Oe(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&I(r)&&(i=tt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){return J(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=te.PARTIALLY_FED,o.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===gt.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,g=S<r,y=b<=r;if(c.status===te.DOWNLOADING&&g&&y){c.status=te.DOWNLOADED;const v=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(v,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const v=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?v:this.containerParser.parseFeedableSegmentChunk(v);E!=null&&E.byteLength&&(c.status=te.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=te.FED,nu(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===te.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=te.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Br(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return J(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>J(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&qi(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=nu(d)?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Br(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var es;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(es||(es={}));class CT{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(_s));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?es.HEADER:es.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return pe(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case es.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case es.PARAM:{const M=new URL(p,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),p=M.toString();break}default:z(a)}this.requestQuic&&(p=li(p));let b=this.abortAllController.signal,g;if(d){const M=new St;if(g=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{M.abort()}catch(X){_s(X)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(X){_s(X)}b=M.signal}const y=he(),v=yield yield _(Ci(p,{priority:u,headers:S,signal:b}).catch(_s)),E=he();if(!v)return g==null||g.unsubscribe(),yield _(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!v.ok||!v.body)return g==null||g.unsubscribe(),yield _(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!o&&!l)return g==null||g.unsubscribe(),yield _(v.arrayBuffer());const[$,x]=v.body.tee(),j=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(x,c));let K=0,H=new Uint8Array(0),q=!1;const Q=M=>{g==null||g.unsubscribe(),q=!0,_s(M)},B=fe(b,function({done:M,value:X}){return pe(this,arguments,function*(){if(K===0&&this.lastRequestFirstBytes$.next(he()-y),b.aborted)return g==null||g.unsubscribe(),yield _(void 0);if(!M&&X){const N=new Uint8Array(H.length+X.length);N.set(H),N.set(X,H.length),H=N,K+=X.byteLength,o==null||o(new DataView(H.buffer),K),yield yield _(j==null?void 0:j.read().then(B,Q))}})}.bind(this));return yield yield _(j==null?void 0:j.read().then(B,Q)),g==null||g.unsubscribe(),yield _(q?null:H.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==gt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(null);const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const g=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);v=new DataView($)}const E=a.parseSegments(v,g,y);return yield _({init:g,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==gt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=wo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return J(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case gt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case gt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _s=s=>{if(!Qn(s))throw s},Kn=1e3,Gr=(s,e,t)=>t*e+(1-t)*s,ac=(s,e)=>s.reduce((t,i)=>t+i,0)/e,OT=(s,e,t,i)=>{let r=0,a=t;const n=ac(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Po{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new xt(`raw_${i}`),this.smoothedSeries$=new xt(`smoothed_${i}`),this.reportedSeries$=new xt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(W(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 BT extends Po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Gr(this.slow,e,this.params.emaAlphaSlow),this.fast=Gr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class MT extends Po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ac(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gr(this.emaSmoothed,e,this.params.emaAlpha);const i=OT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class NT extends Po{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?Gr(this.smoothed,e,this.params.emaAlpha):e}}class Jn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new BT({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new MT({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new NT(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const FT=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},du=["timeupdate","progress","play","seeked","stalled","waiting"];var mt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(mt||(mt={}));let UT=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(mt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(mt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(mt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){const i=yield yield _(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!i)return yield _(null);let r;try{r=DT(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield _(null);const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Ue.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield _(Object.assign(Object.assign({},r),{representations:Li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(mt.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new ou(Ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],I(i)&&(this.audioBufferManager=new ou(Ue.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ri(Kn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+Kn,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...du.map(o=>V(this.element,o))).pipe(P(o=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),ye(),oe(o=>!!o),Bs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),FT(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(p=>{var S,b;return(b=(S=p.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Be({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:u,bufferLength:d})=>J(this,void 0,void 0,function*(){if(D(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let g=Lt.None;if(this.isActiveLowLatency?g=Lt.ActiveLowLatency:b<f+S&&b>=f?g=Lt.LiveWithTargetOffset:c!==0&&b<f&&(g=Lt.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),g===Lt.LiveForwardBuffering||g===Lt.LiveWithTargetOffset){const y=o-(f+p),v=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(v-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:v>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=v:$=0,this.manifestUrlString=qe(this.manifestUrlString,$,Te.DASH_CMAF_OFFSET_P)}g!==Lt.None&&g!==Lt.ActiveLowLatency&&(o=0,this.updateLive())})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(G(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield _(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),I(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&I(i)?yield yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(mt.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ri(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new CT({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Jn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,a;return J(this,void 0,void 0,function*(){D(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=qe(this.manifestUrlString,n,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))})}initBuffer(){D(this.element),this.state$.setState(mt.RUNNING),this.subscription.add(G(...du.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const i={[Ue.VIDEO]:this.videoBufferManager,[Ue.AUDIO]:this.audioBufferManager,[Ue.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;D(this.element),D(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),as(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(mt.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.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),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}waitingEventCallback(){return J(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:R.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return J(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class nc{constructor(e){this.subscription=new ce,this.videoState=new me(we.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==we.STOPPED&&n!==m.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===m.STOPPED){a!==we.STOPPED&&(this.videoState.startTransitionTo(we.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(we.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case we.STOPPED:this.videoState.startTransitionTo(we.READY),this.prepare();return;case we.READY:n===m.PAUSED?(this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case we.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(we.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case we.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new UT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(P(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(we.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(we.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===we.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===mt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=RT(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=IT(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&LT(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=xT(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===mt.REPRESENTATIOS_READY&&(this.videoState.setState(we.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==mt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Ue.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ue.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ye(),P(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=Ni(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}}class VT extends nc{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let HT=class extends ec{constructor(e){super(e),this.liveOffset=new Js}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Be({interval:Ri(qn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ae.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===m.PAUSED&&i===Ae.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class GT extends nc{constructor(e){super(e),this.liveOffset=new Js}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Be({interval:Ri(Kn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===we.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===m.PAUSED&&i===we.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const Rt={};var le;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const Ps=(s,e)=>new Yr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class jT{constructor(e){this.subscription=new ce,this.videoState=new me(le.INITIALIZING),this.textTracksManager=new Pt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==le.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case le.STOPPED:break;case le.READY:case le.PLAYING:case le.PAUSED:this.stop();break;default:z(t)}break;case m.READY:switch(t){case le.STOPPED:this.prepare();break;case le.READY:case le.PLAYING:case le.PAUSED:break;default:z(t)}break;case m.PLAYING:switch(t){case le.PLAYING:break;case le.STOPPED:this.prepare();break;case le.READY:case le.PAUSED:this.playIfAllowed();break;default:z(t)}break;case m.PAUSED:switch(t){case le.PAUSED:break;case le.STOPPED:this.prepare();break;case le.READY:this.videoState.setState(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED);break;case le.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Ft(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(Qe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ks(import("hls.js").then(r=>{e||(Rt.Hls=r.default,Rt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){D(Rt.Hls,"hls.js not loaded"),this.hls=new Rt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(le.STOPPED)}subscribe(){D(Rt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Vt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(fi(this.video,e.isLooped,i)),this.subscription.add(Nt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ps(this.hls,Rt.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),L(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),L(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i)),a(Ps(this.hls,Rt.Events.MANIFEST_PARSED).pipe(P(({levels:d})=>d.reduce((l,c)=>{var h,f;const p=c.name||c.height.toString(10),{width:S,height:b}=c,g=(f=hs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:ci({width:S,height:b});if(!g)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(p,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(Ps(this.hls,Rt.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",p=c.lang,S="internal";l.push({id:h,url:f,language:p,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(Ps(this.hls,Rt.Events.LEVEL_LOADING).pipe(P(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(kt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Ps(this.hls,Rt.Events.LEVEL_SWITCHED).pipe(P(({level:d})=>n(this.hls.levels[d])));o.pipe(oe(I)).subscribe(t.currentVideoTrack$,i),this.subscription.add(kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(W(d))return;const c=(l=this.trackLevels.get(d.id))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,p=this.hls.levels[f];!p||c.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=G(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(le.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(le.PLAYING),(yield si(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t})))||(this.videoState.setState(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(le.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(le.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0)}}const uu="X-Playback-Duration";var lu=s=>J(void 0,void 0,void 0,function*(){var e;const t=yield Ci(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(uu)?parseInt(t.headers.get(uu),10):void 0});const YT=s=>{let e=null;if(s.QUALITY&&(e=hs(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ci({width:t,height:i})}return e!=null?e:null},oc=(s,e=s)=>J(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Ci(s)).text()).split(`
46
- `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Li(c[1].split(",").map(E=>E.split("="))),p=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=YT(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(x=>parseInt(x,10));E&&$&&(y={width:E,height:$})}const v=new URL(n[++d],e).toString();S&&o.push({id:p,quality:S,url:v,bandwidth:b,size:y,fps:g})}if(h){const f=Li(h[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),p=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;p&&S&&u.push({type:"internal",id:S,label:b,language:S,url:p,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}});var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class zT{constructor(e){var t;this.subscription=new ce,this.videoState=new me(ge.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.liveOffset=new Js,this.manifestStartTime$=new T(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===m.STOPPED){r!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&c.state===ie.Requested){this.videoState.startTransitionTo(ge.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ge.READY:a===m.READY?L(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ge.PAUSED:if(a===m.PLAYING)if(this.videoState.startTransitionTo(ge.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);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===m.PAUSED&&(L(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case ge.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.INVARIANT,url:this.params.source.url},oc(qe(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:R.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Qe(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,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ye(),P(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&I(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ie.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Be({startTime:this.manifestStartTime$.pipe(oe(I)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(P(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===A.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,u=qe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),lu(u).then(d=>{var l;if(!W(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(W(c)||!isFinite(c))try{Ci(u).then(h=>h.text()).then(h=>{var f;const p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(p){const S=new URL(p,u).toString();lu(S).then(b=>{W(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var be;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(be||(be={}));class qT{constructor(e){this.subscription=new ce,this.videoState=new me(be.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===m.STOPPED){i!==be.STOPPED&&(this.videoState.startTransitionTo(be.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(be.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===be.STOPPED){this.videoState.startTransitionTo(be.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(be.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&l.state===ie.Requested&&this.seek(l.position),i){case be.READY:r===m.READY?L(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed());return;case be.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(be.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case be.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;case be.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.INVARIANT,url:this.params.source.url},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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),oc(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(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.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(be.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(be.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===be.READY&&this.videoState.setState(be.READY),this.videoState.getState()===be.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&I(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===be.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ie.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(P(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!bc()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(G(V(o,"addtrack"),V(o,"removetrack"),V(o,"change"),We(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&d&&n.searchParams.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ke;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ke||(ke={}));class WT{constructor(e){this.subscription=new ce,this.videoState=new me(ke.STOPPED),this.trackUrls={},this.textTracksManager=new Pt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===m.STOPPED){a!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.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(ke.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==ke.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ke.STOPPED){this.videoState.startTransitionTo(ke.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==m.PAUSED&&c.state===ie.Requested&&this.seek(c.position),a){case ke.READY:n===m.READY?L(this.params.desiredState.playbackState,m.READY):n===m.PAUSED?(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed());return;case ke.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(ke.PAUSED),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ke.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ke.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ke.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ke.READY&&this.videoState.setState(ke.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&I(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===ke.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;D(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];D(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=li(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Qe(i))}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(i=Object.values(this.trackUrls).find(c=>!Ii(c.track.quality)&&Tu(c.track.quality,e)))===null||i===void 0?void 0:i.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&An(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Ii(f.track.quality)&&ts(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=Ni(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const cu=["stun:videostun.mycdn.me:80"],QT=1e3,KT=3,un=()=>null;class JT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=un,this.externalStopCallback=un,this.externalErrorCallback=un,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return J(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 J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:cu}]};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 J(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 J(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:R.WTF,message:e.message})}onPeerConnectionStream(e){return J(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 J(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),QT)}normalizeOptions(e={}){const t={stunServerList:cu,maxRetryNumber:KT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Se||(Se={}));class XT{constructor(e){this.videoState=new me(Se.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case Se.READY:i===m.PAUSED?(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Se.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ft(e.container),this.liveStreamClient=new JT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};G(this.videoState.stateChangeStarted$.pipe(P(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Vt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===Se.READY&&this.videoState.setState(Se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Nt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case Se.READY:break;case Se.PAUSED:t.playbackState.setState(m.PAUSED);break;case Se.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return z(n.to)}},i)).add(G(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(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:ft.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class hu{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!!this.current.done}}var ln,cn,hn,fn,pn,mn,vn,gn,gr,Sn,Sr,bn,br,yn,yr,Tn,Tr,En,Er,$n;const dc=jr().device===yc.Android,di=document.createElement("video"),ZT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',eE='video/mp4; codecs="hev1.1.6.L93.B0"',uc='video/webm; codecs="vp09.00.10.08"',lc='video/webm; codecs="av01.0.00M.08"',tE='audio/mp4; codecs="mp4a.40.2"',iE='audio/webm; codecs="opus"',Me={mms:!!(window.ManagedMediaSource&&(!((cn=(ln=window.ManagedSourceBuffer)===null||ln===void 0?void 0:ln.prototype)===null||cn===void 0)&&cn.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((fn=(hn=window.SourceBuffer)===null||hn===void 0?void 0:hn.prototype)===null||fn===void 0)&&fn.appendBuffer)),hls:!!(!((pn=di.canPlayType)===null||pn===void 0)&&pn.call(di,"application/x-mpegurl")||!((mn=di.canPlayType)===null||mn===void 0)&&mn.call(di,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},dt={mp4:!!(!((vn=di.canPlayType)===null||vn===void 0)&&vn.call(di,"video/mp4")),webm:!!(!((gn=di.canPlayType)===null||gn===void 0)&&gn.call(di,"video/webm")),cmaf:!0},Bt={h264:!!(!((Sn=(gr=window.MediaSource||window.ManagedMediaSource)===null||gr===void 0?void 0:gr.isTypeSupported)===null||Sn===void 0)&&Sn.call(gr,ZT)),h265:!!(!((bn=(Sr=window.MediaSource||window.ManagedMediaSource)===null||Sr===void 0?void 0:Sr.isTypeSupported)===null||bn===void 0)&&bn.call(Sr,eE)),vp9:!!(!((yn=(br=window.MediaSource||window.ManagedMediaSource)===null||br===void 0?void 0:br.isTypeSupported)===null||yn===void 0)&&yn.call(br,uc)),av1:!!(!((Tn=(yr=window.MediaSource||window.ManagedMediaSource)===null||yr===void 0?void 0:yr.isTypeSupported)===null||Tn===void 0)&&Tn.call(yr,lc)),aac:!!(!((En=(Tr=window.MediaSource||window.ManagedMediaSource)===null||Tr===void 0?void 0:Tr.isTypeSupported)===null||En===void 0)&&En.call(Tr,tE)),opus:!!(!(($n=(Er=window.MediaSource||window.ManagedMediaSource)===null||Er===void 0?void 0:Er.isTypeSupported)===null||$n===void 0)&&$n.call(Er,iE))},Wi=(Bt.h264||Bt.h265)&&Bt.aac;var oi;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(oi||(oi={}));var Xt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Xt||(Xt={}));let ki;const sE=()=>J(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={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({},s),{video:Object.assign(Object.assign({},s.video),{contentType:lc})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:uc})}))]);ki={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}});try{sE()}catch(s){console.error(s)}const Vs=Me.hls&&dt.mp4,rE=()=>Object.keys(Bt).filter(s=>Bt[s]),aE=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return Me.mse&&dt.mp4&&Wi;case A.DASH_SEP:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.DASH_WEBM:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.vp9&&Bt.opus;case A.DASH_WEBM_AV1:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.av1&&Bt.opus;case A.DASH_LIVE:return Me.mse&&dt.mp4&&Wi;case A.DASH_LIVE_CMAF:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi&&dt.cmaf;case A.DASH_ONDEMAND:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.HLS:case A.HLS_ONDEMAND:return Vs||e&&Me.mse&&dt.mp4&&Wi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Vs;case A.MPEG:return dt.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Bt.h264&&(dt.mp4||dt.webm);default:return z(i)}}),Ds=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case oi.VP9:return[e,t];case oi.AV1:return[t,e];case oi.NONE:return[];case oi.SMOOTH:return ki?ki[t].smooth?[t,e]:ki[e].smooth?[e,t]:[t,e]:[e,t];case oi.POWER_EFFICIENT:return ki?ki[t].powerEfficient?[t,e]:ki[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},nE=({webmCodec:s,androidPreferredFormat:e})=>{if(dc)switch(e){case Xt.MPEG:return[A.MPEG,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Xt.HLS:return[A.HLS,A.HLS_ONDEMAND,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Xt.DASH:return[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Vs?[...Ds(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},oE=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(dc)switch(s){case Xt.DASH:{o=a;break}case Xt.HLS:case Xt.MPEG:{o=n;break}}else Vs?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},fu=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var dE=s=>new Yr(e=>{const t=new ce,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(P(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(P(({type:d})=>d!==void 0)),n=new O;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const uE={cacheDuration:12e4},lE={chunkDuration:5e3,maxParallelRequests:5};class cE{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,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),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new O,warning$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$: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),is3DVideo$:new T(!1)},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=aE([...oE(this.params.tuning),...nE(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>I(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new hu(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new hu(n.filter(o=>I(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(console.log("Choose provider "+t),W(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!==ie.None;if(this.params.desiredState.seekState.setState({state:ie.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ye.SCREEN:return this.createScreenProvider(t);case Ye.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return D(o),new cy(Object.assign(Object.assign({},n),{source:o,config:uE}))}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJs?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new VT(Object.assign(Object.assign({},n),{source:o}))):new z0(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJsCMAF?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new GT(Object.assign(Object.assign({},n),{source:o})):new HT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),Vs||!this.params.tuning.useHlsJs?new qT(Object.assign(Object.assign({},n),{source:o})):new jT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new zT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new WT(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ny(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},lE),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new XT({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new gb({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ye.CHROMECAST:Ye.SCREEN}chooseFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.next();case Ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return z(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:i(e.url)})}return Li(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ce;let t=!1,i=0;const r=he();return e.add(G(this.providerOutput.error$,dE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(P(a=>({id:`ProviderHangup:${a}`,category:R.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===Ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===R.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,l=u&&(o&&t||!d),c=a.id.includes("partial_metadata"),h=he()-r;l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c&&h<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ye.SCREEN)}})),e}}const hE=5e3,pu="one_video_throughput",mu="one_video_rtt",Zt=window.navigator.connection,vu=()=>{const s=Zt==null?void 0:Zt.downlink;if(I(s)&&s!==10)return s*1e3},gu=()=>{const s=Zt==null?void 0:Zt.rtt;if(I(s)&&s!==3e3)return s},Su=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Os{constructor(e){var t,i;this.subscription=new ce,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Os.load(pu)||(e.useBrowserEstimation?vu():void 0)||hE,a=(i=(t=Os.load(mu))!==null&&t!==void 0?t:e.useBrowserEstimation?gu():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Su(r,a,e.rttPenaltyRequestSize)),this.throughput=Jn.getSmoothedValue(r,-1,e),this.rtt=Jn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vu();u&&this.throughput.next(u);const d=gu();I(d)&&this.rtt.next(d)};Zt&&"onchange"in Zt&&this.subscription.add(V(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ya.set(pu,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ya.set(mu,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Be({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P(({throughput:n,rtt:o})=>Su(n,o,e.rttPenaltyRequestSize)),oe(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=he();const r=new ce;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(V(e,"progress").pipe(_e()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(V(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(V(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=he(),n=0,o=he();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>J(this,void 0,void 0,function*(){if(l)!t&&this.addRawSpeed(r,he()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=he()}o=he()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());yield i==null?void 0:i.read().then(d,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(Os.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=ya.get(e);if(I(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const bu={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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ft.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},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:!1,webmCodec:oi.VP9,androidPreferredFormat:Xt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},fE=s=>{var e;return Object.assign(Object.assign({},Tc(s,bu)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...bu.configName]})};var yu=({seekState:s,position$:e})=>G(s.stateChangeEnded$.pipe(P(({to:t})=>{var i;return t.state===ie.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),oe(I)),e.pipe(oe(()=>s.getState().state===ie.None))),pE=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return D(e,`Wrong container or containerId {${s.container}}`),e};const mE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(oe(r=>r.length>0),_e()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class jE{constructor(e={configName:[]}){if(this.subscription=new ce,this.logger=new Ec,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new me(m.STOPPED),seekState:new me({state:ie.None}),volume:new me({volume:1,muted:!1}),videoTrack:new me(void 0),autoVideoTrackSwitching:new me(!0),autoVideoTrackLimits:new me({}),isLooped:new me(!1),playbackRate:new me(1),externalTextTracks:new me([]),internalTextTracks:new me([]),currentTextTrack:new me(void 0),textTrackCuesSettings:new me({}),cameraOrientation:new me({x:0,y:0})},this.info={playbackState$:new T(m.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),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$: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(ni.NONE),chromecastState$:new T(Ne.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new O,ready$:new O,started$:new O,playing$:new O,paused$:new O,stopped$:new O,willStart$:new O,willResume$:new O,willPause$:new O,willStop$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Ub},this.initLogs(),this.tuning=fE(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wc({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Os(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const p=typeof f;return["number","string","boolean"].includes(p)?f:f===null?null:`<${p}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=pE(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new cE({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},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()===m.STOPPED&&e.startTransitionTo(m.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==m.PLAYING&&t.startTransitionTo(m.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?V(document,"visibilitychange").pipe(_e()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ie.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()===Ne.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()===Ne.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;D(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return mE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ie.None?void 0:t.position;return I(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(G(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(P(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===m.STOPPED),_e()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case m.READY:this.events.ready$.next();break;case m.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case m.PAUSED:this.events.paused$.next();break;case m.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case m.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ie.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:ie.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ie.Applying&&(this.desiredState.seekState.setState({state:ie.None}),this.events.seeked$.next())})).add(e.current$.pipe(P(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(P(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(P(n=>n.map(({quality:o})=>o).sort((o,u)=>Ii(o)?1:Ii(u)?-1:ts(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.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(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(P(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.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Be({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(P(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Be({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(P(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(P(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(P(n=>n.volume),ye()).subscribe(this.info.volume$)).add(yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(G(e.providerOutput.endedEvent$.pipe(ss(!0)),e.providerOutput.seekedEvent$.pipe(ss(!1))).pipe(ye()).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(P(n=>({id:n?`No${n}`:"NoProviders",category:R.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(_e(),P(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),P(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),P(()=>he()-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 i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>i.next(!1)));let r=0;const a=G(e.providerOutput.isBuffering$,t,i).pipe(P(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ye());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(G(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,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(G(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Ne.CONNECTED?l=ni.SECOND_SCREEN:u?n?l=ni.PIP:o?l=ni.FULLSCREEN:l=ni.INLINE:l=ni.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(P(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 ce;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=Ni(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(G(this.desiredState.videoTrack.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(P(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;D(this.providerContainer),D(t),Fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Nb(i)),this.providerContainer.current$.subscribe(({type:i})=>fr("provider",i)),t.duration$.subscribe(i=>fr("duration",i)),t.availableVideoTracks$.pipe(oe(i=>!!i.length),_e()).subscribe(i=>fr("tracks",i)),this.events.fatalError$.subscribe(new xt("fatalError")),this.events.managedError$.subscribe(new xt("managedError")),t.position$.subscribe(new xt("position")),t.currentVideoTrack$.pipe(P(i=>i==null?void 0:i.quality)).subscribe(new xt("quality")),this.info.currentBuffer$.subscribe(new xt("buffer")),t.isBuffering$.subscribe(new xt("isBuffering"))].forEach(i=>this.subscription.add(i)),fr("codecs",rE())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>J(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:R.DOM,message:String(r)})})});this.subscription.add(G(V(document,"visibilitychange"),V(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const YE=`@vkontakte/videoplayer-core@${$c}`;export{Ne as ChromecastState,Ms as HttpConnectionType,WE as Observable,m as PlaybackState,jE as Player,YE as SDK_VERSION,QE as Subject,KE as Subscription,ni as Surface,$c as VERSION,JE as ValueSubject,A as VideoFormat,XE as VideoQuality};
45
+ varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Zl{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new H0(this.params.fov,this.params.orientation),this.cameraRotationManager=new G0(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(j0,this.gl.VERTEX_SHADER),i=this.createShader(Y0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let ec=class{constructor(e){this.subscription=new ce,this.videoState=new me(Ae.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==Ae.STOPPED&&n!==m.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===m.STOPPED){a!==Ae.STOPPED&&(this.videoState.startTransitionTo(Ae.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(Ae.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case Ae.STOPPED:this.videoState.startTransitionTo(Ae.READY),this.prepare();return;case Ae.READY:n===m.PAUSED?(this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case Ae.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(Ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Ae.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new V0({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(P(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ae.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ae.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===pt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=Ky(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=Qy(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&Jy(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=Xy(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===pt.REPRESENTATIOS_READY&&(this.videoState.setState(Ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==pt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Fe.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Fe.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ye(),P(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=Ni(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}},z0=class extends ec{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ue;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ue||(Ue={}));var Lt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(Lt||(Lt={}));var Ur;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Ur||(Ur={}));var gt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(gt||(gt={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var os;(function(s){s.MP4="mp4",s.WEBM="webm"})(os||(os={}));var Vr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Vr||(Vr={}));var we;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(we||(we={}));var on,dn;let tc=!1;try{tc=jr().browser===Xn.Safari&&parseInt((dn=(on=navigator.userAgent.match(/Version\/(\d+)/))===null||on===void 0?void 0:on[1])!==null&&dn!==void 0?dn:"",10)<16}catch(s){console.error(s)}class q0{constructor(e){this.bufferFull$=new O,this.error$=new O,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return J(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let i;tc&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.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:z(t)}}}class Tt{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class ic extends Tt{}class W0 extends Tt{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Q0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class K0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class J0 extends Tt{constructor(e){super(e),this.data=this.content}}class ri extends Tt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class X0 extends ri{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class Z0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class eT extends Tt{parseChildrenBoxes(){return pi(this.content)}}var Di;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Di||(Di={}));class tT extends ri{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Di.MONOSCOPIC;break;case 1:this.stereoMode=Di.TOP_BOTTOM;break;case 2:this.stereoMode=Di.LEFT_RIGHT;break;case 3:this.stereoMode=Di.STEREO_CUSTOM;break;case 4:this.stereoMode=Di.RIGHT_LEFT;break}this.cursor+=1}}class iT extends ri{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class sT extends ri{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class rT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class aT extends ri{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class nT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class oT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class dT extends ri{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class uT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class lT extends ri{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class cT extends ri{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class hT extends ri{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const fT={ftyp:W0,moov:Q0,moof:K0,mdat:J0,sidx:X0,trak:Z0,mdia:rT,mfhd:dT,tkhd:aT,traf:uT,tfhd:lT,tfdt:cT,trun:hT,minf:nT,sv3d:eT,st3d:tT,prhd:iT,proj:oT,equi:sT,unknown:ic};class pT{createBox(e,t){const i=fT[e];return i?new i(t):new ic(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return na.createBox(i,new DataView(e.buffer,e.byteOffset))}}const na=new pT;function Rs(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:na.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Wn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Rs(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function pi(s){const e=[];let t=0;for(;t<s.byteLength;){const i=na.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const mT=new TextDecoder("ascii"),vT=s=>mT.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",gT=s=>{const e=na.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},ST=s=>{const e=Wn(s,"mdat"),t=Wn(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},bT=(s,e)=>{const t=Wn(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},yT=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Rs(s,"sv3d")){e.is3dVideo=!0;const i=Rs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Rs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Rs(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},TT={validateData:vT,parseInit:yT,getIndexRange:()=>{},parseSegments:gT,parseFeedableSegmentChunk:ST,getSegmentEndTime:bT};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var U;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(U||(U={}));const ru={[k.EBML]:{type:U.Master},[k.EBMLVersion]:{type:U.UnsignedInteger},[k.EBMLReadVersion]:{type:U.UnsignedInteger},[k.EBMLMaxIDLength]:{type:U.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:U.UnsignedInteger},[k.DocType]:{type:U.String},[k.DocTypeVersion]:{type:U.UnsignedInteger},[k.DocTypeReadVersion]:{type:U.UnsignedInteger},[k.Void]:{type:U.Binary},[k.Segment]:{type:U.Master},[k.SeekHead]:{type:U.Master},[k.Seek]:{type:U.Master},[k.SeekID]:{type:U.Binary},[k.SeekPosition]:{type:U.UnsignedInteger},[k.Info]:{type:U.Master},[k.TimestampScale]:{type:U.UnsignedInteger},[k.Duration]:{type:U.Float},[k.Tracks]:{type:U.Master},[k.TrackEntry]:{type:U.Master},[k.Video]:{type:U.Master},[k.Projection]:{type:U.Master},[k.ProjectionType]:{type:U.UnsignedInteger},[k.ProjectionPrivate]:{type:U.Master},[k.Chapters]:{type:U.Master},[k.Cluster]:{type:U.Master},[k.Timestamp]:{type:U.UnsignedInteger},[k.SilentTracks]:{type:U.Master},[k.SilentTrackNumber]:{type:U.UnsignedInteger},[k.Position]:{type:U.UnsignedInteger},[k.PrevSize]:{type:U.UnsignedInteger},[k.SimpleBlock]:{type:U.Binary},[k.BlockGroup]:{type:U.Master},[k.EncryptedBlock]:{type:U.Binary},[k.Attachments]:{type:U.Master},[k.Tags]:{type:U.Master},[k.Cues]:{type:U.Master},[k.CuePoint]:{type:U.Master},[k.CueTime]:{type:U.UnsignedInteger},[k.CueTrackPositions]:{type:U.Master},[k.CueTrack]:{type:U.UnsignedInteger},[k.CueClusterPosition]:{type:U.UnsignedInteger},[k.CueRelativePosition]:{type:U.UnsignedInteger},[k.CueDuration]:{type:U.UnsignedInteger},[k.CueBlockNumber]:{type:U.UnsignedInteger},[k.CueCodecState]:{type:U.UnsignedInteger},[k.CueReference]:{type:U.Master},[k.CueRefTime]:{type:U.UnsignedInteger}},sc=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Hr(s,t),r=i in ru,a=r?ru[i].type:U.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=Hr(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Hr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ot=(s,e)=>{switch(e){case U.SignedInteger:return s.getInt8(0);case U.UnsignedInteger:return Hr(s);case U.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case U.String:return new TextDecoder("ascii").decode(s);case U.UTF8:return new TextDecoder("utf-8").decode(s);case U.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case U.Master:return s;case U.Binary:return s;default:z(e)}},ds=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=sc(i);if(!e(r))return;r.type===U.Master&&ds(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},ET=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=sc(s);return ds(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Ot(o,n):a===k.DocType?t=Ot(o,n):a===k.DocTypeReadVersion&&(i=Ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},rc=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],$T=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],AT=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ds(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===k.SeekID){const b=Ot(p,f);d=Hr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Ot(p,f):h===k.Duration?r=Ot(p,f):h===k.SeekPosition&&d===k.Cues?u=Ot(p,f):h===k.Tracks?ds(p,({tag:b,type:g,value:y})=>b===k.ProjectionType?(l=Ot(y,g)===1,!1):!0):a&&n&&rc.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},wT=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kT=(s,e)=>{let t=!1,i=!1;const r=o=>I(o.time)&&I(o.position),a=[];let n;return ds(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=Ot(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Ot(d,u));break;default:t&&rc.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},_T=s=>{let e=0,t=!1;try{ds(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):$T.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},PT={validateData:ET,parseInit:AT,getIndexRange:wT,parseSegments:kT,parseFeedableSegmentChunk:_T},au=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Qi=(s,e)=>{let t=s;t=Fr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Fr(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},DT=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,g,y,v,E,$,x,j,K,H,q,Q,B,M,X,N,C,Y,se,ve,Ee,Le,Je,ht,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=au(ps);else if(ms){const $e=au(ms);I($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let oa=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],da=vi.includes(Ur.WEBM_AS_IN_FFMPEG)||vi.includes(Ur.WEBM_AS_IN_SPEC)?os.WEBM:os.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ua=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],la=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),ca=$e.querySelector("SegmentTemplate");if(gs===Ue.TEXT){for(const Z of Ss){const Ce=Z.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=Z.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");xe[Ue.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Ue.TEXT,url:gi})}continue}for(const Z of Ss){const Ce=(l=Z.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=Z.getAttribute("codecs"))!==null&&c!==void 0?c:ua)!==null&&h!==void 0?h:"",it=(p=(f=Z.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((g=Z.getAttribute("width"))!==null&&g!==void 0?g:"",10),bs=parseInt((y=Z.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((v=Z.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ts=(E=Z.getAttribute("frameRate"))!==null&&E!==void 0?E:"",ha=($=Z.getAttribute("quality"))!==null&&$!==void 0?$:void 0,fa=Ts?sa(Ts):void 0,pa=(x=Z.getAttribute("id"))!==null&&x!==void 0?x:(oa++).toString(10),ma=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,va=`${pa}@${ma}`,ga=(H=(K=(j=Z.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ga,e).toString(),Sa=[...vi,...la,...gi];let bi;const ba=Z.querySelector("SegmentBase"),je=(q=Z.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:ca;if(ba){const st=(B=(Q=Z.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=Z.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:gt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(X=Z.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(N=Z.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=Qi(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0,$i="",nt=0;if(Wt.length){let ot=Et,De=0;for(const At of Wt){const et=parseInt((Le=At.getAttribute("d"))!==null&&Le!==void 0?Le:"",10),Dt=parseInt((Je=At.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,Qt=parseInt((ht=At.getAttribute("t"))!==null&&ht!==void 0?ht:"",10);De=Number.isFinite(Qt)?Qt:De;const $s=et/rt*1e3,Ui=De/rt*1e3;for(let Vi=0;Vi<Dt+1;Vi++){const cc=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:(De+Vi*et).toString(10)})),Do=(Ui!=null?Ui:0)+Vi*$s,hc=Do+$s;ot++,$t.push({time:{from:Do,to:hc},url:cc})}De+=(Dt+1)*et,at+=(Dt+1)*$s}nt=De/rt*1e3,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:De.toString(10)}))}else if(I(Ge)){const De=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,At=Math.ceil(Ge/De);let et=0;for(let Dt=1;Dt<At;Dt++){const Qt=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:Dt.toString(10),segmentTime:et.toString(10)}));$t.push({time:{from:et,to:et+De},url:Qt}),et+=De}nt=et,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:At.toString(10),segmentTime:et.toString(10)}))}const Ai={time:{from:nt,to:1/0},url:$i};bi={type:gt.TEMPLATE,baseUrl:Es,segmentTemplateUrl:Ze,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t,nextSegmentBeyondManifest:Ai,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Ue.VIDEO,audio:Ue.AUDIO,text:Ue.TEXT}[it];yi&&xe[yi].push({id:va,kind:yi,segmentReference:bi,profiles:Sa,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:fa,quality:ha})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:da,representations:xe}},IT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},RT=({id:s,bitrate:e})=>({id:s,bitrate:e}),LT=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},xT=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),nu=s=>"size"in s,qi=s=>s.type===gt.TEMPLATE,Qn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class ou{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new O,this.gaps=[],this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){const h=this.representations.get(c);D(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new q0(this.sourceBuffer),this.subscription.add(V(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(V(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Mr(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield _(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),S=this.parsedInitData.get(h.id);if(D(f,"No init buffer for starting representation"),D(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(p,h),yield yield _(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);D(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(W(p)||W(f)?yield yield _(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield _(p)),f=this.segments.get(c),D(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const S=this.getCurrentPosition();I(S)&&(this.isLive||(f.forEach(b=>b.status=te.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(c){var h;return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield _(void 0);for(const y of this.representations.keys()){const v=c.find(x=>x.id===y);v&&this.representations.set(y,v);const E=this.representations.get(y);if(!E||!qi(E.segmentReference))return yield _(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,p=this.representations.get(f);D(p);const S=this.segments.get(f);D(S,"No segments for starting representation");const b=this.initData.get(f);if(D(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield _(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield _(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(S,p),yield yield _(this.sourceBufferTaskQueue.append(b,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case os.MP4:this.containerParser=TT;break;case os.WEBM:this.containerParser=PT;break;default:z(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=tt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Mr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Oe(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Oe(i,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;I(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!qi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!qi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Qi(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:te.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==gt.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){t.segmentReference.type===gt.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return J(this,void 0,void 0,function*(){e.status=te.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield fe(o,function(){return pe(this,arguments,function*(){const l=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(c=>setTimeout(c,l)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=te.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Qn(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}})}loadByteRangeSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=te.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield fe(n,function(){return pe(this,arguments,function*(){const u=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Qn(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(qi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Oe(e,0).byte.from,to:Oe(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&I(r)&&(i=tt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){return J(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=te.PARTIALLY_FED,o.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===gt.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,g=S<r,y=b<=r;if(c.status===te.DOWNLOADING&&g&&y){c.status=te.DOWNLOADED;const v=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(v,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const v=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?v:this.containerParser.parseFeedableSegmentChunk(v);E!=null&&E.byteLength&&(c.status=te.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=te.FED,nu(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===te.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=te.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Br(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return J(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>J(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&qi(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=nu(d)?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Br(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var es;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(es||(es={}));class CT{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(_s));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?es.HEADER:es.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return pe(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case es.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case es.PARAM:{const M=new URL(p,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),p=M.toString();break}default:z(a)}this.requestQuic&&(p=li(p));let b=this.abortAllController.signal,g;if(d){const M=new St;if(g=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{M.abort()}catch(X){_s(X)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(X){_s(X)}b=M.signal}const y=he(),v=yield yield _(Ci(p,{priority:u,headers:S,signal:b}).catch(_s)),E=he();if(!v)return g==null||g.unsubscribe(),yield _(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!v.ok||!v.body)return g==null||g.unsubscribe(),yield _(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!o&&!l)return g==null||g.unsubscribe(),yield _(v.arrayBuffer());const[$,x]=v.body.tee(),j=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(x,c));let K=0,H=new Uint8Array(0),q=!1;const Q=M=>{g==null||g.unsubscribe(),q=!0,_s(M)},B=fe(b,function({done:M,value:X}){return pe(this,arguments,function*(){if(K===0&&this.lastRequestFirstBytes$.next(he()-y),b.aborted)return g==null||g.unsubscribe(),yield _(void 0);if(!M&&X){const N=new Uint8Array(H.length+X.length);N.set(H),N.set(X,H.length),H=N,K+=X.byteLength,o==null||o(new DataView(H.buffer),K),yield yield _(j==null?void 0:j.read().then(B,Q))}})}.bind(this));return yield yield _(j==null?void 0:j.read().then(B,Q)),g==null||g.unsubscribe(),yield _(q?null:H.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==gt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(null);const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const g=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);v=new DataView($)}const E=a.parseSegments(v,g,y);return yield _({init:g,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==gt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=wo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return J(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case gt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case gt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _s=s=>{if(!Qn(s))throw s},Kn=1e3,Gr=(s,e,t)=>t*e+(1-t)*s,ac=(s,e)=>s.reduce((t,i)=>t+i,0)/e,OT=(s,e,t,i)=>{let r=0,a=t;const n=ac(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Po{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new xt(`raw_${i}`),this.smoothedSeries$=new xt(`smoothed_${i}`),this.reportedSeries$=new xt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(W(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 BT extends Po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Gr(this.slow,e,this.params.emaAlphaSlow),this.fast=Gr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class MT extends Po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ac(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gr(this.emaSmoothed,e,this.params.emaAlpha);const i=OT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class NT extends Po{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?Gr(this.smoothed,e,this.params.emaAlpha):e}}class Jn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new BT({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new MT({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new NT(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const FT=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},du=["timeupdate","progress","play","seeked","stalled","waiting"];var mt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(mt||(mt={}));let UT=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(mt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(mt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(mt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){console.log("updating manifest");const i=yield yield _(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{console.log("Error in getting manifest"),!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})}));if(console.log("Manifest string:"),console.log(i),!i)return yield _(null);let r;try{console.log("Parsing manifest"),r=DT(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(console.log("Manifest after parse:"),console.log(r),!r)return yield _(null);const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource||window.ManagedMediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Ue.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield _(Object.assign(Object.assign({},r),{representations:Li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(mt.REPRESENTATIOS_READY),window.ManagedMediaSource?(console.log("MANAGED MSE INIT"),this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new ou(Ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],I(i)&&(this.audioBufferManager=new ou(Ue.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ri(Kn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+Kn,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...du.map(o=>V(this.element,o))).pipe(P(o=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),ye(),oe(o=>!!o),Bs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),FT(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(p=>{var S,b;return(b=(S=p.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Be({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:u,bufferLength:d})=>J(this,void 0,void 0,function*(){if(D(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let g=Lt.None;if(this.isActiveLowLatency?g=Lt.ActiveLowLatency:b<f+S&&b>=f?g=Lt.LiveWithTargetOffset:c!==0&&b<f&&(g=Lt.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),g===Lt.LiveForwardBuffering||g===Lt.LiveWithTargetOffset){const y=o-(f+p),v=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(v-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:v>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=v:$=0,this.manifestUrlString=qe(this.manifestUrlString,$,Te.DASH_CMAF_OFFSET_P)}g!==Lt.None&&g!==Lt.ActiveLowLatency&&(o=0,this.updateLive())})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(G(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield _(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),I(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&I(i)?yield yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(mt.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ri(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new CT({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Jn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,a;return J(this,void 0,void 0,function*(){D(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=qe(this.manifestUrlString,n,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))})}initBuffer(){D(this.element),this.state$.setState(mt.RUNNING),this.subscription.add(G(...du.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const i={[Ue.VIDEO]:this.videoBufferManager,[Ue.AUDIO]:this.audioBufferManager,[Ue.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;D(this.element),D(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),as(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(mt.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.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),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}waitingEventCallback(){return J(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:R.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return J(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class nc{constructor(e){this.subscription=new ce,this.videoState=new me(we.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==we.STOPPED&&n!==m.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===m.STOPPED){a!==we.STOPPED&&(this.videoState.startTransitionTo(we.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(we.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case we.STOPPED:this.videoState.startTransitionTo(we.READY),this.prepare();return;case we.READY:n===m.PAUSED?(this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case we.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(we.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case we.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new UT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(P(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(we.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(we.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===we.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===mt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=RT(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=IT(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&LT(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=xT(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===mt.REPRESENTATIOS_READY&&(this.videoState.setState(we.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==mt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Ue.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ue.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ye(),P(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=Ni(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){console.log("destroy DASH provider"),this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}}class VT extends nc{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let HT=class extends ec{constructor(e){super(e),this.liveOffset=new Js}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Be({interval:Ri(qn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ae.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===m.PAUSED&&i===Ae.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class GT extends nc{constructor(e){super(e),this.liveOffset=new Js}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Be({interval:Ri(Kn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===we.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===m.PAUSED&&i===we.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const Rt={};var le;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const Ps=(s,e)=>new Yr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class jT{constructor(e){this.subscription=new ce,this.videoState=new me(le.INITIALIZING),this.textTracksManager=new Pt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==le.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case le.STOPPED:break;case le.READY:case le.PLAYING:case le.PAUSED:this.stop();break;default:z(t)}break;case m.READY:switch(t){case le.STOPPED:this.prepare();break;case le.READY:case le.PLAYING:case le.PAUSED:break;default:z(t)}break;case m.PLAYING:switch(t){case le.PLAYING:break;case le.STOPPED:this.prepare();break;case le.READY:case le.PAUSED:this.playIfAllowed();break;default:z(t)}break;case m.PAUSED:switch(t){case le.PAUSED:break;case le.STOPPED:this.prepare();break;case le.READY:this.videoState.setState(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED);break;case le.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Ft(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(Qe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ks(import("hls.js").then(r=>{e||(Rt.Hls=r.default,Rt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){D(Rt.Hls,"hls.js not loaded"),this.hls=new Rt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(le.STOPPED)}subscribe(){D(Rt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Vt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(fi(this.video,e.isLooped,i)),this.subscription.add(Nt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ps(this.hls,Rt.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),L(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),L(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i)),a(Ps(this.hls,Rt.Events.MANIFEST_PARSED).pipe(P(({levels:d})=>d.reduce((l,c)=>{var h,f;const p=c.name||c.height.toString(10),{width:S,height:b}=c,g=(f=hs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:ci({width:S,height:b});if(!g)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(p,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(Ps(this.hls,Rt.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",p=c.lang,S="internal";l.push({id:h,url:f,language:p,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(Ps(this.hls,Rt.Events.LEVEL_LOADING).pipe(P(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(kt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Ps(this.hls,Rt.Events.LEVEL_SWITCHED).pipe(P(({level:d})=>n(this.hls.levels[d])));o.pipe(oe(I)).subscribe(t.currentVideoTrack$,i),this.subscription.add(kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(W(d))return;const c=(l=this.trackLevels.get(d.id))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,p=this.hls.levels[f];!p||c.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=G(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(le.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(le.PLAYING),(yield si(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t})))||(this.videoState.setState(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(le.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(le.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0)}}const uu="X-Playback-Duration";var lu=s=>J(void 0,void 0,void 0,function*(){var e;const t=yield Ci(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(uu)?parseInt(t.headers.get(uu),10):void 0});const YT=s=>{let e=null;if(s.QUALITY&&(e=hs(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ci({width:t,height:i})}return e!=null?e:null},oc=(s,e=s)=>J(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Ci(s)).text()).split(`
46
+ `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Li(c[1].split(",").map(E=>E.split("="))),p=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=YT(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(x=>parseInt(x,10));E&&$&&(y={width:E,height:$})}const v=new URL(n[++d],e).toString();S&&o.push({id:p,quality:S,url:v,bandwidth:b,size:y,fps:g})}if(h){const f=Li(h[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),p=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;p&&S&&u.push({type:"internal",id:S,label:b,language:S,url:p,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}});var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class zT{constructor(e){var t;this.subscription=new ce,this.videoState=new me(ge.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.liveOffset=new Js,this.manifestStartTime$=new T(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===m.STOPPED){r!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&c.state===ie.Requested){this.videoState.startTransitionTo(ge.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ge.READY:a===m.READY?L(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ge.PAUSED:if(a===m.PLAYING)if(this.videoState.startTransitionTo(ge.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);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===m.PAUSED&&(L(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case ge.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.INVARIANT,url:this.params.source.url},oc(qe(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:R.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Qe(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,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ye(),P(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&I(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ie.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Be({startTime:this.manifestStartTime$.pipe(oe(I)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(P(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===A.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,u=qe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),lu(u).then(d=>{var l;if(!W(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(W(c)||!isFinite(c))try{Ci(u).then(h=>h.text()).then(h=>{var f;const p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(p){const S=new URL(p,u).toString();lu(S).then(b=>{W(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var be;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(be||(be={}));class qT{constructor(e){this.subscription=new ce,this.videoState=new me(be.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===m.STOPPED){i!==be.STOPPED&&(this.videoState.startTransitionTo(be.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(be.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===be.STOPPED){this.videoState.startTransitionTo(be.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(be.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&l.state===ie.Requested&&this.seek(l.position),i){case be.READY:r===m.READY?L(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed());return;case be.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(be.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case be.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;case be.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.INVARIANT,url:this.params.source.url},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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),oc(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(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.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(be.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(be.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===be.READY&&this.videoState.setState(be.READY),this.videoState.getState()===be.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&I(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===be.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ie.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(P(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!bc()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(G(V(o,"addtrack"),V(o,"removetrack"),V(o,"change"),We(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&d&&n.searchParams.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ke;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ke||(ke={}));class WT{constructor(e){this.subscription=new ce,this.videoState=new me(ke.STOPPED),this.trackUrls={},this.textTracksManager=new Pt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===m.STOPPED){a!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.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(ke.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==ke.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ke.STOPPED){this.videoState.startTransitionTo(ke.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==m.PAUSED&&c.state===ie.Requested&&this.seek(c.position),a){case ke.READY:n===m.READY?L(this.params.desiredState.playbackState,m.READY):n===m.PAUSED?(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed());return;case ke.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(ke.PAUSED),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ke.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Vt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ke.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ke.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ke.READY&&this.videoState.setState(ke.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&I(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===ke.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;D(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];D(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=li(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Qe(i))}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(i=Object.values(this.trackUrls).find(c=>!Ii(c.track.quality)&&Tu(c.track.quality,e)))===null||i===void 0?void 0:i.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&An(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Ii(f.track.quality)&&ts(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=Ni(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const cu=["stun:videostun.mycdn.me:80"],QT=1e3,KT=3,un=()=>null;class JT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=un,this.externalStopCallback=un,this.externalErrorCallback=un,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return J(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 J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:cu}]};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 J(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 J(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:R.WTF,message:e.message})}onPeerConnectionStream(e){return J(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 J(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),QT)}normalizeOptions(e={}){const t={stunServerList:cu,maxRetryNumber:KT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Se||(Se={}));class XT{constructor(e){this.videoState=new me(Se.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case Se.READY:i===m.PAUSED?(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Se.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ft(e.container),this.liveStreamClient=new JT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};G(this.videoState.stateChangeStarted$.pipe(P(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Vt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===Se.READY&&this.videoState.setState(Se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Nt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case Se.READY:break;case Se.PAUSED:t.playbackState.setState(m.PAUSED);break;case Se.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return z(n.to)}},i)).add(G(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(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:ft.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class hu{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!!this.current.done}}var ln,cn,hn,fn,pn,mn,vn,gn,gr,Sn,Sr,bn,br,yn,yr,Tn,Tr,En,Er,$n;const dc=jr().device===yc.Android,di=document.createElement("video"),ZT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',eE='video/mp4; codecs="hev1.1.6.L93.B0"',uc='video/webm; codecs="vp09.00.10.08"',lc='video/webm; codecs="av01.0.00M.08"',tE='audio/mp4; codecs="mp4a.40.2"',iE='audio/webm; codecs="opus"',Me={mms:!!(window.ManagedMediaSource&&(!((cn=(ln=window.ManagedSourceBuffer)===null||ln===void 0?void 0:ln.prototype)===null||cn===void 0)&&cn.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((fn=(hn=window.SourceBuffer)===null||hn===void 0?void 0:hn.prototype)===null||fn===void 0)&&fn.appendBuffer)),hls:!!(!((pn=di.canPlayType)===null||pn===void 0)&&pn.call(di,"application/x-mpegurl")||!((mn=di.canPlayType)===null||mn===void 0)&&mn.call(di,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},dt={mp4:!!(!((vn=di.canPlayType)===null||vn===void 0)&&vn.call(di,"video/mp4")),webm:!!(!((gn=di.canPlayType)===null||gn===void 0)&&gn.call(di,"video/webm")),cmaf:!0},Bt={h264:!!(!((Sn=(gr=window.MediaSource||window.ManagedMediaSource)===null||gr===void 0?void 0:gr.isTypeSupported)===null||Sn===void 0)&&Sn.call(gr,ZT)),h265:!!(!((bn=(Sr=window.MediaSource||window.ManagedMediaSource)===null||Sr===void 0?void 0:Sr.isTypeSupported)===null||bn===void 0)&&bn.call(Sr,eE)),vp9:!!(!((yn=(br=window.MediaSource||window.ManagedMediaSource)===null||br===void 0?void 0:br.isTypeSupported)===null||yn===void 0)&&yn.call(br,uc)),av1:!!(!((Tn=(yr=window.MediaSource||window.ManagedMediaSource)===null||yr===void 0?void 0:yr.isTypeSupported)===null||Tn===void 0)&&Tn.call(yr,lc)),aac:!!(!((En=(Tr=window.MediaSource||window.ManagedMediaSource)===null||Tr===void 0?void 0:Tr.isTypeSupported)===null||En===void 0)&&En.call(Tr,tE)),opus:!!(!(($n=(Er=window.MediaSource||window.ManagedMediaSource)===null||Er===void 0?void 0:Er.isTypeSupported)===null||$n===void 0)&&$n.call(Er,iE))},Wi=(Bt.h264||Bt.h265)&&Bt.aac;var oi;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(oi||(oi={}));var Xt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Xt||(Xt={}));let ki;const sE=()=>J(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={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({},s),{video:Object.assign(Object.assign({},s.video),{contentType:lc})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:uc})}))]);ki={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}});try{sE()}catch(s){console.error(s)}const Vs=Me.hls&&dt.mp4,rE=()=>Object.keys(Bt).filter(s=>Bt[s]),aE=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return Me.mse&&dt.mp4&&Wi;case A.DASH_SEP:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.DASH_WEBM:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.vp9&&Bt.opus;case A.DASH_WEBM_AV1:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.av1&&Bt.opus;case A.DASH_LIVE:return Me.mse&&dt.mp4&&Wi;case A.DASH_LIVE_CMAF:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi&&dt.cmaf;case A.DASH_ONDEMAND:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.HLS:case A.HLS_ONDEMAND:return Vs||e&&Me.mse&&dt.mp4&&Wi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Vs;case A.MPEG:return dt.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Bt.h264&&(dt.mp4||dt.webm);default:return z(i)}}),Ds=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case oi.VP9:return[e,t];case oi.AV1:return[t,e];case oi.NONE:return[];case oi.SMOOTH:return ki?ki[t].smooth?[t,e]:ki[e].smooth?[e,t]:[t,e]:[e,t];case oi.POWER_EFFICIENT:return ki?ki[t].powerEfficient?[t,e]:ki[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},nE=({webmCodec:s,androidPreferredFormat:e})=>{if(dc)switch(e){case Xt.MPEG:return[A.MPEG,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Xt.HLS:return[A.HLS,A.HLS_ONDEMAND,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Xt.DASH:return[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Vs?[...Ds(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},oE=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(dc)switch(s){case Xt.DASH:{o=a;break}case Xt.HLS:case Xt.MPEG:{o=n;break}}else Vs?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},fu=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var dE=s=>new Yr(e=>{const t=new ce,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(P(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(P(({type:d})=>d!==void 0)),n=new O;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const uE={cacheDuration:12e4},lE={chunkDuration:5e3,maxParallelRequests:5};class cE{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,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),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new O,warning$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$: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),is3DVideo$:new T(!1)},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=aE([...oE(this.params.tuning),...nE(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>I(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new hu(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new hu(n.filter(o=>I(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(console.log("Choose provider "+t),W(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!==ie.None;if(this.params.desiredState.seekState.setState({state:ie.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ye.SCREEN:return this.createScreenProvider(t);case Ye.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return D(o),new cy(Object.assign(Object.assign({},n),{source:o,config:uE}))}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJs?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new VT(Object.assign(Object.assign({},n),{source:o}))):new z0(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJsCMAF?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new GT(Object.assign(Object.assign({},n),{source:o})):new HT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),Vs||!this.params.tuning.useHlsJs?new qT(Object.assign(Object.assign({},n),{source:o})):new jT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new zT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new WT(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ny(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},lE),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new XT({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new gb({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ye.CHROMECAST:Ye.SCREEN}chooseFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.next();case Ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return z(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:i(e.url)})}return Li(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ce;let t=!1,i=0;const r=he();return e.add(G(this.providerOutput.error$,dE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(P(a=>({id:`ProviderHangup:${a}`,category:R.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{console.log(a);const n=this.current$.getValue().destination;if(n===Ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===R.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,l=u&&(o&&t||!d),c=a.id.includes("partial_metadata"),h=he()-r;l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c&&h<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ye.SCREEN)}})),e}}const hE=5e3,pu="one_video_throughput",mu="one_video_rtt",Zt=window.navigator.connection,vu=()=>{const s=Zt==null?void 0:Zt.downlink;if(I(s)&&s!==10)return s*1e3},gu=()=>{const s=Zt==null?void 0:Zt.rtt;if(I(s)&&s!==3e3)return s},Su=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Os{constructor(e){var t,i;this.subscription=new ce,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Os.load(pu)||(e.useBrowserEstimation?vu():void 0)||hE,a=(i=(t=Os.load(mu))!==null&&t!==void 0?t:e.useBrowserEstimation?gu():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Su(r,a,e.rttPenaltyRequestSize)),this.throughput=Jn.getSmoothedValue(r,-1,e),this.rtt=Jn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vu();u&&this.throughput.next(u);const d=gu();I(d)&&this.rtt.next(d)};Zt&&"onchange"in Zt&&this.subscription.add(V(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ya.set(pu,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ya.set(mu,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Be({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P(({throughput:n,rtt:o})=>Su(n,o,e.rttPenaltyRequestSize)),oe(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=he();const r=new ce;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(V(e,"progress").pipe(_e()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(V(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(V(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=he(),n=0,o=he();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>J(this,void 0,void 0,function*(){if(l)!t&&this.addRawSpeed(r,he()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=he()}o=he()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());yield i==null?void 0:i.read().then(d,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(Os.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=ya.get(e);if(I(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const bu={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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ft.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},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:!1,webmCodec:oi.VP9,androidPreferredFormat:Xt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},fE=s=>{var e;return Object.assign(Object.assign({},Tc(s,bu)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...bu.configName]})};var yu=({seekState:s,position$:e})=>G(s.stateChangeEnded$.pipe(P(({to:t})=>{var i;return t.state===ie.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),oe(I)),e.pipe(oe(()=>s.getState().state===ie.None))),pE=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return D(e,`Wrong container or containerId {${s.container}}`),e};const mE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(oe(r=>r.length>0),_e()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class jE{constructor(e={configName:[]}){if(this.subscription=new ce,this.logger=new Ec,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new me(m.STOPPED),seekState:new me({state:ie.None}),volume:new me({volume:1,muted:!1}),videoTrack:new me(void 0),autoVideoTrackSwitching:new me(!0),autoVideoTrackLimits:new me({}),isLooped:new me(!1),playbackRate:new me(1),externalTextTracks:new me([]),internalTextTracks:new me([]),currentTextTrack:new me(void 0),textTrackCuesSettings:new me({}),cameraOrientation:new me({x:0,y:0})},this.info={playbackState$:new T(m.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),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$: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(ni.NONE),chromecastState$:new T(Ne.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new O,ready$:new O,started$:new O,playing$:new O,paused$:new O,stopped$:new O,willStart$:new O,willResume$:new O,willPause$:new O,willStop$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Ub},this.initLogs(),this.tuning=fE(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wc({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Os(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const p=typeof f;return["number","string","boolean"].includes(p)?f:f===null?null:`<${p}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=pE(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new cE({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},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()===m.STOPPED&&e.startTransitionTo(m.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==m.PLAYING&&t.startTransitionTo(m.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?V(document,"visibilitychange").pipe(_e()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ie.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()===Ne.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()===Ne.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;D(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return mE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ie.None?void 0:t.position;return I(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(G(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(P(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===m.STOPPED),_e()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case m.READY:this.events.ready$.next();break;case m.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case m.PAUSED:this.events.paused$.next();break;case m.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case m.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ie.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:ie.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ie.Applying&&(this.desiredState.seekState.setState({state:ie.None}),this.events.seeked$.next())})).add(e.current$.pipe(P(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(P(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(P(n=>n.map(({quality:o})=>o).sort((o,u)=>Ii(o)?1:Ii(u)?-1:ts(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.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(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(P(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.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Be({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(P(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Be({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(P(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(P(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(P(n=>n.volume),ye()).subscribe(this.info.volume$)).add(yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(G(e.providerOutput.endedEvent$.pipe(ss(!0)),e.providerOutput.seekedEvent$.pipe(ss(!1))).pipe(ye()).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(P(n=>({id:n?`No${n}`:"NoProviders",category:R.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(_e(),P(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),P(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),P(()=>he()-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 i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>i.next(!1)));let r=0;const a=G(e.providerOutput.isBuffering$,t,i).pipe(P(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ye());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(G(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,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(G(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Ne.CONNECTED?l=ni.SECOND_SCREEN:u?n?l=ni.PIP:o?l=ni.FULLSCREEN:l=ni.INLINE:l=ni.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(P(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 ce;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=Ni(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(G(this.desiredState.videoTrack.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(P(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;D(this.providerContainer),D(t),Fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Nb(i)),this.providerContainer.current$.subscribe(({type:i})=>fr("provider",i)),t.duration$.subscribe(i=>fr("duration",i)),t.availableVideoTracks$.pipe(oe(i=>!!i.length),_e()).subscribe(i=>fr("tracks",i)),this.events.fatalError$.subscribe(new xt("fatalError")),this.events.managedError$.subscribe(new xt("managedError")),t.position$.subscribe(new xt("position")),t.currentVideoTrack$.pipe(P(i=>i==null?void 0:i.quality)).subscribe(new xt("quality")),this.info.currentBuffer$.subscribe(new xt("buffer")),t.isBuffering$.subscribe(new xt("isBuffering"))].forEach(i=>this.subscription.add(i)),fr("codecs",rE())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>J(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:R.DOM,message:String(r)})})});this.subscription.add(G(V(document,"visibilitychange"),V(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const YE=`@vkontakte/videoplayer-core@${$c}`;export{Ne as ChromecastState,Ms as HttpConnectionType,WE as Observable,m as PlaybackState,jE as Player,YE as SDK_VERSION,QE as Subject,KE as Subscription,ni as Surface,$c as VERSION,JE as ValueSubject,A as VideoFormat,XE as VideoQuality};