@vkontakte/videoplayer-core 2.0.99 → 2.0.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +10 -10
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +11 -11
- package/evergreen.esm.js +11 -11
- package/package.json +1 -1
package/es2015.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.100
|
|
3
|
+
* Fri, 12 Apr 2024 14:49:51 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-100/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as b,Subject as D,Subscription as re,isNonNullable as P,ErrorCategory as _,isNullable as K,fromEvent as x,assertNever as G,merge as F,tap as Di,map as A,observableFrom as Ne,filterChanged as fe,assertNonNullable as R,debounce as tt,getHighestQuality as yd,timeout as Td,getCurrentBrowser as Fa,CurrentClientBrowser as yl,combine as it,once as Pe,mapTo as ks,filter as he,VideoQuality as _e,now as le,assertNotEmptyArray as Ed,videoSizeToQuality as Bi,isInvariantQuality as Ot,isHigher as ui,isLower as ys,isHigherOrEqual as da,isLowerOrEqual as Ps,interval as Rs,videoQualityToHeight as $d,Observable as Ns,debounceFn as wd,abortable as Re,getExponentialDelay as Ts,isIOS as Ad,CurrentClientDevice as kd,safeStorage as hr,fillWithDefault as Pd,Logger as Rd}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as UT,Subject as HT,Subscription as jT,ValueSubject as GT,VideoQuality as YT}from"@vkontakte/videoplayer-shared/es2015.esm.js";const Id="2.0.99";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var y;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var $e;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})($e||($e={}));var be;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(be||(be={}));var ca;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ca||(ca={}));var z;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(z||(z={}));var gt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(gt||(gt={}));function ee(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(d){try{l(s.next(d))}catch(c){n(c)}}function u(d){try{l(s.throw(d))}catch(c){n(c)}}function l(d){d.done?a(d.value):r(d.value).then(o,u)}l((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function Ie(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(v,m){a.push([h,f,v,m])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(v){c(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(l,d):c(a[0][2],h)}function l(h){o("next",h)}function d(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Cd=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class _d{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(be.NOT_AVAILABLE),this.errorEvent$=new D,this.realCastState$=new b(be.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=P((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Cd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(x(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return G(r.sessionState)}})).add(F(x(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Di(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),A(r=>r.castState)),Ne([s.getCastState()])).pipe(fe(),A(Dd),Di(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===be.CONNECTED,o=P(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();R(u);const l=u.getCastDevice(),d=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===be.CONNECTED?P(this.connection$.getValue())?be.CONNECTED:be.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Dd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return be.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return be.AVAILABLE;case cast.framework.CastState.CONNECTING:return be.CONNECTING;case cast.framework.CastState.CONNECTED:return be.CONNECTED;default:return G(i)}};var fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Fs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Fe=function(i){try{return!!i()}catch(e){return!0}},Ld=Fe,Vs=!Ld(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Tl=Vs,El=Function.prototype,ha=El.call,xd=Tl&&El.bind.bind(ha,ha),Ve=Tl?xd:function(i){return function(){return ha.apply(i,arguments)}},$l=Ve,Od=$l({}.toString),Md=$l("".slice),Ni=function(i){return Md(Od(i),8,-1)},Bd=Ve,Nd=Fe,Fd=Ni,pr=Object,Vd=Bd("".split),Ud=Nd(function(){return!pr("z").propertyIsEnumerable(0)})?function(i){return Fd(i)=="String"?Vd(i,""):pr(i)}:pr,Fi=function(i){return i==null},Hd=Fi,jd=TypeError,Va=function(i){if(Hd(i))throw jd("Can't call method on "+i);return i},Gd=Ud,Yd=Va,Vi=function(i){return Gd(Yd(i))},pi={},Zi=function(i){return i&&i.Math==Math&&i},Te=Zi(typeof globalThis=="object"&&globalThis)||Zi(typeof window=="object"&&window)||Zi(typeof self=="object"&&self)||Zi(typeof fr=="object"&&fr)||function(){return this}()||fr||Function("return this")(),fa=typeof document=="object"&&document.all,qd=typeof fa=="undefined"&&fa!==void 0,wl={all:fa,IS_HTMLDDA:qd},Al=wl,zd=Al.all,ve=Al.IS_HTMLDDA?function(i){return typeof i=="function"||i===zd}:function(i){return typeof i=="function"},Wd=Te,Qd=ve,In=Wd.WeakMap,Kd=Qd(In)&&/native code/.test(String(In)),Cn=ve,kl=wl,Jd=kl.all,ht=kl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Cn(i)||i===Jd}:function(i){return typeof i=="object"?i!==null:Cn(i)},Xd=Fe,Tt=!Xd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Bt={},Zd=Te,_n=ht,pa=Zd.document,ec=_n(pa)&&_n(pa.createElement),Ua=function(i){return ec?pa.createElement(i):{}},tc=Tt,ic=Fe,sc=Ua,Pl=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Tt,ac=Fe,Rl=rc&&ac(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),nc=ht,oc=String,lc=TypeError,ft=function(i){if(nc(i))return i;throw lc(oc(i)+" is not an object")},uc=Vs,es=Function.prototype.call,Le=uc?es.bind(es):function(){return es.apply(es,arguments)},Ha={},mr=Ha,vr=Te,dc=ve,Dn=function(i){return dc(i)?i:void 0},Nt=function(i,e){return arguments.length<2?Dn(mr[i])||Dn(vr[i]):mr[i]&&mr[i][e]||vr[i]&&vr[i][e]},cc=Ve,Us=cc({}.isPrototypeOf),Hs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Il=Te,gr=Hs,Ln=Il.process,xn=Il.Deno,On=Ln&&Ln.versions||xn&&xn.version,Mn=On&&On.v8,Ge,Is;Mn&&(Ge=Mn.split("."),Is=Ge[0]>0&&Ge[0]<4?1:+(Ge[0]+Ge[1]));!Is&&gr&&(Ge=gr.match(/Edge\/(\d+)/),(!Ge||Ge[1]>=74)&&(Ge=gr.match(/Chrome\/(\d+)/),Ge&&(Is=+Ge[1])));var Cl=Is,Bn=Cl,hc=Fe,fc=Te,pc=fc.String,_l=!!Object.getOwnPropertySymbols&&!hc(function(){var i=Symbol();return!pc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Bn&&Bn<41}),mc=_l,Dl=mc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",vc=Nt,gc=ve,Sc=Us,bc=Dl,yc=Object,Ll=bc?function(i){return typeof i=="symbol"}:function(i){var e=vc("Symbol");return gc(e)&&Sc(e.prototype,yc(i))},Tc=String,js=function(i){try{return Tc(i)}catch(e){return"Object"}},Ec=ve,$c=js,wc=TypeError,Ft=function(i){if(Ec(i))return i;throw wc($c(i)+" is not a function")},Ac=Ft,kc=Fi,Gs=function(i,e){var t=i[e];return kc(t)?void 0:Ac(t)},Sr=Le,br=ve,yr=ht,Pc=TypeError,Rc=function(i,e){var t,s;if(e==="string"&&br(t=i.toString)&&!yr(s=Sr(t,i))||br(t=i.valueOf)&&!yr(s=Sr(t,i))||e!=="string"&&br(t=i.toString)&&!yr(s=Sr(t,i)))return s;throw Pc("Can't convert object to primitive value")},xl={exports:{}},Ic=!0,Nn=Te,Cc=Object.defineProperty,_c=function(i,e){try{Cc(Nn,i,{value:e,configurable:!0,writable:!0})}catch(t){Nn[i]=e}return e},Dc=Te,Lc=_c,Fn="__core-js_shared__",xc=Dc[Fn]||Lc(Fn,{}),ja=xc,Vn=ja;(xl.exports=function(i,e){return Vn[i]||(Vn[i]=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 Ol=xl.exports,Oc=Va,Mc=Object,Ys=function(i){return Mc(Oc(i))},Bc=Ve,Nc=Ys,Fc=Bc({}.hasOwnProperty),rt=Object.hasOwn||function(e,t){return Fc(Nc(e),t)},Vc=Ve,Uc=0,Hc=Math.random(),jc=Vc(1 .toString),Ml=function(i){return"Symbol("+(i===void 0?"":i)+")_"+jc(++Uc+Hc,36)},Gc=Te,Yc=Ol,Un=rt,qc=Ml,zc=_l,Wc=Dl,ri=Gc.Symbol,Tr=Yc("wks"),Qc=Wc?ri.for||ri:ri&&ri.withoutSetter||qc,Ae=function(i){return Un(Tr,i)||(Tr[i]=zc&&Un(ri,i)?ri[i]:Qc("Symbol."+i)),Tr[i]},Kc=Le,Hn=ht,jn=Ll,Jc=Gs,Xc=Rc,Zc=Ae,eh=TypeError,th=Zc("toPrimitive"),ih=function(i,e){if(!Hn(i)||jn(i))return i;var t=Jc(i,th),s;if(t){if(e===void 0&&(e="default"),s=Kc(t,i,e),!Hn(s)||jn(s))return s;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(i,e)},sh=ih,rh=Ll,Ga=function(i){var e=sh(i,"string");return rh(e)?e:e+""},ah=Tt,nh=Pl,oh=Rl,ts=ft,Gn=Ga,lh=TypeError,Er=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,$r="enumerable",wr="configurable",Ar="writable";Bt.f=ah?oh?function(e,t,s){if(ts(e),t=Gn(t),ts(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Ar in s&&!s[Ar]){var r=uh(e,t);r&&r[Ar]&&(e[t]=s.value,s={configurable:wr in s?s[wr]:r[wr],enumerable:$r in s?s[$r]:r[$r],writable:!1})}return Er(e,t,s)}:Er:function(e,t,s){if(ts(e),t=Gn(t),ts(s),nh)try{return Er(e,t,s)}catch(r){}if("get"in s||"set"in s)throw lh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var qs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},dh=Tt,ch=Bt,hh=qs,Ui=dh?function(i,e,t){return ch.f(i,e,hh(1,t))}:function(i,e,t){return i[e]=t,i},fh=Ol,ph=Ml,Yn=fh("keys"),Ya=function(i){return Yn[i]||(Yn[i]=ph(i))},qa={},mh=Kd,Bl=Te,vh=ht,gh=Ui,kr=rt,Pr=ja,Sh=Ya,bh=qa,qn="Object already initialized",ma=Bl.TypeError,yh=Bl.WeakMap,Cs,Li,_s,Th=function(i){return _s(i)?Li(i):Cs(i,{})},Eh=function(i){return function(e){var t;if(!vh(e)||(t=Li(e)).type!==i)throw ma("Incompatible receiver, "+i+" required");return t}};if(mh||Pr.state){var Qe=Pr.state||(Pr.state=new yh);Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Cs=function(i,e){if(Qe.has(i))throw ma(qn);return e.facade=i,Qe.set(i,e),e},Li=function(i){return Qe.get(i)||{}},_s=function(i){return Qe.has(i)}}else{var Jt=Sh("state");bh[Jt]=!0,Cs=function(i,e){if(kr(i,Jt))throw ma(qn);return e.facade=i,gh(i,Jt,e),e},Li=function(i){return kr(i,Jt)?i[Jt]:{}},_s=function(i){return kr(i,Jt)}}var Nl={set:Cs,get:Li,has:_s,enforce:Th,getterFor:Eh},$h=Vs,Fl=Function.prototype,zn=Fl.apply,Wn=Fl.call,Vl=typeof Reflect=="object"&&Reflect.apply||($h?Wn.bind(zn):function(){return Wn.apply(zn,arguments)}),wh=Ni,Ah=Ve,Ul=function(i){if(wh(i)==="Function")return Ah(i)},za={},Hl={},jl={}.propertyIsEnumerable,Gl=Object.getOwnPropertyDescriptor,kh=Gl&&!jl.call({1:2},1);Hl.f=kh?function(e){var t=Gl(this,e);return!!t&&t.enumerable}:jl;var Ph=Tt,Rh=Le,Ih=Hl,Ch=qs,_h=Vi,Dh=Ga,Lh=rt,xh=Pl,Qn=Object.getOwnPropertyDescriptor;za.f=Ph?Qn:function(e,t){if(e=_h(e),t=Dh(t),xh)try{return Qn(e,t)}catch(s){}if(Lh(e,t))return Ch(!Rh(Ih.f,e,t),e[t])};var Oh=Fe,Mh=ve,Bh=/#|\.prototype\./,Hi=function(i,e){var t=Fh[Nh(i)];return t==Uh?!0:t==Vh?!1:Mh(e)?Oh(e):!!e},Nh=Hi.normalize=function(i){return String(i).replace(Bh,".").toLowerCase()},Fh=Hi.data={},Vh=Hi.NATIVE="N",Uh=Hi.POLYFILL="P",Yl=Hi,Kn=Ul,Hh=Ft,jh=Vs,Gh=Kn(Kn.bind),zs=function(i,e){return Hh(i),e===void 0?i:jh?Gh(i,e):function(){return i.apply(e,arguments)}},is=Te,Yh=Vl,qh=Ul,zh=ve,Wh=za.f,Qh=Yl,Xt=Ha,Kh=zs,Zt=Ui,Jn=rt,Jh=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Yh(i,this,arguments)};return e.prototype=i.prototype,e},qe=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?is:r?is[t]:(is[t]||{}).prototype,o=s?Xt:Xt[t]||Zt(Xt,t,{})[t],u=o.prototype,l,d,c,h,f,v,m,g,S;for(h in e)l=Qh(s?h:t+(r?".":"#")+h,i.forced),d=!l&&n&&Jn(n,h),v=o[h],d&&(i.dontCallGetSet?(S=Wh(n,h),m=S&&S.value):m=n[h]),f=d&&m?m:e[h],!(d&&typeof v==typeof f)&&(i.bind&&d?g=Kh(f,is):i.wrap&&d?g=Jh(f):a&&zh(f)?g=qh(f):g=f,(i.sham||f&&f.sham||v&&v.sham)&&Zt(g,"sham",!0),Zt(o,h,g),a&&(c=t+"Prototype",Jn(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],h,f),i.real&&u&&(l||!u[h])&&Zt(u,h,f)))},va=Tt,Xh=rt,ql=Function.prototype,Zh=va&&Object.getOwnPropertyDescriptor,Wa=Xh(ql,"name"),ef=Wa&&function(){}.name==="something",tf=Wa&&(!va||va&&Zh(ql,"name").configurable),sf={EXISTS:Wa,PROPER:ef,CONFIGURABLE:tf},zl={},rf=Math.ceil,af=Math.floor,nf=Math.trunc||function(e){var t=+e;return(t>0?af:rf)(t)},of=nf,Qa=function(i){var e=+i;return e!==e||e===0?0:of(e)},lf=Qa,uf=Math.max,df=Math.min,cf=function(i,e){var t=lf(i);return t<0?uf(t+e,0):df(t,e)},hf=Qa,ff=Math.min,pf=function(i){return i>0?ff(hf(i),9007199254740991):0},mf=pf,Ka=function(i){return mf(i.length)},vf=Vi,gf=cf,Sf=Ka,Xn=function(i){return function(e,t,s){var r=vf(e),a=Sf(r),n=gf(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},bf={includes:Xn(!0),indexOf:Xn(!1)},yf=Ve,Rr=rt,Tf=Vi,Ef=bf.indexOf,$f=qa,Zn=yf([].push),wf=function(i,e){var t=Tf(i),s=0,r=[],a;for(a in t)!Rr($f,a)&&Rr(t,a)&&Zn(r,a);for(;e.length>s;)Rr(t,a=e[s++])&&(~Ef(r,a)||Zn(r,a));return r},Wl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Af=wf,kf=Wl,Pf=Object.keys||function(e){return Af(e,kf)},Rf=Tt,If=Rl,Cf=Bt,_f=ft,Df=Vi,Lf=Pf;zl.f=Rf&&!If?Object.defineProperties:function(e,t){_f(e);for(var s=Df(t),r=Lf(t),a=r.length,n=0,o;a>n;)Cf.f(e,o=r[n++],s[o]);return e};var xf=Nt,Ql=xf("document","documentElement"),Of=ft,Mf=zl,eo=Wl,Bf=qa,Nf=Ql,Ff=Ua,Vf=Ya,to=">",io="<",ga="prototype",Sa="script",Kl=Vf("IE_PROTO"),Ir=function(){},Jl=function(i){return io+Sa+to+i+io+"/"+Sa+to},so=function(i){i.write(Jl("")),i.close();var e=i.parentWindow.Object;return i=null,e},Uf=function(){var i=Ff("iframe"),e="java"+Sa+":",t;return i.style.display="none",Nf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Jl("document.F=Object")),t.close(),t.F},ss,Es=function(){try{ss=new ActiveXObject("htmlfile")}catch(e){}Es=typeof document!="undefined"?document.domain&&ss?so(ss):Uf():so(ss);for(var i=eo.length;i--;)delete Es[ga][eo[i]];return Es()};Bf[Kl]=!0;var Xl=Object.create||function(e,t){var s;return e!==null?(Ir[ga]=Of(e),s=new Ir,Ir[ga]=null,s[Kl]=e):s=Es(),t===void 0?s:Mf.f(s,t)},Hf=Fe,jf=!Hf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Gf=rt,Yf=ve,qf=Ys,zf=Ya,Wf=jf,ro=zf("IE_PROTO"),ba=Object,Qf=ba.prototype,Zl=Wf?ba.getPrototypeOf:function(i){var e=qf(i);if(Gf(e,ro))return e[ro];var t=e.constructor;return Yf(t)&&e instanceof t?t.prototype:e instanceof ba?Qf:null},Kf=Ui,Ja=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Kf(i,e,t),i},Jf=Fe,Xf=ve,Zf=ht,ep=Xl,ao=Zl,tp=Ja,ip=Ae,ya=ip("iterator"),eu=!1,ut,Cr,_r;[].keys&&(_r=[].keys(),"next"in _r?(Cr=ao(ao(_r)),Cr!==Object.prototype&&(ut=Cr)):eu=!0);var sp=!Zf(ut)||Jf(function(){var i={};return ut[ya].call(i)!==i});sp?ut={}:ut=ep(ut);Xf(ut[ya])||tp(ut,ya,function(){return this});var tu={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:eu},rp=Ae,ap=rp("toStringTag"),iu={};iu[ap]="z";var Xa=String(iu)==="[object z]",np=Xa,op=ve,$s=Ni,lp=Ae,up=lp("toStringTag"),dp=Object,cp=$s(function(){return arguments}())=="Arguments",hp=function(i,e){try{return i[e]}catch(t){}},ji=np?$s:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=hp(e=dp(i),up))=="string"?t:cp?$s(e):(s=$s(e))=="Object"&&op(e.callee)?"Arguments":s},fp=Xa,pp=ji,mp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},vp=Xa,gp=Bt.f,Sp=Ui,bp=rt,yp=mp,Tp=Ae,no=Tp("toStringTag"),Za=function(i,e,t,s){if(i){var r=t?i:i.prototype;bp(r,no)||gp(r,no,{configurable:!0,value:e}),s&&!vp&&Sp(r,"toString",yp)}},Ep=tu.IteratorPrototype,$p=Xl,wp=qs,Ap=Za,kp=pi,Pp=function(){return this},Rp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=$p(Ep,{next:wp(+!s,t)}),Ap(i,r,!1,!0),kp[r]=Pp,i},Ip=qe,Cp=Le,su=sf,_p=Rp,Dp=Zl,Lp=Za,oo=Ja,xp=Ae,lo=pi,ru=tu,Op=su.PROPER;su.CONFIGURABLE;ru.IteratorPrototype;var rs=ru.BUGGY_SAFARI_ITERATORS,Dr=xp("iterator"),uo="keys",as="values",co="entries",Mp=function(){return this},Bp=function(i,e,t,s,r,a,n){_p(t,e,s);var o=function(S){if(S===r&&h)return h;if(!rs&&S in d)return d[S];switch(S){case uo:return function(){return new t(this,S)};case as:return function(){return new t(this,S)};case co:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[Dr]||d["@@iterator"]||r&&d[r],h=!rs&&c||o(r),f=e=="Array"&&d.entries||c,v,m,g;if(f&&(v=Dp(f.call(new i)),v!==Object.prototype&&v.next&&(Lp(v,u,!0,!0),lo[u]=Mp)),Op&&r==as&&c&&c.name!==as&&(l=!0,h=function(){return Cp(c,this)}),r)if(m={values:o(as),keys:a?h:o(uo),entries:o(co)},n)for(g in m)(rs||l||!(g in d))&&oo(d,g,m[g]);else Ip({target:e,proto:!0,forced:rs||l},m);return n&&d[Dr]!==h&&oo(d,Dr,h,{name:r}),lo[e]=h,m},Np=function(i,e){return{value:i,done:e}},Fp=Vi,ho=pi,au=Nl;Bt.f;var Vp=Bp,ns=Np,nu="Array Iterator",Up=au.set,Hp=au.getterFor(nu);Vp(Array,"Array",function(i,e){Up(this,{type:nu,target:Fp(i),index:0,kind:e})},function(){var i=Hp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ns(void 0,!0)):t=="keys"?ns(s,!1):t=="values"?ns(e[s],!1):ns([s,e[s]],!1)},"values");ho.Arguments=ho.Array;var jp=Ae,Gp=pi,Yp=jp("iterator"),qp=Array.prototype,zp=function(i){return i!==void 0&&(Gp.Array===i||qp[Yp]===i)},Wp=ji,fo=Gs,Qp=Fi,Kp=pi,Jp=Ae,Xp=Jp("iterator"),ou=function(i){if(!Qp(i))return fo(i,Xp)||fo(i,"@@iterator")||Kp[Wp(i)]},Zp=Le,em=Ft,tm=ft,im=js,sm=ou,rm=TypeError,am=function(i,e){var t=arguments.length<2?sm(i):e;if(em(t))return tm(Zp(t,i));throw rm(im(i)+" is not iterable")},nm=Le,po=ft,om=Gs,lm=function(i,e,t){var s,r;po(i);try{if(s=om(i,"return"),!s){if(e==="throw")throw t;return t}s=nm(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return po(s),t},um=zs,dm=Le,cm=ft,hm=js,fm=zp,pm=Ka,mo=Us,mm=am,vm=ou,vo=lm,gm=TypeError,ws=function(i,e){this.stopped=i,this.result=e},go=ws.prototype,en=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=um(e,s),l,d,c,h,f,v,m,g=function(E){return l&&vo(l,"normal",E),new ws(!0,E)},S=function(E){return r?(cm(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)l=i.iterator;else if(n)l=i;else{if(d=vm(i),!d)throw gm(hm(i)+" is not iterable");if(fm(d)){for(c=0,h=pm(i);h>c;c++)if(f=S(i[c]),f&&mo(go,f))return f;return new ws(!1)}l=mm(i,d)}for(v=a?i.next:l.next;!(m=dm(v,l)).done;){try{f=S(m.value)}catch(E){vo(l,"throw",E)}if(typeof f=="object"&&f&&mo(go,f))return f}return new ws(!1)},Sm=Ga,bm=Bt,ym=qs,Tm=function(i,e,t){var s=Sm(e);s in i?bm.f(i,s,ym(0,t)):i[s]=t},Em=qe,$m=en,wm=Tm;Em({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $m(e,function(s,r){wm(t,s,r)},{AS_ENTRIES:!0}),t}});var Am=Ha,km=Am.Object.fromEntries,Pm={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},Rm=Pm,Im=Te,Cm=ji,_m=Ui,So=pi,Dm=Ae,bo=Dm("toStringTag");for(var Lr in Rm){var yo=Im[Lr],xr=yo&&yo.prototype;xr&&Cm(xr)!==bo&&_m(xr,bo,Lr),So[Lr]=So.Array}var Lm=km,xm=Lm,Om=xm,Mm=Om,Ds=Fs(Mm),Bm=Ni,Ws=typeof process!="undefined"&&Bm(process)=="process",Nm=Bt,Fm=function(i,e,t){return Nm.f(i,e,t)},Vm=Nt,Um=Fm,Hm=Ae,jm=Tt,To=Hm("species"),Gm=function(i){var e=Vm(i);jm&&e&&!e[To]&&Um(e,To,{configurable:!0,get:function(){return this}})},Ym=Us,qm=TypeError,zm=function(i,e){if(Ym(e,i))return i;throw qm("Incorrect invocation")},Wm=Ve,Qm=ve,Ta=ja,Km=Wm(Function.toString);Qm(Ta.inspectSource)||(Ta.inspectSource=function(i){return Km(i)});var lu=Ta.inspectSource,Jm=Ve,Xm=Fe,uu=ve,Zm=ji,ev=Nt,tv=lu,du=function(){},iv=[],cu=ev("Reflect","construct"),tn=/^\s*(?:class|function)\b/,sv=Jm(tn.exec),rv=!tn.exec(du),$i=function(e){if(!uu(e))return!1;try{return cu(du,iv,e),!0}catch(t){return!1}},hu=function(e){if(!uu(e))return!1;switch(Zm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rv||!!sv(tn,tv(e))}catch(t){return!0}};hu.sham=!0;var av=!cu||Xm(function(){var i;return $i($i.call)||!$i(Object)||!$i(function(){i=!0})||i})?hu:$i,nv=av,ov=js,lv=TypeError,uv=function(i){if(nv(i))return i;throw lv(ov(i)+" is not a constructor")},Eo=ft,dv=uv,cv=Fi,hv=Ae,fv=hv("species"),fu=function(i,e){var t=Eo(i).constructor,s;return t===void 0||cv(s=Eo(t)[fv])?e:dv(s)},pv=Ve,mv=pv([].slice),vv=TypeError,gv=function(i,e){if(i<e)throw vv("Not enough arguments");return i},Sv=Hs,pu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sv),De=Te,bv=Vl,yv=zs,$o=ve,Tv=rt,mu=Fe,wo=Ql,Ev=mv,Ao=Ua,$v=gv,wv=pu,Av=Ws,Ea=De.setImmediate,$a=De.clearImmediate,kv=De.process,Or=De.Dispatch,Pv=De.Function,ko=De.MessageChannel,Rv=De.String,Mr=0,Ii={},Po="onreadystatechange",xi,It,Br,Nr;mu(function(){xi=De.location});var sn=function(i){if(Tv(Ii,i)){var e=Ii[i];delete Ii[i],e()}},Fr=function(i){return function(){sn(i)}},Ro=function(i){sn(i.data)},Io=function(i){De.postMessage(Rv(i),xi.protocol+"//"+xi.host)};(!Ea||!$a)&&(Ea=function(e){$v(arguments.length,1);var t=$o(e)?e:Pv(e),s=Ev(arguments,1);return Ii[++Mr]=function(){bv(t,void 0,s)},It(Mr),Mr},$a=function(e){delete Ii[e]},Av?It=function(i){kv.nextTick(Fr(i))}:Or&&Or.now?It=function(i){Or.now(Fr(i))}:ko&&!wv?(Br=new ko,Nr=Br.port2,Br.port1.onmessage=Ro,It=yv(Nr.postMessage,Nr)):De.addEventListener&&$o(De.postMessage)&&!De.importScripts&&xi&&xi.protocol!=="file:"&&!mu(Io)?(It=Io,De.addEventListener("message",Ro,!1)):Po in Ao("script")?It=function(i){wo.appendChild(Ao("script"))[Po]=function(){wo.removeChild(this),sn(i)}}:It=function(i){setTimeout(Fr(i),0)});var vu={set:Ea,clear:$a},gu=function(){this.head=null,this.tail=null};gu.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Su=gu,Iv=Hs,Cv=/ipad|iphone|ipod/i.test(Iv)&&typeof Pebble!="undefined",_v=Hs,Dv=/web0s(?!.*chrome)/i.test(_v),Mt=Te,Co=zs,Lv=za.f,Vr=vu.set,xv=Su,Ov=pu,Mv=Cv,Bv=Dv,Ur=Ws,_o=Mt.MutationObserver||Mt.WebKitMutationObserver,Do=Mt.document,Lo=Mt.process,os=Mt.Promise,xo=Lv(Mt,"queueMicrotask"),wa=xo&&xo.value,ei,Hr,jr,ls,Oo;if(!wa){var us=new xv,ds=function(){var i,e;for(Ur&&(i=Lo.domain)&&i.exit();e=us.get();)try{e()}catch(t){throw us.head&&ei(),t}i&&i.enter()};!Ov&&!Ur&&!Bv&&_o&&Do?(Hr=!0,jr=Do.createTextNode(""),new _o(ds).observe(jr,{characterData:!0}),ei=function(){jr.data=Hr=!Hr}):!Mv&&os&&os.resolve?(ls=os.resolve(void 0),ls.constructor=os,Oo=Co(ls.then,ls),ei=function(){Oo(ds)}):Ur?ei=function(){Lo.nextTick(ds)}:(Vr=Co(Vr,Mt),ei=function(){Vr(ds)}),wa=function(i){us.head||ei(),us.add(i)}}var Nv=wa,Fv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},rn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Vv=Te,mi=Vv.Promise,bu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Uv=bu,Hv=Ws,jv=!Uv&&!Hv&&typeof window=="object"&&typeof document=="object",Gv=Te,Ci=mi,Yv=ve,qv=Yl,zv=lu,Wv=Ae,Qv=jv,Kv=bu,Gr=Cl,Mo=Ci&&Ci.prototype,Jv=Wv("species"),Aa=!1,yu=Yv(Gv.PromiseRejectionEvent),Xv=qv("Promise",function(){var i=zv(Ci),e=i!==String(Ci);if(!e&&Gr===66||!(Mo.catch&&Mo.finally))return!0;if(!Gr||Gr<51||!/native code/.test(i)){var t=new Ci(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jv]=s,Aa=t.then(function(){})instanceof s,!Aa)return!0}return!e&&(Qv||Kv)&&!yu}),Gi={CONSTRUCTOR:Xv,REJECTION_EVENT:yu,SUBCLASSING:Aa},vi={},Bo=Ft,Zv=TypeError,eg=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw Zv("Bad Promise constructor");e=s,t=r}),this.resolve=Bo(e),this.reject=Bo(t)};vi.f=function(i){return new eg(i)};var tg=qe,Ls=Ws,yt=Te,Yi=Le,ig=Ja,sg=Za,rg=Gm,ag=Ft,ka=ve,ng=ht,og=zm,lg=fu,Tu=vu.set,an=Nv,ug=Fv,dg=rn,cg=Su,Eu=Nl,Pa=mi,nn=Gi,$u=vi,Qs="Promise",wu=nn.CONSTRUCTOR,hg=nn.REJECTION_EVENT;nn.SUBCLASSING;var Yr=Eu.getterFor(Qs),fg=Eu.set,pg=Pa&&Pa.prototype,ai=Pa,qr=pg,Au=yt.TypeError,Ra=yt.document,on=yt.process,Ia=$u.f,mg=Ia,vg=!!(Ra&&Ra.createEvent&&yt.dispatchEvent),ku="unhandledrejection",gg="rejectionhandled",No=0,Pu=1,Sg=2,ln=1,Ru=2,cs,Fo,bg,Iu=function(i){var e;return ng(i)&&ka(e=i.then)?e:!1},Cu=function(i,e){var t=e.value,s=e.state==Pu,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,l,d;try{r?(s||(e.rejection===Ru&&Tg(e),e.rejection=ln),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===i.promise?n(Au("Promise-chain cycle")):(l=Iu(u))?Yi(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},_u=function(i,e){i.notified||(i.notified=!0,an(function(){for(var t=i.reactions,s;s=t.get();)Cu(s,i);i.notified=!1,e&&!i.rejection&&yg(i)}))},Du=function(i,e,t){var s,r;vg?(s=Ra.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),yt.dispatchEvent(s)):s={promise:e,reason:t},!hg&&(r=yt["on"+i])?r(s):i===ku&&ug("Unhandled promise rejection",t)},yg=function(i){Yi(Tu,yt,function(){var e=i.facade,t=i.value,s=Vo(i),r;if(s&&(r=dg(function(){Ls?on.emit("unhandledRejection",t,e):Du(ku,e,t)}),i.rejection=Ls||Vo(i)?Ru:ln,r.error))throw r.value})},Vo=function(i){return i.rejection!==ln&&!i.parent},Tg=function(i){Yi(Tu,yt,function(){var e=i.facade;Ls?on.emit("rejectionHandled",e):Du(gg,e,i.value)})},ni=function(i,e,t){return function(s){i(e,s,t)}},di=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Sg,_u(i,!0))},Ca=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Au("Promise can't be resolved itself");var s=Iu(e);s?an(function(){var r={done:!1};try{Yi(s,e,ni(Ca,r,i),ni(di,r,i))}catch(a){di(r,a,i)}}):(i.value=e,i.state=Pu,_u(i,!1))}catch(r){di({done:!1},r,i)}}};wu&&(ai=function(e){og(this,qr),ag(e),Yi(cs,this);var t=Yr(this);try{e(ni(Ca,t),ni(di,t))}catch(s){di(t,s)}},qr=ai.prototype,cs=function(e){fg(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:No,value:void 0})},cs.prototype=ig(qr,"then",function(e,t){var s=Yr(this),r=Ia(lg(this,ai));return s.parent=!0,r.ok=ka(e)?e:!0,r.fail=ka(t)&&t,r.domain=Ls?on.domain:void 0,s.state==No?s.reactions.add(r):an(function(){Cu(r,s)}),r.promise}),Fo=function(){var i=new cs,e=Yr(i);this.promise=i,this.resolve=ni(Ca,e),this.reject=ni(di,e)},$u.f=Ia=function(i){return i===ai||i===bg?new Fo(i):mg(i)});tg({global:!0,constructor:!0,wrap:!0,forced:wu},{Promise:ai});sg(ai,Qs,!1,!0);rg(Qs);var Eg=Ae,Lu=Eg("iterator"),xu=!1;try{var $g=0,Uo={next:function(){return{done:!!$g++}},return:function(){xu=!0}};Uo[Lu]=function(){return this},Array.from(Uo,function(){throw 2})}catch(i){}var wg=function(i,e){if(!e&&!xu)return!1;var t=!1;try{var s={};s[Lu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Ag=mi,kg=wg,Pg=Gi.CONSTRUCTOR,Ou=Pg||!kg(function(i){Ag.all(i).then(void 0,function(){})}),Rg=qe,Ig=Le,Cg=Ft,_g=vi,Dg=rn,Lg=en,xg=Ou;Rg({target:"Promise",stat:!0,forced:xg},{all:function(e){var t=this,s=_g.f(t),r=s.resolve,a=s.reject,n=Dg(function(){var o=Cg(t.resolve),u=[],l=0,d=1;Lg(e,function(c){var h=l++,f=!1;d++,Ig(o,t,c).then(function(v){f||(f=!0,u[h]=v,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),s.promise}});var Og=qe,Mg=Gi.CONSTRUCTOR,Ho=mi;Ho&&Ho.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(i){return this.then(void 0,i)}});var Bg=qe,Ng=Le,Fg=Ft,Vg=vi,Ug=rn,Hg=en,jg=Ou;Bg({target:"Promise",stat:!0,forced:jg},{race:function(e){var t=this,s=Vg.f(t),r=s.reject,a=Ug(function(){var n=Fg(t.resolve);Hg(e,function(o){Ng(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Gg=qe,Yg=Le,qg=vi,zg=Gi.CONSTRUCTOR;Gg({target:"Promise",stat:!0,forced:zg},{reject:function(e){var t=qg.f(this);return Yg(t.reject,void 0,e),t.promise}});var Wg=ft,Qg=ht,Kg=vi,Mu=function(i,e){if(Wg(i),Qg(e)&&e.constructor===i)return e;var t=Kg.f(i),s=t.resolve;return s(e),t.promise},Jg=qe,Xg=Nt,Zg=Ic,eS=mi,tS=Gi.CONSTRUCTOR,iS=Mu,sS=Xg("Promise"),rS=!tS;Jg({target:"Promise",stat:!0,forced:Zg},{resolve:function(e){return iS(rS&&this===sS?eS:this,e)}});var aS=qe,_a=mi,nS=Fe,oS=Nt,lS=ve,uS=fu,jo=Mu,dS=_a&&_a.prototype,cS=!!_a&&nS(function(){dS.finally.call({then:function(){}},function(){})});aS({target:"Promise",proto:!0,real:!0,forced:cS},{finally:function(i){var e=uS(this,oS("Promise")),t=lS(i);return this.then(t?function(s){return jo(e,i()).then(function(){return s})}:i,t?function(s){return jo(e,i()).then(function(){throw s})}:i)}});var hS=Nt,un=hS,fS=un,pS=fS("Promise","finally"),mS=pS,vS=mS,gS=vS,SS=gS,dn=Fs(SS),ge;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ge||(ge={}));var Ye=(i,e=0,t=ge.OFFSET_P)=>{switch(t){case ge.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ge.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ge.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:G(t)}return i};const Go=(i,e)=>{var t;switch(e){case ge.OFFSET_P:return NaN;case ge.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ge.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:G(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ce{constructor(e){this.transitionStarted$=new D,this.transitionEnded$=new D,this.transitionUpdated$=new D,this.forceChanged$=new D,this.stateChangeStarted$=F(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=F(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||P(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const bS=i=>{switch(i){case y.MPEG:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return G(i)}};var V;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const yS=5,TS=5,ES=500,Yo=7e3;class $S{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ce(V.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&s!==V.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:G(s)}break}case p.PLAYING:{switch(s){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:G(s)}break}case p.PAUSED:{switch(s){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:G(s)}break}default:G(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(bS(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 re;this.subscription.add(e),this.subscription.add(F(this.videoState.stateChangeStarted$.pipe(A(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(A(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 D;e.add(r.pipe(tt(ES)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>yS)&&r.next(o),a=o})),e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(x(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<TS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:G(n)}}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=F(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===V.READY&&this.videoState.setState(V.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case y.MPEG:{const d=s[e];R(d);const c=yd(Object.keys(d));R(c);const h=d[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=s[e];R(d),r=d.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=s[e];R(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=s[e];R(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=s[e];R(d),r=Ye(d.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:d,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return G(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:l}=this.params.meta;return P(u)&&(o.metadata.title=u),P(l)&&(o.metadata.subtitle=l),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===z.Applying||s.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Td(Yo).subscribe(()=>a(`timeout(${Yo})`)))});dn(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const cn=i=>{i.removeAttribute("src"),i.load()},wS=i=>{try{i.pause(),i.playbackRate=0,cn(i),i.remove()}catch(e){console.error(e)}};class AS{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 Da=window.WeakMap?new WeakMap:new AS,Vt=i=>{let e=i.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),i.appendChild(e)),Da.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ut=i=>{const e=Da.get(i);Da.delete(i),e?cn(i):wS(i)},ot=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),l=new re;return r&&l.add(r.subscribe(d=>{const c=i.getState();s(d,c)&&i.setState(d)},a)),s(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),u&&i.setState(d.to)},a)),l},qi=(i,e,t)=>ot(e,()=>i.loop,s=>{P(s)&&(i.loop=s)},{onError:t}),Ht=(i,e,t,s)=>ot(e,()=>({muted:i.muted,volume:i.volume}),r=>{P(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),gi=(i,e,t,s)=>ot(e,()=>i.playbackRate,r=>{P(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),kS=i=>["__",i.language,i.label].join("|"),PS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class Et{constructor(){this.available$=new D,this.current$=new b(void 0),this.error$=new D,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(ot(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ot(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ot(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(ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(x(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(F(x(e,"addtrack"),x(e,"removetrack"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),fe((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(F(x(e,"change"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),A(s=>s&&this.htmlTextTrackToITextTrack(s).id),fe()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(x(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,l,d,c,h;const f=(l=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&l!==void 0?l:null;f&&f.length&&(this.applyCueSettings((c=(d=o.target)===null||d===void 0?void 0:d.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(x(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;P(t.align)&&(r.align=t.align),P(t.position)&&(r.position=t.position),P(t.size)&&(r.size=t.size),P(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Et.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:kS(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:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.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(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(K(e)||!PS(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){R(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class hn{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 Bu=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qo=i=>{const e=Bu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},RS=i=>{const e=Bu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},IS=3;var CS=(i,e,t=IS)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const jt=i=>{const e=w=>x(i,w).pipe(ks(void 0)),s=F(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>x(i,w))).pipe(A(w=>w.type==="ended"?i.readyState<2:i.readyState<3),fe()),r=F(x(i,"progress"),x(i,"timeupdate")).pipe(A(()=>CS(i.buffered,i.currentTime))),n=Fa().browser===yl.Safari?it({play:e("play").pipe(Pe()),playing:e("playing")}).pipe(ks(void 0)):e("playing"),o=x(i,"volumechange").pipe(A(()=>({muted:i.muted,volume:i.volume}))),u=x(i,"ratechange").pipe(A(()=>i.playbackRate)),l=x(i,"error").pipe(he(()=>!!(i.error||i.played.length)),A(()=>{var w;const $=i.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(w=i.error)!==null&&w!==void 0?w:void 0}})),d=x(i,"timeupdate").pipe(A(()=>i.currentTime)),c=new D,h=.3;let f;d.subscribe(w=>{i.loop&&P(f)&&P(w)&&f>=i.duration-h&&w<=h&&c.next(f),f=w});const v=x(i,"enterpictureinpicture"),m=x(i,"leavepictureinpicture"),g=new b(RS(i));v.subscribe(()=>g.next(!0)),m.subscribe(()=>g.next(!1));const S=new b(qo(i));return x(i,"fullscreenchange").pipe(A(()=>qo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(he(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:x(i,"durationchange").pipe(A(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Ks=i=>{switch(i){case"mobile":return _e.Q_144P;case"lowest":return _e.Q_240P;case"low":return _e.Q_360P;case"sd":case"medium":return _e.Q_480P;case"hd":case"high":return _e.Q_720P;case"fullhd":case"full":return _e.Q_1080P;case"quadhd":case"quad":return _e.Q_1440P;case"ultrahd":case"ultra":return _e.Q_2160P}},_S=qe,DS=Ys,LS=Ka,xS=Qa;_S({target:"Array",proto:!0},{at:function(e){var t=DS(this),s=LS(t),r=xS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var OS=un,MS=OS("Array","at"),BS=MS,NS=BS,FS=NS,VS=FS,nt=Fs(VS);let fn=!1,lt={};const US=i=>{fn=i},HS=()=>{lt={}},jS=i=>{i(lt)},hs=(i,e)=>{var t;fn&&(lt.meta=(t=lt.meta)!==null&&t!==void 0?t:{},lt.meta[i]=e)};class Xe{constructor(e){this.name=e}next(e){var t,s;if(!fn)return;lt.series=(t=lt.series)!==null&&t!==void 0?t:{};const r=(s=lt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),lt.series[this.name]=r}}var Lt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(Lt||(Lt={}));const GS=new Xe("best_bitrate"),YS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class qS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const zS='Assertion "ABR Tracks is empty array" failed',Js=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{var h,f,v,m,g;Ed(i,zS);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},w=E&&Bi(E),$=s.considerPlaybackRate&&P(o)?o:1,k=i.filter(N=>!Ot(N.quality)).sort((N,C)=>ui(N.quality,C.quality)?-1:1),j=(f=nt(k,-1))===null||f===void 0?void 0:f.quality,Y=(v=nt(k,0))===null||v===void 0?void 0:v.quality,J=K(r)||P(r.min)&&P(r.max)&&ys(r.max,r.min)||P(r.min)&&Y&&ui(r.min,Y)||P(r.max)&&j&&ys(r.max,j),q=$*YS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),X={},B=k.filter(N=>(w?ys(N.quality,w):!0)?(P(t)&&isFinite(t)&&P(N.bitrate)?t-a>=N.bitrate*q:!0)?s.lazyQualitySwitch&&P(s.minBufferToSwitchUp)&&u&&!Ot(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&ui(N.quality,u.quality)?(X[N.quality]=Lt.Buffer,!1):!!d&&da(N.quality,d)?(X[N.quality]=Lt.DroppedFramesLimit,!1):J||(K(r.max)||Ps(N.quality,r.max))&&(K(r.min)||da(N.quality,r.min))?!0:(X[N.quality]=Lt.FitsQualityLimits,!1):(X[N.quality]=Lt.FitsThroughput,!1):(X[N.quality]=Lt.FitsContainer,!1))[0];B&&B.bitrate&&GS.next(B.bitrate);const L=(m=B!=null?B:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];L.quality!==((g=l==null?void 0:l.last)===null||g===void 0?void 0:g.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as b,Subject as D,Subscription as re,isNonNullable as k,ErrorCategory as _,isNullable as K,fromEvent as x,assertNever as j,merge as F,tap as Li,map as w,observableFrom as Ne,filterChanged as fe,assertNonNullable as R,debounce as tt,getHighestQuality as yd,timeout as Td,getCurrentBrowser as Fa,CurrentClientBrowser as yl,combine as it,once as Pe,mapTo as ks,filter as he,VideoQuality as _e,now as le,assertNotEmptyArray as Ed,videoSizeToQuality as Ot,isInvariantQuality as Mt,isHigher as di,isLower as ys,isHigherOrEqual as da,isLowerOrEqual as Ps,interval as Rs,videoQualityToHeight as $d,Observable as Ns,debounceFn as wd,abortable as Re,getExponentialDelay as Ts,isIOS as Ad,CurrentClientDevice as kd,safeStorage as hr,fillWithDefault as Pd,Logger as Rd}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as UT,Subject as HT,Subscription as jT,ValueSubject as GT,VideoQuality as YT}from"@vkontakte/videoplayer-shared/es2015.esm.js";const Id="2.0.100";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var y;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var $e;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})($e||($e={}));var be;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(be||(be={}));var ca;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ca||(ca={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var gt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(gt||(gt={}));function ee(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(d){try{l(s.next(d))}catch(c){n(c)}}function u(d){try{l(s.throw(d))}catch(c){n(c)}}function l(d){d.done?a(d.value):r(d.value).then(o,u)}l((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function Ie(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(v,m){a.push([h,f,v,m])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(v){c(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(l,d):c(a[0][2],h)}function l(h){o("next",h)}function d(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Cd=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class _d{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(be.NOT_AVAILABLE),this.errorEvent$=new D,this.realCastState$=new b(be.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=k((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Cd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(x(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return j(r.sessionState)}})).add(F(x(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Li(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),Ne([s.getCastState()])).pipe(fe(),w(Dd),Li(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===be.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();R(u);const l=u.getCastDevice(),d=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===be.CONNECTED?k(this.connection$.getValue())?be.CONNECTED:be.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Dd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return be.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return be.AVAILABLE;case cast.framework.CastState.CONNECTING:return be.CONNECTING;case cast.framework.CastState.CONNECTED:return be.CONNECTED;default:return j(i)}};var fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Fs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Fe=function(i){try{return!!i()}catch(e){return!0}},Ld=Fe,Vs=!Ld(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Tl=Vs,El=Function.prototype,ha=El.call,xd=Tl&&El.bind.bind(ha,ha),Ve=Tl?xd:function(i){return function(){return ha.apply(i,arguments)}},$l=Ve,Od=$l({}.toString),Md=$l("".slice),Ni=function(i){return Md(Od(i),8,-1)},Bd=Ve,Nd=Fe,Fd=Ni,pr=Object,Vd=Bd("".split),Ud=Nd(function(){return!pr("z").propertyIsEnumerable(0)})?function(i){return Fd(i)=="String"?Vd(i,""):pr(i)}:pr,Fi=function(i){return i==null},Hd=Fi,jd=TypeError,Va=function(i){if(Hd(i))throw jd("Can't call method on "+i);return i},Gd=Ud,Yd=Va,Vi=function(i){return Gd(Yd(i))},mi={},Zi=function(i){return i&&i.Math==Math&&i},Te=Zi(typeof globalThis=="object"&&globalThis)||Zi(typeof window=="object"&&window)||Zi(typeof self=="object"&&self)||Zi(typeof fr=="object"&&fr)||function(){return this}()||fr||Function("return this")(),fa=typeof document=="object"&&document.all,qd=typeof fa=="undefined"&&fa!==void 0,wl={all:fa,IS_HTMLDDA:qd},Al=wl,zd=Al.all,ve=Al.IS_HTMLDDA?function(i){return typeof i=="function"||i===zd}:function(i){return typeof i=="function"},Wd=Te,Qd=ve,In=Wd.WeakMap,Kd=Qd(In)&&/native code/.test(String(In)),Cn=ve,kl=wl,Jd=kl.all,ht=kl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Cn(i)||i===Jd}:function(i){return typeof i=="object"?i!==null:Cn(i)},Xd=Fe,Tt=!Xd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Nt={},Zd=Te,_n=ht,pa=Zd.document,ec=_n(pa)&&_n(pa.createElement),Ua=function(i){return ec?pa.createElement(i):{}},tc=Tt,ic=Fe,sc=Ua,Pl=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Tt,ac=Fe,Rl=rc&&ac(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),nc=ht,oc=String,lc=TypeError,ft=function(i){if(nc(i))return i;throw lc(oc(i)+" is not an object")},uc=Vs,es=Function.prototype.call,Le=uc?es.bind(es):function(){return es.apply(es,arguments)},Ha={},mr=Ha,vr=Te,dc=ve,Dn=function(i){return dc(i)?i:void 0},Ft=function(i,e){return arguments.length<2?Dn(mr[i])||Dn(vr[i]):mr[i]&&mr[i][e]||vr[i]&&vr[i][e]},cc=Ve,Us=cc({}.isPrototypeOf),Hs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Il=Te,gr=Hs,Ln=Il.process,xn=Il.Deno,On=Ln&&Ln.versions||xn&&xn.version,Mn=On&&On.v8,Ge,Is;Mn&&(Ge=Mn.split("."),Is=Ge[0]>0&&Ge[0]<4?1:+(Ge[0]+Ge[1]));!Is&&gr&&(Ge=gr.match(/Edge\/(\d+)/),(!Ge||Ge[1]>=74)&&(Ge=gr.match(/Chrome\/(\d+)/),Ge&&(Is=+Ge[1])));var Cl=Is,Bn=Cl,hc=Fe,fc=Te,pc=fc.String,_l=!!Object.getOwnPropertySymbols&&!hc(function(){var i=Symbol();return!pc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Bn&&Bn<41}),mc=_l,Dl=mc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",vc=Ft,gc=ve,Sc=Us,bc=Dl,yc=Object,Ll=bc?function(i){return typeof i=="symbol"}:function(i){var e=vc("Symbol");return gc(e)&&Sc(e.prototype,yc(i))},Tc=String,js=function(i){try{return Tc(i)}catch(e){return"Object"}},Ec=ve,$c=js,wc=TypeError,Vt=function(i){if(Ec(i))return i;throw wc($c(i)+" is not a function")},Ac=Vt,kc=Fi,Gs=function(i,e){var t=i[e];return kc(t)?void 0:Ac(t)},Sr=Le,br=ve,yr=ht,Pc=TypeError,Rc=function(i,e){var t,s;if(e==="string"&&br(t=i.toString)&&!yr(s=Sr(t,i))||br(t=i.valueOf)&&!yr(s=Sr(t,i))||e!=="string"&&br(t=i.toString)&&!yr(s=Sr(t,i)))return s;throw Pc("Can't convert object to primitive value")},xl={exports:{}},Ic=!0,Nn=Te,Cc=Object.defineProperty,_c=function(i,e){try{Cc(Nn,i,{value:e,configurable:!0,writable:!0})}catch(t){Nn[i]=e}return e},Dc=Te,Lc=_c,Fn="__core-js_shared__",xc=Dc[Fn]||Lc(Fn,{}),ja=xc,Vn=ja;(xl.exports=function(i,e){return Vn[i]||(Vn[i]=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 Ol=xl.exports,Oc=Va,Mc=Object,Ys=function(i){return Mc(Oc(i))},Bc=Ve,Nc=Ys,Fc=Bc({}.hasOwnProperty),rt=Object.hasOwn||function(e,t){return Fc(Nc(e),t)},Vc=Ve,Uc=0,Hc=Math.random(),jc=Vc(1 .toString),Ml=function(i){return"Symbol("+(i===void 0?"":i)+")_"+jc(++Uc+Hc,36)},Gc=Te,Yc=Ol,Un=rt,qc=Ml,zc=_l,Wc=Dl,ai=Gc.Symbol,Tr=Yc("wks"),Qc=Wc?ai.for||ai:ai&&ai.withoutSetter||qc,Ae=function(i){return Un(Tr,i)||(Tr[i]=zc&&Un(ai,i)?ai[i]:Qc("Symbol."+i)),Tr[i]},Kc=Le,Hn=ht,jn=Ll,Jc=Gs,Xc=Rc,Zc=Ae,eh=TypeError,th=Zc("toPrimitive"),ih=function(i,e){if(!Hn(i)||jn(i))return i;var t=Jc(i,th),s;if(t){if(e===void 0&&(e="default"),s=Kc(t,i,e),!Hn(s)||jn(s))return s;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(i,e)},sh=ih,rh=Ll,Ga=function(i){var e=sh(i,"string");return rh(e)?e:e+""},ah=Tt,nh=Pl,oh=Rl,ts=ft,Gn=Ga,lh=TypeError,Er=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,$r="enumerable",wr="configurable",Ar="writable";Nt.f=ah?oh?function(e,t,s){if(ts(e),t=Gn(t),ts(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Ar in s&&!s[Ar]){var r=uh(e,t);r&&r[Ar]&&(e[t]=s.value,s={configurable:wr in s?s[wr]:r[wr],enumerable:$r in s?s[$r]:r[$r],writable:!1})}return Er(e,t,s)}:Er:function(e,t,s){if(ts(e),t=Gn(t),ts(s),nh)try{return Er(e,t,s)}catch(r){}if("get"in s||"set"in s)throw lh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var qs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},dh=Tt,ch=Nt,hh=qs,Ui=dh?function(i,e,t){return ch.f(i,e,hh(1,t))}:function(i,e,t){return i[e]=t,i},fh=Ol,ph=Ml,Yn=fh("keys"),Ya=function(i){return Yn[i]||(Yn[i]=ph(i))},qa={},mh=Kd,Bl=Te,vh=ht,gh=Ui,kr=rt,Pr=ja,Sh=Ya,bh=qa,qn="Object already initialized",ma=Bl.TypeError,yh=Bl.WeakMap,Cs,xi,_s,Th=function(i){return _s(i)?xi(i):Cs(i,{})},Eh=function(i){return function(e){var t;if(!vh(e)||(t=xi(e)).type!==i)throw ma("Incompatible receiver, "+i+" required");return t}};if(mh||Pr.state){var Qe=Pr.state||(Pr.state=new yh);Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Cs=function(i,e){if(Qe.has(i))throw ma(qn);return e.facade=i,Qe.set(i,e),e},xi=function(i){return Qe.get(i)||{}},_s=function(i){return Qe.has(i)}}else{var Xt=Sh("state");bh[Xt]=!0,Cs=function(i,e){if(kr(i,Xt))throw ma(qn);return e.facade=i,gh(i,Xt,e),e},xi=function(i){return kr(i,Xt)?i[Xt]:{}},_s=function(i){return kr(i,Xt)}}var Nl={set:Cs,get:xi,has:_s,enforce:Th,getterFor:Eh},$h=Vs,Fl=Function.prototype,zn=Fl.apply,Wn=Fl.call,Vl=typeof Reflect=="object"&&Reflect.apply||($h?Wn.bind(zn):function(){return Wn.apply(zn,arguments)}),wh=Ni,Ah=Ve,Ul=function(i){if(wh(i)==="Function")return Ah(i)},za={},Hl={},jl={}.propertyIsEnumerable,Gl=Object.getOwnPropertyDescriptor,kh=Gl&&!jl.call({1:2},1);Hl.f=kh?function(e){var t=Gl(this,e);return!!t&&t.enumerable}:jl;var Ph=Tt,Rh=Le,Ih=Hl,Ch=qs,_h=Vi,Dh=Ga,Lh=rt,xh=Pl,Qn=Object.getOwnPropertyDescriptor;za.f=Ph?Qn:function(e,t){if(e=_h(e),t=Dh(t),xh)try{return Qn(e,t)}catch(s){}if(Lh(e,t))return Ch(!Rh(Ih.f,e,t),e[t])};var Oh=Fe,Mh=ve,Bh=/#|\.prototype\./,Hi=function(i,e){var t=Fh[Nh(i)];return t==Uh?!0:t==Vh?!1:Mh(e)?Oh(e):!!e},Nh=Hi.normalize=function(i){return String(i).replace(Bh,".").toLowerCase()},Fh=Hi.data={},Vh=Hi.NATIVE="N",Uh=Hi.POLYFILL="P",Yl=Hi,Kn=Ul,Hh=Vt,jh=Vs,Gh=Kn(Kn.bind),zs=function(i,e){return Hh(i),e===void 0?i:jh?Gh(i,e):function(){return i.apply(e,arguments)}},is=Te,Yh=Vl,qh=Ul,zh=ve,Wh=za.f,Qh=Yl,Zt=Ha,Kh=zs,ei=Ui,Jn=rt,Jh=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Yh(i,this,arguments)};return e.prototype=i.prototype,e},qe=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?is:r?is[t]:(is[t]||{}).prototype,o=s?Zt:Zt[t]||ei(Zt,t,{})[t],u=o.prototype,l,d,c,h,f,v,m,g,S;for(h in e)l=Qh(s?h:t+(r?".":"#")+h,i.forced),d=!l&&n&&Jn(n,h),v=o[h],d&&(i.dontCallGetSet?(S=Wh(n,h),m=S&&S.value):m=n[h]),f=d&&m?m:e[h],!(d&&typeof v==typeof f)&&(i.bind&&d?g=Kh(f,is):i.wrap&&d?g=Jh(f):a&&zh(f)?g=qh(f):g=f,(i.sham||f&&f.sham||v&&v.sham)&&ei(g,"sham",!0),ei(o,h,g),a&&(c=t+"Prototype",Jn(Zt,c)||ei(Zt,c,{}),ei(Zt[c],h,f),i.real&&u&&(l||!u[h])&&ei(u,h,f)))},va=Tt,Xh=rt,ql=Function.prototype,Zh=va&&Object.getOwnPropertyDescriptor,Wa=Xh(ql,"name"),ef=Wa&&function(){}.name==="something",tf=Wa&&(!va||va&&Zh(ql,"name").configurable),sf={EXISTS:Wa,PROPER:ef,CONFIGURABLE:tf},zl={},rf=Math.ceil,af=Math.floor,nf=Math.trunc||function(e){var t=+e;return(t>0?af:rf)(t)},of=nf,Qa=function(i){var e=+i;return e!==e||e===0?0:of(e)},lf=Qa,uf=Math.max,df=Math.min,cf=function(i,e){var t=lf(i);return t<0?uf(t+e,0):df(t,e)},hf=Qa,ff=Math.min,pf=function(i){return i>0?ff(hf(i),9007199254740991):0},mf=pf,Ka=function(i){return mf(i.length)},vf=Vi,gf=cf,Sf=Ka,Xn=function(i){return function(e,t,s){var r=vf(e),a=Sf(r),n=gf(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},bf={includes:Xn(!0),indexOf:Xn(!1)},yf=Ve,Rr=rt,Tf=Vi,Ef=bf.indexOf,$f=qa,Zn=yf([].push),wf=function(i,e){var t=Tf(i),s=0,r=[],a;for(a in t)!Rr($f,a)&&Rr(t,a)&&Zn(r,a);for(;e.length>s;)Rr(t,a=e[s++])&&(~Ef(r,a)||Zn(r,a));return r},Wl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Af=wf,kf=Wl,Pf=Object.keys||function(e){return Af(e,kf)},Rf=Tt,If=Rl,Cf=Nt,_f=ft,Df=Vi,Lf=Pf;zl.f=Rf&&!If?Object.defineProperties:function(e,t){_f(e);for(var s=Df(t),r=Lf(t),a=r.length,n=0,o;a>n;)Cf.f(e,o=r[n++],s[o]);return e};var xf=Ft,Ql=xf("document","documentElement"),Of=ft,Mf=zl,eo=Wl,Bf=qa,Nf=Ql,Ff=Ua,Vf=Ya,to=">",io="<",ga="prototype",Sa="script",Kl=Vf("IE_PROTO"),Ir=function(){},Jl=function(i){return io+Sa+to+i+io+"/"+Sa+to},so=function(i){i.write(Jl("")),i.close();var e=i.parentWindow.Object;return i=null,e},Uf=function(){var i=Ff("iframe"),e="java"+Sa+":",t;return i.style.display="none",Nf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Jl("document.F=Object")),t.close(),t.F},ss,Es=function(){try{ss=new ActiveXObject("htmlfile")}catch(e){}Es=typeof document!="undefined"?document.domain&&ss?so(ss):Uf():so(ss);for(var i=eo.length;i--;)delete Es[ga][eo[i]];return Es()};Bf[Kl]=!0;var Xl=Object.create||function(e,t){var s;return e!==null?(Ir[ga]=Of(e),s=new Ir,Ir[ga]=null,s[Kl]=e):s=Es(),t===void 0?s:Mf.f(s,t)},Hf=Fe,jf=!Hf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Gf=rt,Yf=ve,qf=Ys,zf=Ya,Wf=jf,ro=zf("IE_PROTO"),ba=Object,Qf=ba.prototype,Zl=Wf?ba.getPrototypeOf:function(i){var e=qf(i);if(Gf(e,ro))return e[ro];var t=e.constructor;return Yf(t)&&e instanceof t?t.prototype:e instanceof ba?Qf:null},Kf=Ui,Ja=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Kf(i,e,t),i},Jf=Fe,Xf=ve,Zf=ht,ep=Xl,ao=Zl,tp=Ja,ip=Ae,ya=ip("iterator"),eu=!1,ut,Cr,_r;[].keys&&(_r=[].keys(),"next"in _r?(Cr=ao(ao(_r)),Cr!==Object.prototype&&(ut=Cr)):eu=!0);var sp=!Zf(ut)||Jf(function(){var i={};return ut[ya].call(i)!==i});sp?ut={}:ut=ep(ut);Xf(ut[ya])||tp(ut,ya,function(){return this});var tu={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:eu},rp=Ae,ap=rp("toStringTag"),iu={};iu[ap]="z";var Xa=String(iu)==="[object z]",np=Xa,op=ve,$s=Ni,lp=Ae,up=lp("toStringTag"),dp=Object,cp=$s(function(){return arguments}())=="Arguments",hp=function(i,e){try{return i[e]}catch(t){}},ji=np?$s:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=hp(e=dp(i),up))=="string"?t:cp?$s(e):(s=$s(e))=="Object"&&op(e.callee)?"Arguments":s},fp=Xa,pp=ji,mp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},vp=Xa,gp=Nt.f,Sp=Ui,bp=rt,yp=mp,Tp=Ae,no=Tp("toStringTag"),Za=function(i,e,t,s){if(i){var r=t?i:i.prototype;bp(r,no)||gp(r,no,{configurable:!0,value:e}),s&&!vp&&Sp(r,"toString",yp)}},Ep=tu.IteratorPrototype,$p=Xl,wp=qs,Ap=Za,kp=mi,Pp=function(){return this},Rp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=$p(Ep,{next:wp(+!s,t)}),Ap(i,r,!1,!0),kp[r]=Pp,i},Ip=qe,Cp=Le,su=sf,_p=Rp,Dp=Zl,Lp=Za,oo=Ja,xp=Ae,lo=mi,ru=tu,Op=su.PROPER;su.CONFIGURABLE;ru.IteratorPrototype;var rs=ru.BUGGY_SAFARI_ITERATORS,Dr=xp("iterator"),uo="keys",as="values",co="entries",Mp=function(){return this},Bp=function(i,e,t,s,r,a,n){_p(t,e,s);var o=function(S){if(S===r&&h)return h;if(!rs&&S in d)return d[S];switch(S){case uo:return function(){return new t(this,S)};case as:return function(){return new t(this,S)};case co:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[Dr]||d["@@iterator"]||r&&d[r],h=!rs&&c||o(r),f=e=="Array"&&d.entries||c,v,m,g;if(f&&(v=Dp(f.call(new i)),v!==Object.prototype&&v.next&&(Lp(v,u,!0,!0),lo[u]=Mp)),Op&&r==as&&c&&c.name!==as&&(l=!0,h=function(){return Cp(c,this)}),r)if(m={values:o(as),keys:a?h:o(uo),entries:o(co)},n)for(g in m)(rs||l||!(g in d))&&oo(d,g,m[g]);else Ip({target:e,proto:!0,forced:rs||l},m);return n&&d[Dr]!==h&&oo(d,Dr,h,{name:r}),lo[e]=h,m},Np=function(i,e){return{value:i,done:e}},Fp=Vi,ho=mi,au=Nl;Nt.f;var Vp=Bp,ns=Np,nu="Array Iterator",Up=au.set,Hp=au.getterFor(nu);Vp(Array,"Array",function(i,e){Up(this,{type:nu,target:Fp(i),index:0,kind:e})},function(){var i=Hp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ns(void 0,!0)):t=="keys"?ns(s,!1):t=="values"?ns(e[s],!1):ns([s,e[s]],!1)},"values");ho.Arguments=ho.Array;var jp=Ae,Gp=mi,Yp=jp("iterator"),qp=Array.prototype,zp=function(i){return i!==void 0&&(Gp.Array===i||qp[Yp]===i)},Wp=ji,fo=Gs,Qp=Fi,Kp=mi,Jp=Ae,Xp=Jp("iterator"),ou=function(i){if(!Qp(i))return fo(i,Xp)||fo(i,"@@iterator")||Kp[Wp(i)]},Zp=Le,em=Vt,tm=ft,im=js,sm=ou,rm=TypeError,am=function(i,e){var t=arguments.length<2?sm(i):e;if(em(t))return tm(Zp(t,i));throw rm(im(i)+" is not iterable")},nm=Le,po=ft,om=Gs,lm=function(i,e,t){var s,r;po(i);try{if(s=om(i,"return"),!s){if(e==="throw")throw t;return t}s=nm(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return po(s),t},um=zs,dm=Le,cm=ft,hm=js,fm=zp,pm=Ka,mo=Us,mm=am,vm=ou,vo=lm,gm=TypeError,ws=function(i,e){this.stopped=i,this.result=e},go=ws.prototype,en=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=um(e,s),l,d,c,h,f,v,m,g=function(E){return l&&vo(l,"normal",E),new ws(!0,E)},S=function(E){return r?(cm(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)l=i.iterator;else if(n)l=i;else{if(d=vm(i),!d)throw gm(hm(i)+" is not iterable");if(fm(d)){for(c=0,h=pm(i);h>c;c++)if(f=S(i[c]),f&&mo(go,f))return f;return new ws(!1)}l=mm(i,d)}for(v=a?i.next:l.next;!(m=dm(v,l)).done;){try{f=S(m.value)}catch(E){vo(l,"throw",E)}if(typeof f=="object"&&f&&mo(go,f))return f}return new ws(!1)},Sm=Ga,bm=Nt,ym=qs,Tm=function(i,e,t){var s=Sm(e);s in i?bm.f(i,s,ym(0,t)):i[s]=t},Em=qe,$m=en,wm=Tm;Em({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $m(e,function(s,r){wm(t,s,r)},{AS_ENTRIES:!0}),t}});var Am=Ha,km=Am.Object.fromEntries,Pm={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},Rm=Pm,Im=Te,Cm=ji,_m=Ui,So=mi,Dm=Ae,bo=Dm("toStringTag");for(var Lr in Rm){var yo=Im[Lr],xr=yo&&yo.prototype;xr&&Cm(xr)!==bo&&_m(xr,bo,Lr),So[Lr]=So.Array}var Lm=km,xm=Lm,Om=xm,Mm=Om,Ds=Fs(Mm),Bm=Ni,Ws=typeof process!="undefined"&&Bm(process)=="process",Nm=Nt,Fm=function(i,e,t){return Nm.f(i,e,t)},Vm=Ft,Um=Fm,Hm=Ae,jm=Tt,To=Hm("species"),Gm=function(i){var e=Vm(i);jm&&e&&!e[To]&&Um(e,To,{configurable:!0,get:function(){return this}})},Ym=Us,qm=TypeError,zm=function(i,e){if(Ym(e,i))return i;throw qm("Incorrect invocation")},Wm=Ve,Qm=ve,Ta=ja,Km=Wm(Function.toString);Qm(Ta.inspectSource)||(Ta.inspectSource=function(i){return Km(i)});var lu=Ta.inspectSource,Jm=Ve,Xm=Fe,uu=ve,Zm=ji,ev=Ft,tv=lu,du=function(){},iv=[],cu=ev("Reflect","construct"),tn=/^\s*(?:class|function)\b/,sv=Jm(tn.exec),rv=!tn.exec(du),wi=function(e){if(!uu(e))return!1;try{return cu(du,iv,e),!0}catch(t){return!1}},hu=function(e){if(!uu(e))return!1;switch(Zm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rv||!!sv(tn,tv(e))}catch(t){return!0}};hu.sham=!0;var av=!cu||Xm(function(){var i;return wi(wi.call)||!wi(Object)||!wi(function(){i=!0})||i})?hu:wi,nv=av,ov=js,lv=TypeError,uv=function(i){if(nv(i))return i;throw lv(ov(i)+" is not a constructor")},Eo=ft,dv=uv,cv=Fi,hv=Ae,fv=hv("species"),fu=function(i,e){var t=Eo(i).constructor,s;return t===void 0||cv(s=Eo(t)[fv])?e:dv(s)},pv=Ve,mv=pv([].slice),vv=TypeError,gv=function(i,e){if(i<e)throw vv("Not enough arguments");return i},Sv=Hs,pu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sv),De=Te,bv=Vl,yv=zs,$o=ve,Tv=rt,mu=Fe,wo=Ql,Ev=mv,Ao=Ua,$v=gv,wv=pu,Av=Ws,Ea=De.setImmediate,$a=De.clearImmediate,kv=De.process,Or=De.Dispatch,Pv=De.Function,ko=De.MessageChannel,Rv=De.String,Mr=0,Ci={},Po="onreadystatechange",Oi,It,Br,Nr;mu(function(){Oi=De.location});var sn=function(i){if(Tv(Ci,i)){var e=Ci[i];delete Ci[i],e()}},Fr=function(i){return function(){sn(i)}},Ro=function(i){sn(i.data)},Io=function(i){De.postMessage(Rv(i),Oi.protocol+"//"+Oi.host)};(!Ea||!$a)&&(Ea=function(e){$v(arguments.length,1);var t=$o(e)?e:Pv(e),s=Ev(arguments,1);return Ci[++Mr]=function(){bv(t,void 0,s)},It(Mr),Mr},$a=function(e){delete Ci[e]},Av?It=function(i){kv.nextTick(Fr(i))}:Or&&Or.now?It=function(i){Or.now(Fr(i))}:ko&&!wv?(Br=new ko,Nr=Br.port2,Br.port1.onmessage=Ro,It=yv(Nr.postMessage,Nr)):De.addEventListener&&$o(De.postMessage)&&!De.importScripts&&Oi&&Oi.protocol!=="file:"&&!mu(Io)?(It=Io,De.addEventListener("message",Ro,!1)):Po in Ao("script")?It=function(i){wo.appendChild(Ao("script"))[Po]=function(){wo.removeChild(this),sn(i)}}:It=function(i){setTimeout(Fr(i),0)});var vu={set:Ea,clear:$a},gu=function(){this.head=null,this.tail=null};gu.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Su=gu,Iv=Hs,Cv=/ipad|iphone|ipod/i.test(Iv)&&typeof Pebble!="undefined",_v=Hs,Dv=/web0s(?!.*chrome)/i.test(_v),Bt=Te,Co=zs,Lv=za.f,Vr=vu.set,xv=Su,Ov=pu,Mv=Cv,Bv=Dv,Ur=Ws,_o=Bt.MutationObserver||Bt.WebKitMutationObserver,Do=Bt.document,Lo=Bt.process,os=Bt.Promise,xo=Lv(Bt,"queueMicrotask"),wa=xo&&xo.value,ti,Hr,jr,ls,Oo;if(!wa){var us=new xv,ds=function(){var i,e;for(Ur&&(i=Lo.domain)&&i.exit();e=us.get();)try{e()}catch(t){throw us.head&&ti(),t}i&&i.enter()};!Ov&&!Ur&&!Bv&&_o&&Do?(Hr=!0,jr=Do.createTextNode(""),new _o(ds).observe(jr,{characterData:!0}),ti=function(){jr.data=Hr=!Hr}):!Mv&&os&&os.resolve?(ls=os.resolve(void 0),ls.constructor=os,Oo=Co(ls.then,ls),ti=function(){Oo(ds)}):Ur?ti=function(){Lo.nextTick(ds)}:(Vr=Co(Vr,Bt),ti=function(){Vr(ds)}),wa=function(i){us.head||ti(),us.add(i)}}var Nv=wa,Fv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},rn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Vv=Te,vi=Vv.Promise,bu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Uv=bu,Hv=Ws,jv=!Uv&&!Hv&&typeof window=="object"&&typeof document=="object",Gv=Te,_i=vi,Yv=ve,qv=Yl,zv=lu,Wv=Ae,Qv=jv,Kv=bu,Gr=Cl,Mo=_i&&_i.prototype,Jv=Wv("species"),Aa=!1,yu=Yv(Gv.PromiseRejectionEvent),Xv=qv("Promise",function(){var i=zv(_i),e=i!==String(_i);if(!e&&Gr===66||!(Mo.catch&&Mo.finally))return!0;if(!Gr||Gr<51||!/native code/.test(i)){var t=new _i(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jv]=s,Aa=t.then(function(){})instanceof s,!Aa)return!0}return!e&&(Qv||Kv)&&!yu}),Gi={CONSTRUCTOR:Xv,REJECTION_EVENT:yu,SUBCLASSING:Aa},gi={},Bo=Vt,Zv=TypeError,eg=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw Zv("Bad Promise constructor");e=s,t=r}),this.resolve=Bo(e),this.reject=Bo(t)};gi.f=function(i){return new eg(i)};var tg=qe,Ls=Ws,yt=Te,Yi=Le,ig=Ja,sg=Za,rg=Gm,ag=Vt,ka=ve,ng=ht,og=zm,lg=fu,Tu=vu.set,an=Nv,ug=Fv,dg=rn,cg=Su,Eu=Nl,Pa=vi,nn=Gi,$u=gi,Qs="Promise",wu=nn.CONSTRUCTOR,hg=nn.REJECTION_EVENT;nn.SUBCLASSING;var Yr=Eu.getterFor(Qs),fg=Eu.set,pg=Pa&&Pa.prototype,ni=Pa,qr=pg,Au=yt.TypeError,Ra=yt.document,on=yt.process,Ia=$u.f,mg=Ia,vg=!!(Ra&&Ra.createEvent&&yt.dispatchEvent),ku="unhandledrejection",gg="rejectionhandled",No=0,Pu=1,Sg=2,ln=1,Ru=2,cs,Fo,bg,Iu=function(i){var e;return ng(i)&&ka(e=i.then)?e:!1},Cu=function(i,e){var t=e.value,s=e.state==Pu,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,l,d;try{r?(s||(e.rejection===Ru&&Tg(e),e.rejection=ln),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===i.promise?n(Au("Promise-chain cycle")):(l=Iu(u))?Yi(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},_u=function(i,e){i.notified||(i.notified=!0,an(function(){for(var t=i.reactions,s;s=t.get();)Cu(s,i);i.notified=!1,e&&!i.rejection&&yg(i)}))},Du=function(i,e,t){var s,r;vg?(s=Ra.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),yt.dispatchEvent(s)):s={promise:e,reason:t},!hg&&(r=yt["on"+i])?r(s):i===ku&&ug("Unhandled promise rejection",t)},yg=function(i){Yi(Tu,yt,function(){var e=i.facade,t=i.value,s=Vo(i),r;if(s&&(r=dg(function(){Ls?on.emit("unhandledRejection",t,e):Du(ku,e,t)}),i.rejection=Ls||Vo(i)?Ru:ln,r.error))throw r.value})},Vo=function(i){return i.rejection!==ln&&!i.parent},Tg=function(i){Yi(Tu,yt,function(){var e=i.facade;Ls?on.emit("rejectionHandled",e):Du(gg,e,i.value)})},oi=function(i,e,t){return function(s){i(e,s,t)}},ci=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Sg,_u(i,!0))},Ca=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Au("Promise can't be resolved itself");var s=Iu(e);s?an(function(){var r={done:!1};try{Yi(s,e,oi(Ca,r,i),oi(ci,r,i))}catch(a){ci(r,a,i)}}):(i.value=e,i.state=Pu,_u(i,!1))}catch(r){ci({done:!1},r,i)}}};wu&&(ni=function(e){og(this,qr),ag(e),Yi(cs,this);var t=Yr(this);try{e(oi(Ca,t),oi(ci,t))}catch(s){ci(t,s)}},qr=ni.prototype,cs=function(e){fg(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:No,value:void 0})},cs.prototype=ig(qr,"then",function(e,t){var s=Yr(this),r=Ia(lg(this,ni));return s.parent=!0,r.ok=ka(e)?e:!0,r.fail=ka(t)&&t,r.domain=Ls?on.domain:void 0,s.state==No?s.reactions.add(r):an(function(){Cu(r,s)}),r.promise}),Fo=function(){var i=new cs,e=Yr(i);this.promise=i,this.resolve=oi(Ca,e),this.reject=oi(ci,e)},$u.f=Ia=function(i){return i===ni||i===bg?new Fo(i):mg(i)});tg({global:!0,constructor:!0,wrap:!0,forced:wu},{Promise:ni});sg(ni,Qs,!1,!0);rg(Qs);var Eg=Ae,Lu=Eg("iterator"),xu=!1;try{var $g=0,Uo={next:function(){return{done:!!$g++}},return:function(){xu=!0}};Uo[Lu]=function(){return this},Array.from(Uo,function(){throw 2})}catch(i){}var wg=function(i,e){if(!e&&!xu)return!1;var t=!1;try{var s={};s[Lu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Ag=vi,kg=wg,Pg=Gi.CONSTRUCTOR,Ou=Pg||!kg(function(i){Ag.all(i).then(void 0,function(){})}),Rg=qe,Ig=Le,Cg=Vt,_g=gi,Dg=rn,Lg=en,xg=Ou;Rg({target:"Promise",stat:!0,forced:xg},{all:function(e){var t=this,s=_g.f(t),r=s.resolve,a=s.reject,n=Dg(function(){var o=Cg(t.resolve),u=[],l=0,d=1;Lg(e,function(c){var h=l++,f=!1;d++,Ig(o,t,c).then(function(v){f||(f=!0,u[h]=v,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),s.promise}});var Og=qe,Mg=Gi.CONSTRUCTOR,Ho=vi;Ho&&Ho.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(i){return this.then(void 0,i)}});var Bg=qe,Ng=Le,Fg=Vt,Vg=gi,Ug=rn,Hg=en,jg=Ou;Bg({target:"Promise",stat:!0,forced:jg},{race:function(e){var t=this,s=Vg.f(t),r=s.reject,a=Ug(function(){var n=Fg(t.resolve);Hg(e,function(o){Ng(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Gg=qe,Yg=Le,qg=gi,zg=Gi.CONSTRUCTOR;Gg({target:"Promise",stat:!0,forced:zg},{reject:function(e){var t=qg.f(this);return Yg(t.reject,void 0,e),t.promise}});var Wg=ft,Qg=ht,Kg=gi,Mu=function(i,e){if(Wg(i),Qg(e)&&e.constructor===i)return e;var t=Kg.f(i),s=t.resolve;return s(e),t.promise},Jg=qe,Xg=Ft,Zg=Ic,eS=vi,tS=Gi.CONSTRUCTOR,iS=Mu,sS=Xg("Promise"),rS=!tS;Jg({target:"Promise",stat:!0,forced:Zg},{resolve:function(e){return iS(rS&&this===sS?eS:this,e)}});var aS=qe,_a=vi,nS=Fe,oS=Ft,lS=ve,uS=fu,jo=Mu,dS=_a&&_a.prototype,cS=!!_a&&nS(function(){dS.finally.call({then:function(){}},function(){})});aS({target:"Promise",proto:!0,real:!0,forced:cS},{finally:function(i){var e=uS(this,oS("Promise")),t=lS(i);return this.then(t?function(s){return jo(e,i()).then(function(){return s})}:i,t?function(s){return jo(e,i()).then(function(){throw s})}:i)}});var hS=Ft,un=hS,fS=un,pS=fS("Promise","finally"),mS=pS,vS=mS,gS=vS,SS=gS,dn=Fs(SS),ge;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ge||(ge={}));var Ye=(i,e=0,t=ge.OFFSET_P)=>{switch(t){case ge.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ge.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ge.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:j(t)}return i};const Go=(i,e)=>{var t;switch(e){case ge.OFFSET_P:return NaN;case ge.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ge.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:j(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ce{constructor(e){this.transitionStarted$=new D,this.transitionEnded$=new D,this.transitionUpdated$=new D,this.forceChanged$=new D,this.stateChangeStarted$=F(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=F(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||k(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const bS=i=>{switch(i){case y.MPEG:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return j(i)}};var V;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const yS=5,TS=5,ES=500,Yo=7e3;class $S{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ce(V.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==V.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:j(s)}break}case p.PLAYING:{switch(s){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:j(s)}break}case p.PAUSED:{switch(s){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:j(s)}break}default:j(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(bS(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 re;this.subscription.add(e),this.subscription.add(F(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(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 D;e.add(r.pipe(tt(ES)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(x(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===Y.Applying||Math.abs(o-a)>yS)&&r.next(o),a=o})),e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(x(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<TS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:j(n)}}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=F(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===V.READY&&this.videoState.setState(V.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case y.MPEG:{const d=s[e];R(d);const c=yd(Object.keys(d));R(c);const h=d[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=s[e];R(d),r=d.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=s[e];R(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=s[e];R(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=s[e];R(d),r=Ye(d.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:d,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return j(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:l}=this.params.meta;return k(u)&&(o.metadata.title=u),k(l)&&(o.metadata.subtitle=l),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Td(Yo).subscribe(()=>a(`timeout(${Yo})`)))});dn(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.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:_.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const cn=i=>{i.removeAttribute("src"),i.load()},wS=i=>{try{i.pause(),i.playbackRate=0,cn(i),i.remove()}catch(e){console.error(e)}};class AS{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 Da=window.WeakMap?new WeakMap:new AS,Ut=i=>{let e=i.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),i.appendChild(e)),Da.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ht=i=>{const e=Da.get(i);Da.delete(i),e?cn(i):wS(i)},ot=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),l=new re;return r&&l.add(r.subscribe(d=>{const c=i.getState();s(d,c)&&i.setState(d)},a)),s(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),u&&i.setState(d.to)},a)),l},qi=(i,e,t)=>ot(e,()=>i.loop,s=>{k(s)&&(i.loop=s)},{onError:t}),jt=(i,e,t,s)=>ot(e,()=>({muted:i.muted,volume:i.volume}),r=>{k(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),Si=(i,e,t,s)=>ot(e,()=>i.playbackRate,r=>{k(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),kS=i=>["__",i.language,i.label].join("|"),PS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class Et{constructor(){this.available$=new D,this.current$=new b(void 0),this.error$=new D,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(ot(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{k(a)&&this.setInternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ot(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{k(a)&&this.setExternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ot(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(ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(x(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(F(x(e,"addtrack"),x(e,"removetrack"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),fe((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(F(x(e,"change"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),w(s=>s&&this.htmlTextTrackToITextTrack(s).id),fe()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(x(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,l,d,c,h;const f=(l=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&l!==void 0?l:null;f&&f.length&&(this.applyCueSettings((c=(d=o.target)===null||d===void 0?void 0:d.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(x(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Et.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:kS(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:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.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(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(K(e)||!PS(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){R(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class hn{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 Bu=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qo=i=>{const e=Bu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},RS=i=>{const e=Bu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},IS=3;var CS=(i,e,t=IS)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const Gt=i=>{const e=$=>x(i,$).pipe(ks(void 0)),s=F(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map($=>x(i,$))).pipe(w($=>$.type==="ended"?i.readyState<2:i.readyState<3),fe()),r=F(x(i,"progress"),x(i,"timeupdate")).pipe(w(()=>CS(i.buffered,i.currentTime))),n=Fa().browser===yl.Safari?it({play:e("play").pipe(Pe()),playing:e("playing")}).pipe(ks(void 0)):e("playing"),o=x(i,"volumechange").pipe(w(()=>({muted:i.muted,volume:i.volume}))),u=x(i,"ratechange").pipe(w(()=>i.playbackRate)),l=x(i,"error").pipe(he(()=>!!(i.error||i.played.length)),w(()=>{var $;const A=i.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:($=i.error)!==null&&$!==void 0?$:void 0}})),d=x(i,"timeupdate").pipe(w(()=>i.currentTime)),c=new D,h=.3;let f;d.subscribe($=>{i.loop&&k(f)&&k($)&&f>=i.duration-h&&$<=h&&c.next(f),f=$});const v=x(i,"enterpictureinpicture"),m=x(i,"leavepictureinpicture"),g=new b(RS(i));v.subscribe(()=>g.next(!0)),m.subscribe(()=>g.next(!1));const S=new b(qo(i));return x(i,"fullscreenchange").pipe(w(()=>qo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(he(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:x(i,"durationchange").pipe(w(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Ks=i=>{switch(i){case"mobile":return _e.Q_144P;case"lowest":return _e.Q_240P;case"low":return _e.Q_360P;case"sd":case"medium":return _e.Q_480P;case"hd":case"high":return _e.Q_720P;case"fullhd":case"full":return _e.Q_1080P;case"quadhd":case"quad":return _e.Q_1440P;case"ultrahd":case"ultra":return _e.Q_2160P}},_S=qe,DS=Ys,LS=Ka,xS=Qa;_S({target:"Array",proto:!0},{at:function(e){var t=DS(this),s=LS(t),r=xS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var OS=un,MS=OS("Array","at"),BS=MS,NS=BS,FS=NS,VS=FS,nt=Fs(VS);let fn=!1,lt={};const US=i=>{fn=i},HS=()=>{lt={}},jS=i=>{i(lt)},hs=(i,e)=>{var t;fn&&(lt.meta=(t=lt.meta)!==null&&t!==void 0?t:{},lt.meta[i]=e)};class Xe{constructor(e){this.name=e}next(e){var t,s;if(!fn)return;lt.series=(t=lt.series)!==null&&t!==void 0?t:{};const r=(s=lt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),lt.series[this.name]=r}}var Lt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(Lt||(Lt={}));const GS=new Xe("best_bitrate"),YS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class qS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const zS='Assertion "ABR Tracks is empty array" failed',Js=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{var h,f,v,m,g;Ed(i,zS);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},$=E&&Ot(E),A=s.considerPlaybackRate&&k(o)?o:1,P=i.filter(N=>!Mt(N.quality)).sort((N,C)=>di(N.quality,C.quality)?-1:1),q=(f=nt(P,-1))===null||f===void 0?void 0:f.quality,z=(v=nt(P,0))===null||v===void 0?void 0:v.quality,J=K(r)||k(r.min)&&k(r.max)&&ys(r.max,r.min)||k(r.min)&&z&&di(r.min,z)||k(r.max)&&q&&ys(r.max,q),G=A*YS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),X={},B=P.filter(N=>($?ys(N.quality,$):!0)?(k(t)&&isFinite(t)&&k(N.bitrate)?t-a>=N.bitrate*G:!0)?s.lazyQualitySwitch&&k(s.minBufferToSwitchUp)&&u&&!Mt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&di(N.quality,u.quality)?(X[N.quality]=Lt.Buffer,!1):!!d&&da(N.quality,d)?(X[N.quality]=Lt.DroppedFramesLimit,!1):J||(K(r.max)||Ps(N.quality,r.max))&&(K(r.min)||da(N.quality,r.min))?!0:(X[N.quality]=Lt.FitsQualityLimits,!1):(X[N.quality]=Lt.FitsThroughput,!1):(X[N.quality]=Lt.FitsContainer,!1))[0];B&&B.bitrate&&GS.next(B.bitrate);const L=(m=B!=null?B:P[Math.ceil((P.length-1)/2)])!==null&&m!==void 0?m:i[0];L.quality!==((g=l==null?void 0:l.last)===null||g===void 0?void 0:g.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(N=>`{ id: ${N.id}, quality: ${N.quality}, bitrate: ${N.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -13,13 +13,13 @@ import{ValueSubject as b,Subject as D,Subscription as re,isNonNullable as P,Erro
|
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${$},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
20
|
+
playbackRateFactor: ${A},
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${G},
|
|
23
23
|
minBufferToSwitchUp: ${s.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${d},
|
|
25
25
|
limitsAreInvalid: ${J},
|
|
@@ -34,7 +34,7 @@ import{ValueSubject as b,Subject as D,Subscription as re,isNonNullable as P,Erro
|
|
|
34
34
|
[selected track] ${L==null?void 0:L.quality}
|
|
35
35
|
`});const ae=L&&l&&l.history[L.id]&&le()-l.history[L.id]<=s.trackCooldown&&(!l.last||L.id!==l.last.id);if(L!=null&&L.id&&l&&!ae&&l.recordSelection(L),ae&&(l!=null&&l.last)){const N=l.last;return l==null||l.recordSwitch(N),c({message:`
|
|
36
36
|
[last selected] ${N==null?void 0:N.quality}
|
|
37
|
-
`}),N}return l==null||l.recordSwitch(L),L};var st=i=>new URL(i).hostname;const zo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Gt=i=>ee(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!zo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return zo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return le()}function Nu(i){return we()-i}function Wo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function WS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function As(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,l=0,d,c,h=!1,f="arraybuffer",v=7e3,m=2e3,g=()=>{if(u)return;R(d);const B=Nu(d);let L;if(B<m){L=m-B,setTimeout(g,L);return}m*=2,m>v&&(m=v),n&&n.abort(),n=new r,j()};const S=B=>(a=B,te),E=B=>(c=B,te),w=()=>(f="json",te),$=()=>{if(!u){if(--l>=0){g(),s&&s();return}u=!0,c&&c(),t&&t()}},k=B=>(h=B,te),j=()=>{d=we(),n=new r,n.open("get",i);let B=0,L,ae=0;const N=()=>(R(d),Math.max(d,Math.max(L||0,ae||0)));if(a&&n.addEventListener("progress",C=>{const Z=we();a.updateChunk&&C.loaded>B&&(a.updateChunk(N(),C.loaded-B),B=C.loaded,L=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(u)return;R(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const Z=n.response.byteLength-B;Z&&a.updateChunk&&a.updateChunk(N(),Z)}n.responseType==="json"&&!Object.values(n.response).length?$():(c&&c(),e(n.response))}else $()}),n.addEventListener("error",()=>{$()}),h){const C=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=we(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),te},te={withBitrateReporting:S,withParallel:k,withJSONResponse:w,withRetryCount:B=>(l=B,te),withRetryInterval:(B,L)=>(P(B)&&(m=B),P(L)&&(v=L),te),withTimeout:B=>(o=B,te),withFinally:E,send:j,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return te}const QS=100,KS=2e3,JS=500;let XS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-JS;if(t-e>KS){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>QS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class ZS{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=As(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const fs=1e4,zr=3,eb=6e4,tb=10,ib=1,sb=500;class rb{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new XS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{WS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ZS(zr,fs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,l=null,d=!1;const c=()=>{const $=a&&(!d||d===this.rep);return $||t("Not running!"),$},h=($,k,j)=>{u&&u.abort(),u=As(this.urlResolver.resolve($,!1),k,j,()=>this._retryCallback()).withTimeout(fs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zr).withFinally(()=>{u=null}).send()},f=($,k,j)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),k,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=$=>{const k=s.playbackRate;s.playbackRate!==$&&(t(`Playback rate switch: ${k}=>${$}`),s.playbackRate=$)},m=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const j=we()-1e4;let Y=0;for(let q=0;q<this.bufferStates.length;q++){const X=this.bufferStates[q];$=Math.min($,X.buf),X.ts<j&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${$} drop=${Y} jitter=${this.sourceJitter}`);let J=$-ib;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?v(1.15):J>1?v(1.1):J>.3?v(1.05):v(1)}},S=$=>{let k;const j=()=>k&&k.start?k.start.length:0,Y=C=>k.start[C]/1e3,J=C=>k.dur[C]/1e3,q=C=>k.fragIndex+C,X=(C,Z)=>({chunkIdx:q(C),startTS:Y(C),dur:J(C),discontinuity:Z}),te=()=>{let C=0;if(k&&k.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=Z;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let Se=k.dur.length-1;for(;Se>=0&&(pe-=k.dur[Se],!(pe<=0));--Se);C=Math.min(Se,k.dur.length-1-ue),C=Math.max(C,0)}return X(C,!0)},B=C=>{const Z=j();if(!(Z<=0)){if(P(C)){for(let ue=0;ue<Z;ue++)if(Y(ue)>C)return X(ue)}return te()}},L=C=>{const Z=j(),ue=C?C.chunkIdx+1:0,pe=ue-k.fragIndex;if(!(Z<=0)){if(!C||pe<0||pe-Z>tb)return t(`Resync: offset=${pe} bChunks=${Z} chunk=`+JSON.stringify(C)),te();if(!(pe>=Z))return X(ue-k.fragIndex,!1)}},ae=(C,Z,ue)=>{l&&l.abort(),l=As(this.urlResolver.resolve(C,!0,this.lowLatency),Z,ue,()=>this._retryCallback()).withTimeout(fs).withRetryCount(zr).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(C,Z)=>{ae($,ue=>{if(!c())return;k=ue;const pe=!!k.lowLatency;pe!==this.lowLatency&&m(pe);let Se=0;for(let ze=0;ze<k.dur.length;++ze)Se+=k.dur[ze];Se>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,C(B(Z))},()=>this._handleNetworkError())},nextChunk:L}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:$=>{const{videoElement:k,logger:j}=this.params;let Y=S(e.jidxUrl),J,q,X,te,B=0,L,ae,N;const C=()=>{L&&(clearTimeout(L),L=void 0);const Q=Math.max(sb,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+Q,ke=we(),Ce=Math.min(1e4,Ee-ke);B=ke;const qt=()=>{l||c()&&Y.seek(()=>{c()&&(B=we(),Z(),C())})};Ce>0?L=window.setTimeout(()=>{this.paused?C():qt()},Ce):qt()},Z=()=>{let Q;for(;Q=Y.nextChunk(te);)te=Q,Si(Q);const Ee=Y.nextChunk(X);if(Ee){if(X&&Ee.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?C():(E(),this._initPlayerWith(e));return}ze(Ee)}else C()},ue=(Q,Ee)=>{if(!c()||!this.sourceBuffer)return;let ke,Ce,qt;const bi=at=>{window.setTimeout(()=>{c()&&ue(Q,Ee)},at)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),bi(100);else{const at=we(),xe=k.currentTime;!this.paused&&k.buffered.length>1&&ae===xe&&at-N>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),ae!==xe&&(ae=xe,N=at);const zt=this._getBufferSizeSec();if(zt>30)j(`Buffered ${zt} seconds; delaying appendBuffer`),bi(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:at,buf:zt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(yi){if(yi.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),qt=this.sourceBuffer.buffered.length,qt!==0&&(ke=this.sourceBuffer.buffered.start(0),Ce=xe,Ce-ke>4&&this.sourceBuffer.remove(ke,Ce-3)),bi(1e3);else throw yi}}},pe=()=>{q&&J&&(j([`Appending chunk, sz=${q.byteLength}:`,JSON.stringify(X)]),ue(q,function(){q=null,Z()}))},Se=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),ze=Q=>{c()&&f(Se(Q),(Ee,ke)=>{if(c()){if(ke/=1e3,q=Ee,X=Q,n=Q.startTS,ke){const Ce=Math.min(10,Q.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ce:Ce}pe()}},()=>this._handleNetworkError())},Si=Q=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(Q),!1)))},Yt=Q=>{c()&&(e.cachedHeader=Q,ue(Q,()=>{J=!0,pe()}))};a=!0,Y.seek(Q=>{if(c()){if(B=we(),!Q){C();return}te=Q,!K($)||Q.startTS>$?ze(Q):(X=Q,Z())}},$),e.cachedHeader?Yt(e.cachedHeader):h(e.headerUrl,Yt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},d}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),P(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=we();if(this.chunkRateEstimator.addInterval(h,v,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:g}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nu(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&l(),f},notifySwitch:c=>{const h=we();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=As(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(fs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Gt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},eb))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Fu{constructor(){this.onDroopedVideoFramesLimit$=new D,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new D,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Ot(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&ui(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(x(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Rs(this.droppedFramesChecker.checkTime).pipe(he(()=>this.playing),he(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(tt(this.droppedFramesChecker.checkTime)),s=F(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>ys(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var H;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const ab=[H.PAUSED,H.PLAYING,H.READY],nb=[H.PAUSED,H.PLAYING,H.READY];class ob{constructor(e){this.subscription=new re,this.videoState=new ce(H.STOPPED),this.representations$=new b([]),this.textTracksManager=new Et,this.droppedFramesManager=new Fu,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new hn,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const l=r.isBuffering;this.params.output.isBuffering$.next(l);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const l=r.manifest,d=[];for(const c of l){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Ks(c.name))!==null&&n!==void 0?n:Bi(c.video),v=c.bitrate/1e3,m=Object.assign({},c.video);if(!f)continue;const g={id:h,quality:f,bitrate:v,size:m};d.push({track:g,representation:c})}this.representations$.next(d),this.params.output.availableVideoTracks$.next(d.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const l=r.quality,d=(u=this.representations$.getValue().find(({representation:c})=>c===l))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(l.headerUrl,this.params.source.url).hostname),P(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:l,duration:d}=r;this.params.dependencies.throughputEstimator.addRawSpeed(l,d);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(a)return;const l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(nb.includes(r)&&(l||d)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===z.Requested&&ab.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Ye(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(n===p.PAUSED)this.videoState.setState(H.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)})}return;case H.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Ye(this.params.source.url,c))}return;default:return G(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:r})};F(this.videoState.stateChangeStarted$.pipe(A(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Vt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(st(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=jt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(A(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===H.READY&&this.videoState.setState(H.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fe(),A(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(it({zeroTime:this.zeroTime$.pipe(he(P)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(qi(this.video,this.params.desiredState.isLooped,t)).add(Ht(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(gi(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&$d(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case H.MANIFEST_READY:case H.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return G(r.to)}},t)).add(F(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(tt(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}createLiveDashPlayer(){const e=new rb({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),l=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&P(u)?u:Js(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=d==null?void 0:d.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(h||c!==f)&&this.setVideoTrack(d),v&&this.setAutoQuality(l),h||v||c!==f){const m=(n=o.find(({track:g})=>g.id===c))===null||n===void 0?void 0:n.representation;R(m,"Representations missing"),this.dash.startPlay(m,l)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;R(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===H.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var ye;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ye||(ye={}));var Je;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(Je||(Je={}));var xs;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(xs||(xs={}));var Be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Be||(Be={}));var U;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(U||(U={}));var hi;(function(i){i.MP4="mp4",i.WEBM="webm"})(hi||(hi={}));var Os;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Os||(Os={}));var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(oe||(oe={}));var oi=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const lb=300,ub=(i,e=lb)=>new Ns(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(wd(n=>{const o=n[0];if(!o)return;let u,l;o.contentBoxSize&&o.contentBoxSize[0]?(l=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,l=o.contentRect.height),P(u)&&P(l)&&t.next({width:u,height:l})},e));return a.observe(i),()=>a.disconnect()});class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Vu extends Qo{constructor(){super(),this.listeners||Qo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Uu=class{constructor(){Object.defineProperty(this,"signal",{value:new Vu,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Uu.prototype[Symbol.toStringTag]="AbortController",Vu.prototype[Symbol.toStringTag]="AbortSignal");function Hu(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function db(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Hu({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);const h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,l)=>{const d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{d.addEventListener("abort",()=>v(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}const Xs=Hu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ju=Xs?db({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Oi=Xs?ju.fetch:window.fetch;Xs?ju.Request:window.Request;const ci=Xs?Uu:window.AbortController;var La=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const cb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},hb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=hb?cb:window.requestIdleCallback;var Wr,Qr;const fb=16;let Gu=!1;try{Gu=Fa().browser===yl.Safari&&parseInt((Qr=(Wr=navigator.userAgent.match(/Version\/(\d+)/))===null||Wr===void 0?void 0:Wr[1])!==null&&Qr!==void 0?Qr:"",10)<=fb}catch(i){console.error(i)}class pb{constructor(e){this.bufferFull$=new D,this.error$=new D,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:_.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ee(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ee(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ee(this,void 0,void 0,function*(){return new Promise(t=>{let s;Gu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:_.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:G(t)}}}var Jo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ue{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 Yu extends Ue{}class mb extends Ue{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class vb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class gb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Sb extends Ue{constructor(e){super(e),this.data=this.content}}class pt extends Ue{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class bb extends pt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class yb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Tb extends Ue{parseChildrenBoxes(){return $t(this.content)}}var xt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(xt||(xt={}));class Eb extends pt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=xt.MONOSCOPIC;break;case 1:this.stereoMode=xt.TOP_BOTTOM;break;case 2:this.stereoMode=xt.LEFT_RIGHT;break;case 3:this.stereoMode=xt.STEREO_CUSTOM;break;case 4:this.stereoMode=xt.RIGHT_LEFT;break}this.cursor+=1}}class $b extends pt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class wb extends pt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ab extends Ue{parseChildrenBoxes(){return $t(this.content)}}class kb extends pt{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 Pb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Rb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Ib extends pt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Cb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class _b extends pt{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 Db extends pt{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 Lb extends pt{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 xb={ftyp:mb,moov:vb,moof:gb,mdat:Sb,sidx:bb,trak:yb,mdia:Ab,mfhd:Ib,tkhd:kb,traf:Cb,tfhd:_b,tfdt:Db,trun:Lb,minf:Pb,sv3d:Tb,st3d:Eb,prhd:$b,proj:Rb,equi:wb,unknown:Yu};class Ob{createBox(e,t){const s=xb[e];return s?new s(t):new Yu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Zs.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Zs=new Ob;function Ri(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(n=>n.charCodeAt(0));let r=i.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===s[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+o>i.buffer.byteLength?null:Zs.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function xa(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=Ri(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function $t(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Zs.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Mb=new TextDecoder("ascii"),Bb=i=>Mb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Nb=i=>{const e=Zs.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:U.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Fb=i=>{const e=xa(i,"mdat"),t=xa(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],a=s.source.byteOffset,o=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,a,o)},Vb=(i,e)=>{const t=xa(i,"traf"),s=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,l)=>u+l,0):n=s.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Ub=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ri(i,"sv3d")){e.is3dVideo=!0;const s=Ri(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=Ri(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Ri(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Hb={validateData:Bb,parseInit:Ub,getIndexRange:()=>{},parseSegments:Nb,parseFeedableSegmentChunk:Fb,getSegmentEndTime:Vb};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var I;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(I||(I={}));const Xo={[T.EBML]:{type:I.Master},[T.EBMLVersion]:{type:I.UnsignedInteger},[T.EBMLReadVersion]:{type:I.UnsignedInteger},[T.EBMLMaxIDLength]:{type:I.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[T.DocType]:{type:I.String},[T.DocTypeVersion]:{type:I.UnsignedInteger},[T.DocTypeReadVersion]:{type:I.UnsignedInteger},[T.Void]:{type:I.Binary},[T.Segment]:{type:I.Master},[T.SeekHead]:{type:I.Master},[T.Seek]:{type:I.Master},[T.SeekID]:{type:I.Binary},[T.SeekPosition]:{type:I.UnsignedInteger},[T.Info]:{type:I.Master},[T.TimestampScale]:{type:I.UnsignedInteger},[T.Duration]:{type:I.Float},[T.Tracks]:{type:I.Master},[T.TrackEntry]:{type:I.Master},[T.Video]:{type:I.Master},[T.Projection]:{type:I.Master},[T.ProjectionType]:{type:I.UnsignedInteger},[T.ProjectionPrivate]:{type:I.Master},[T.Chapters]:{type:I.Master},[T.Cluster]:{type:I.Master},[T.Timestamp]:{type:I.UnsignedInteger},[T.SilentTracks]:{type:I.Master},[T.SilentTrackNumber]:{type:I.UnsignedInteger},[T.Position]:{type:I.UnsignedInteger},[T.PrevSize]:{type:I.UnsignedInteger},[T.SimpleBlock]:{type:I.Binary},[T.BlockGroup]:{type:I.Master},[T.EncryptedBlock]:{type:I.Binary},[T.Attachments]:{type:I.Master},[T.Tags]:{type:I.Master},[T.Cues]:{type:I.Master},[T.CuePoint]:{type:I.Master},[T.CueTime]:{type:I.UnsignedInteger},[T.CueTrackPositions]:{type:I.Master},[T.CueTrack]:{type:I.UnsignedInteger},[T.CueClusterPosition]:{type:I.UnsignedInteger},[T.CueRelativePosition]:{type:I.UnsignedInteger},[T.CueDuration]:{type:I.UnsignedInteger},[T.CueBlockNumber]:{type:I.UnsignedInteger},[T.CueCodecState]:{type:I.UnsignedInteger},[T.CueReference]:{type:I.Master},[T.CueRefTime]:{type:I.UnsignedInteger}},qu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Ms(i,t),r=s in Xo,a=r?Xo[s].type:I.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,d=Ms(u),c=l*Math.pow(2,(o-1)*8)+d,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ms=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(i,e)=>{switch(e){case I.SignedInteger:return i.getInt8(0);case I.UnsignedInteger:return Ms(i);case I.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(i);case I.UTF8:return new TextDecoder("utf-8").decode(i);case I.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case I.Master:return i;case I.Binary:return i;default:G(e)}},fi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=qu(s);if(!e(r))return;r.type===I.Master&&fi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},jb=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=qu(i);return fi(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=Ze(o,n):a===T.DocType?t=Ze(o,n):a===T.DocTypeReadVersion&&(s=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},zu=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Gb=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],Yb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,l,d=!1;const c=0;return fi(i,({tag:h,type:f,value:v,valueSize:m})=>{if(h===T.SeekID){const g=Ze(v,f);l=Ms(g)}else h!==T.SeekPosition&&(l=void 0);return h===T.Segment?(e=v.byteOffset,t=v.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=Ze(v,f):h===T.Duration?r=Ze(v,f):h===T.SeekPosition&&l===T.Cues?u=Ze(v,f):h===T.Tracks?fi(v,({tag:g,type:S,value:E})=>g===T.ProjectionType?(d=Ze(E,S)===1,!1):!0):a&&n&&zu.includes(h)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:Os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},qb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zb=(i,e)=>{let t=!1,s=!1;const r=o=>P(o.time)&&P(o.position),a=[];let n;return fi(i,({tag:o,type:u,value:l})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=Ze(l,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=Ze(l,u));break;default:t&&zu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:l,position:d}=o,c=a[u+1];return{status:U.NONE,time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Wb=i=>{let e=0,t=!1;try{fi(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Gb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Qb={validateData:jb,parseInit:Yb,getIndexRange:qb,parseSegments:zb,parseFeedableSegmentChunk:Wb};var Kb=ht,Jb=Ni,Xb=Ae,Zb=Xb("match"),ey=function(i){var e;return Kb(i)&&((e=i[Zb])!==void 0?!!e:Jb(i)=="RegExp")},ty=ji,iy=String,sy=function(i){if(ty(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return iy(i)},ry=ft,ay=function(){var i=ry(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},ny=Le,oy=rt,ly=Us,uy=ay,Zo=RegExp.prototype,dy=function(i){var e=i.flags;return e===void 0&&!("flags"in Zo)&&!oy(i,"flags")&&ly(Zo,i)?ny(uy,i):e},pn=Ve,cy=Ys,hy=Math.floor,Kr=pn("".charAt),fy=pn("".replace),Jr=pn("".slice),py=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,my=/\$([$&'`]|\d{1,2})/g,vy=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=my;return r!==void 0&&(r=cy(r),u=py),fy(a,u,function(l,d){var c;switch(Kr(d,0)){case"$":return"$";case"&":return i;case"`":return Jr(e,0,t);case"'":return Jr(e,n);case"<":c=r[Jr(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var f=hy(h/10);return f===0?l:f<=o?s[f-1]===void 0?Kr(d,1):s[f-1]+Kr(d,1):l}c=s[h-1]}return c===void 0?"":c})},gy=qe,Sy=Le,mn=Ve,el=Va,by=ve,yy=Fi,Ty=ey,ti=sy,Ey=Gs,$y=dy,wy=vy,Ay=Ae,ky=Ay("replace"),Py=TypeError,Wu=mn("".indexOf),Ry=mn("".replace),tl=mn("".slice),Iy=Math.max,il=function(i,e,t){return t>i.length?-1:e===""?t:Wu(i,e,t)};gy({target:"String",proto:!0},{replaceAll:function(e,t){var s=el(this),r,a,n,o,u,l,d,c,h,f=0,v=0,m="";if(!yy(e)){if(r=Ty(e),r&&(a=ti(el($y(e))),!~Wu(a,"g")))throw Py("`.replaceAll` does not allow non-global regexes");if(n=Ey(e,ky),n)return Sy(n,e,s,t);if(r)return Ry(ti(s),e,t)}for(o=ti(s),u=ti(e),l=by(t),l||(t=ti(t)),d=u.length,c=Iy(1,d),f=il(o,u,0);f!==-1;)h=l?ti(t(u,f,o)):wy(u,o,f,[],void 0,t),m+=tl(o,v,f)+h,v=f+d,f=il(o,u,f+c);return v<o.length&&(m+=tl(o,v)),m}});var Cy=un,_y=Cy("String","replaceAll"),Dy=_y,Ly=Dy,xy=Ly,Oy=xy,sl=Fs(Oy);const My=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},rl=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},si=(i,e)=>{let t=i;t=sl(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=sl(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},By=(i,e)=>{var t,s,r,a,n,o,u,l,d,c,h,f,v,m,g,S,E,w,$,k,j,Y,J,q,X,te,B,L,ae,N,C,Z,ue,pe,Se,ze,Si,Yt,Q,Ee,ke,Ce;const bi=new DOMParser().parseFromString(i,"application/xml"),at={video:[],audio:[],text:[]},xe=bi.children[0],zt=xe.getElementsByTagName("Period")[0],yi=(r=(s=(t=xe.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",td=zt.children,id=xe.getAttribute("type")==="dynamic",Sn=xe.getAttribute("availabilityStartTime"),sd=Sn?new Date(Sn).getTime():void 0;let wt;const bn=xe.getAttribute("mediaPresentationDuration"),yn=zt.getAttribute("duration"),er=xe.getElementsByTagName("vk:Attrs")[0],Tn=er==null?void 0:er.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(bn)wt=rl(bn);else if(yn){const He=rl(yn);P(He)&&(wt=He)}else Tn&&(wt=parseInt(Tn,10));let rd=0;const tr=(n=(a=xe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],ad=tr.includes(xs.WEBM_AS_IN_FFMPEG)||tr.includes(xs.WEBM_AS_IN_SPEC)?hi.WEBM:hi.MP4;for(const He of td){const zi=He.getAttribute("mimeType"),nd=He.getAttribute("codecs"),En=(o=He.getAttribute("contentType"))!==null&&o!==void 0?o:zi==null?void 0:zi.split("/")[0],od=(l=(u=He.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&l!==void 0?l:[],$n=He.querySelectorAll("Representation"),ld=He.querySelector("SegmentTemplate");if(En===ye.TEXT){for(const me of $n){const mt=me.getAttribute("id")||"",Wi=He.getAttribute("lang"),Wt=(h=(c=(d=me.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",ir=new URL(Wt||yi,e).toString(),sr=mt.includes("_auto");at[ye.TEXT].push({id:mt,lang:Wi,isAuto:sr,kind:ye.TEXT,url:ir})}continue}for(const me of $n){const mt=(f=me.getAttribute("mimeType"))!==null&&f!==void 0?f:zi,Wi=(m=(v=me.getAttribute("codecs"))!==null&&v!==void 0?v:nd)!==null&&m!==void 0?m:"",Wt=(S=(g=me.getAttribute("contentType"))!==null&&g!==void 0?g:mt==null?void 0:mt.split("/")[0])!==null&&S!==void 0?S:En,ir=(w=(E=He.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&w!==void 0?w:[],sr=parseInt(($=me.getAttribute("width"))!==null&&$!==void 0?$:"",10),wn=parseInt((k=me.getAttribute("height"))!==null&&k!==void 0?k:"",10),An=parseInt((j=me.getAttribute("bandwidth"))!==null&&j!==void 0?j:"",10)/1e3,kn=(Y=me.getAttribute("frameRate"))!==null&&Y!==void 0?Y:"",ud=(J=me.getAttribute("quality"))!==null&&J!==void 0?J:void 0,dd=kn?My(kn):void 0,cd=(q=me.getAttribute("id"))!==null&&q!==void 0?q:(rd++).toString(10),hd=Wt==="video"?`${wn}p`:Wt==="audio"?`${An}Kbps`:Wi,fd=`${cd}@${hd}`,pd=(B=(te=(X=me.querySelector("BaseURL"))===null||X===void 0?void 0:X.textContent)===null||te===void 0?void 0:te.trim())!==null&&B!==void 0?B:"",Pn=new URL(pd||yi,e).toString(),md=[...tr,...od,...ir];let rr;const vd=me.querySelector("SegmentBase"),At=(L=me.querySelector("SegmentTemplate"))!==null&&L!==void 0?L:ld;if(vd){const kt=(N=(ae=me.querySelector("SegmentBase Initialization"))===null||ae===void 0?void 0:ae.getAttribute("range"))!==null&&N!==void 0?N:"",[Pt,nr]=kt.split("-").map(Qt=>parseInt(Qt,10)),vt={from:Pt,to:nr},Ti=(C=me.querySelector("SegmentBase"))===null||C===void 0?void 0:C.getAttribute("indexRange"),[or,Qi]=Ti?Ti.split("-").map(Qt=>parseInt(Qt,10)):[],Ei=Ti?{from:or,to:Qi}:void 0;rr={type:Be.BYTE_RANGE,url:Pn,initRange:vt,indexRange:Ei}}else if(At){const kt={representationId:(Z=me.getAttribute("id"))!==null&&Z!==void 0?Z:void 0,bandwidth:(ue=me.getAttribute("bandwidth"))!==null&&ue!==void 0?ue:void 0},Pt=parseInt((pe=At.getAttribute("timescale"))!==null&&pe!==void 0?pe:"",10),nr=(Se=At.getAttribute("initialization"))!==null&&Se!==void 0?Se:"",vt=At.getAttribute("media"),Ti=(Si=parseInt((ze=At.getAttribute("startNumber"))!==null&&ze!==void 0?ze:"",10))!==null&&Si!==void 0?Si:1,or=si(nr,kt);if(!vt)throw new ReferenceError("No media attribute in SegmentTemplate");const Qi=(Yt=At.querySelectorAll("SegmentTimeline S"))!==null&&Yt!==void 0?Yt:[],Ei=[];let Qt=0,lr="",ur=0;if(Qi.length){let Ki=Ti,je=0;for(const Kt of Qi){const We=parseInt((Q=Kt.getAttribute("d"))!==null&&Q!==void 0?Q:"",10),Rt=parseInt((Ee=Kt.getAttribute("r"))!==null&&Ee!==void 0?Ee:"",10)||0,Ji=parseInt((ke=Kt.getAttribute("t"))!==null&&ke!==void 0?ke:"",10);je=Number.isFinite(Ji)?Ji:je;const dr=We/Pt*1e3,cr=je/Pt*1e3;for(let Xi=0;Xi<Rt+1;Xi++){const Sd=si(vt,Object.assign(Object.assign({},kt),{segmentNumber:Ki.toString(10),segmentTime:(je+Xi*We).toString(10)})),Rn=(cr!=null?cr:0)+Xi*dr,bd=Rn+dr;Ki++,Ei.push({time:{from:Rn,to:bd},url:Sd})}je+=(Rt+1)*We,Qt+=(Rt+1)*dr}ur=je/Pt*1e3,lr=si(vt,Object.assign(Object.assign({},kt),{segmentNumber:Ki.toString(10),segmentTime:je.toString(10)}))}else if(P(wt)){const je=parseInt((Ce=At.getAttribute("duration"))!==null&&Ce!==void 0?Ce:"",10)/Pt*1e3,Kt=Math.ceil(wt/je);let We=0;for(let Rt=1;Rt<Kt;Rt++){const Ji=si(vt,Object.assign(Object.assign({},kt),{segmentNumber:Rt.toString(10),segmentTime:We.toString(10)}));Ei.push({time:{from:We,to:We+je},url:Ji}),We+=je}ur=We,lr=si(vt,Object.assign(Object.assign({},kt),{segmentNumber:Kt.toString(10),segmentTime:We.toString(10)}))}const gd={time:{from:ur,to:1/0},url:lr};rr={type:Be.TEMPLATE,baseUrl:Pn,segmentTemplateUrl:vt,initUrl:or,totalSegmentsDurationMs:Qt,segments:Ei,nextSegmentBeyondManifest:gd,timescale:Pt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Wt||!mt)continue;const ar={video:ye.VIDEO,audio:ye.AUDIO,text:ye.TEXT}[Wt];ar&&at[ar].push({id:fd,kind:ar,segmentReference:rr,profiles:md,duration:wt,bitrate:An,mime:mt,codecs:Wi,width:sr,height:wn,fps:dd,quality:ud})}}return{dynamic:id,liveAvailabilityStartTime:sd,duration:wt,container:ad,representations:at}},Ny=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ks(a):void 0)!==null&&n!==void 0?n:Bi({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Fy=({id:i,bitrate:e})=>({id:i,bitrate:e}),Vy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=nt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:nt(i,-1)},Uy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),al=i=>"size"in i,ii=i=>i.type===Be.TEMPLATE,Oa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class nl{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:d}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.playingRepresentationInit$=new b(void 0),this.error$=new D,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ci,this.destroyAbortController=new ci,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){const h=this.representations.get(c);R(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new pb(this.sourceBuffer),this.subscription.add(x(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(x(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),v=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(R(f,"No init buffer for starting representation"),R(v,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield M(void 0);this.searchGaps(v,h),yield yield M(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);R(h,`No such representation ${c}`);let f=this.segments.get(c),v=this.initData.get(c);if(K(v)||K(f)?yield yield M(this.loadInit(h,"high",!1)):v instanceof Promise&&(yield yield M(v)),f=this.segments.get(c),R(f,"No segments for starting representation"),v=this.initData.get(c),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();P(m)&&(this.isLive||(f.forEach(g=>g.status=U.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,function(c){var h;return Ie(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield M(void 0);for(const E of this.representations.keys()){const w=c.find(j=>j.id===E);w&&this.representations.set(E,w);const $=this.representations.get(E);if(!$||!ii($.segmentReference))return yield M(void 0);const k=this.getActualLiveStartingSegments($.segmentReference);this.segments.set($.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,v=this.representations.get(f);R(v);const m=this.segments.get(f);R(m,"No segments for starting representation");const g=this.initData.get(f);if(R(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return yield M(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield M(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield M(this.sourceBufferTaskQueue.append(g,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(d!=null&&d.dynamic),this.container=s,s){case hi.MP4:this.containerParser=Hb;break;case hi.WEBM:this.containerParser=Qb;break;default:G(s)}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 ci,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(R(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(l=>e>=l.time.from&&e<l.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=oi(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const l=oi(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{const d=nt(o,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===U.FED&&!o.length&&oi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=nt(s,-1);u&&u.status===U.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;P(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=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<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,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 s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!ii(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:U.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],l=(a=(r=nt(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,d=o==null?void 0:o.findIndex(c=>Math.floor(l)>=Math.floor(c.time.from)&&Math.floor(l)<=Math.floor(c.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(d+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!ii(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=si(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||o.push({status:U.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;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,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const m=h<=s&&f>=s,g=h>s||m||v===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===U.NONE||c===U.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!La(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==Be.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===U.NONE||h.status===U.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ee(this,void 0,void 0,function*(){t.segmentReference.type===Be.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return ee(this,void 0,void 0,function*(){e.status=U.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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Re(o,function(){return Ie(this,arguments,function*(){const d=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const c=new DataView(d);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=U.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){if(!Oa(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,s="auto"){return ee(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=U.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 Re(n,function(){return Ie(this,arguments,function*(){const u=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){if(!Oa(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(ii(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:nt(e,0).byte.from,to:nt(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(u,l)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ii(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:l,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&P(r)&&(s=oi((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:_.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){return ee(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=s,o.loadedBytes>o.feedingBytes){const l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(l);d!=null&&d.byteLength&&(u.status=U.PARTIALLY_FED,o.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,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,l=e.byteLength;for(const d of this.activeSegments){const{segment:c}=d,h=u===Be.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:l;if(d.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,g=h?c.byte.to-s:e.byteLength,S=m<r,E=g<=r;if(c.status===U.DOWNLOADING&&S&&E){c.status=U.DOWNLOADED;const w=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(w,a).then($=>$&&!a.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(d.loadedBytes=Math.min(f,r-m),d.loadedBytes>d.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+m+d.feedingBytes,d.loadedBytes-d.feedingBytes),$=d.loadedBytes===f?w:this.containerParser.parseFeedableSegmentChunk(w);$!=null&&$.byteLength&&(c.status=U.PARTIALLY_FED,d.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(k=>{if(a.aborted)n();else if(k)d.fedBytes+=$.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=U.FED,al(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===U.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=U.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===U.PARTIALLY_FED||e.status===U.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=U.NONE),e.status=U.PARTIALLY_EJECTED):e.status=U.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ko(()=>dn(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ee(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Re(this.destroyAbortController.signal,function(){return Ie(this,arguments,function*(){const o=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>ee(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&ii(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),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ee(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=l=>{var d;a=Math.min(a,l.time.from),n=Math.max(n,l.time.to);const c=al(l)?(d=l.size)!==null&&d!==void 0?d:0:l.byte.to-l.byte.from;r+=c};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===U.FED&&u(d)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const l of this.segments.values())for(const d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;d.status===U.FED&&u(d)}}if(o=isFinite(a)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){const d=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===U.NONE&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(c)){a=d,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const c of d)c.time.from>e+l&&c.status===U.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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==U.FED&&a!==U.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);u||(l.length===1?r.status=U.PARTIALLY_EJECTED:r.status=U.NONE)}}}var Ma=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Hy=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ca.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},li;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(li||(li={}));class jy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new ci,this.subscription=new re,this.fetchManifest=Re(this.abortAllController.signal,function(r){return Ie(this,arguments,function*(){let a=r;this.requestQuic&&(a=Ma(a));const n=yield yield M(Oi(a,{signal:this.abortAllController.signal}).catch(wi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Re(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?li.HEADER:li.PARAM,range:n,onProgress:o,priority:u="auto",signal:l,measureThroughput:d=!0,isLowLatency:c=!1}={}){var h,f;return Ie(this,arguments,function*(){let v=r;const m=new Headers;if(n)switch(a){case li.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case li.PARAM:{const L=new URL(v,location.href);L.searchParams.append("bytes",`${n.from}-${n.to}`),v=L.toString();break}default:G(a)}this.requestQuic&&(v=Ma(v));let g=this.abortAllController.signal,S;if(l){const L=new ci;if(S=F(x(this.abortAllController.signal,"abort"),x(l,"abort")).subscribe(()=>{try{L.abort()}catch(ae){wi(ae)}}),this.abortAllController.signal.aborted||l.aborted)try{L.abort()}catch(ae){wi(ae)}g=L.signal}const E=le(),w=yield yield M(Oi(v,{priority:u,headers:m,signal:g}).catch(wi)),$=le();if(!w)return S==null||S.unsubscribe(),yield M(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt($-E),!w.ok||!w.body)return S==null||S.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${w.status}: ${w.statusText}`)));if(this.onHeadersReceived(w.headers),!o&&!d)return S==null||S.unsubscribe(),yield M(w.arrayBuffer());const[k,j]=w.body.tee(),Y=k.getReader();d&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(j,c));let J=0,q=new Uint8Array(0),X=!1;const te=L=>{S==null||S.unsubscribe(),X=!0,wi(L)},B=Re(g,function({done:L,value:ae}){return Ie(this,arguments,function*(){if(J===0&&this.lastRequestFirstBytes$.next(le()-E),g.aborted)return S==null||S.unsubscribe(),yield M(void 0);if(!L&&ae){const N=new Uint8Array(q.length+ae.length);N.set(q),N.set(ae,q.length),q=N,J+=ae.byteLength,o==null||o(new DataView(q.buffer),J),yield yield M(Y==null?void 0:Y.read().then(B,te))}})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(B,te)),S==null||S.unsubscribe(),yield M(X?null:q.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,function(r,a,n){var o;return Ie(this,arguments,function*(){if(r.type!==Be.BYTE_RANGE)return yield M(null);const{from:u,to:l}=r.initRange;let d=u,c=l,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=l+1===f,h&&(d=Math.min(f,u),c=Math.max(v,l))),d=Math.min(d,0);const m=yield yield M(this.fetch(r.url,{range:{from:d,to:c},priority:n,measureThroughput:!1}));if(!m)return yield M(null);const g=new DataView(m,u-d,l-d+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let w;if(h)w=new DataView(m,E.from-d,E.to-E.from+1);else{const k=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!k)return yield M(null);w=new DataView(k)}const $=a.parseSegments(w,S,E);return yield M({init:S,dataView:new DataView(m),segments:$})})}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,function(r,a){return Ie(this,arguments,function*(){if(r.type!==Be.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(l=>Object.assign(Object.assign({},l),{status:U.NONE,size:void 0}));return yield M({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Hy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ee(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:G(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const wi=i=>{if(!Oa(i))throw i},Ba=1e3,Bs=(i,e,t)=>t*e+(1-t)*i,Qu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Gy=(i,e,t,s)=>{let r=0,a=t;const n=Qu(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class vn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new b(e.initial),this.debounced$=new b(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Xe(`raw_${s}`),this.smoothedSeries$=new Xe(`smoothed_${s}`),this.reportedSeries$=new Xe(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(K(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Yy extends vn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Bs(this.slow,e,this.params.emaAlphaSlow),this.fast=Bs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class qy extends vn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Bs(this.emaSmoothed,e,this.params.emaAlpha);const s=Gy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class zy extends vn{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?Bs(this.smoothed,e,this.params.emaAlpha):e}}class Na{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Yy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new qy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new zy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const Wy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Ct=()=>window.ManagedMediaSource||window.MediaSource,Ku=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Qy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Ky=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,ol=["timeupdate","progress","play","seeked","stalled","waiting"];var Me;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Me||(Me={}));let Jy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new ce(Me.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new D,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.isLive$=new b(!1),this.liveDuration$=new b(0),this.liveAvailabilityStartTime$=new b(void 0),this.bufferLength$=new b(0),this.liveLoadBufferLength$=new b(0),this.livePositionFromPlayer$=new b(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new D,this.gapWatchdogStarted=!1,this.destroyController=new ci,this.initManifest=Re(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){this.element=t,this.manifestUrlString=Ye(s,r,ge.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Me.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Me.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,function(){var t;return Ie(this,arguments,function*(){const s=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(null);let r;try{r=By(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var l,d,c,h;return!!(!((d=(l=this.element)===null||l===void 0?void 0:l.canPlayType)===null||d===void 0)&&d.call(l,o)&&(!((h=(c=Ct())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===ye.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 M(Object.assign(Object.assign({},r),{representations:Ds(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){R(this.manifest),R(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Me.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(x(m,"error").pipe(he(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:_.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?Ky():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Ku())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={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 nl(ye.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],P(s)&&(this.audioBufferManager=new nl(ye.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),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(Rs(Ba).subscribe(m=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=Go(this.manifestUrlString,ge.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ye(this.manifestUrlString,S+Ba,ge.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(F(...ol.map(m=>x(this.element,m))).pipe(A(m=>this.element?oi(this.element.buffered,this.element.currentTime*1e3):0),fe(),he(m=>!!m),Di(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(he(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,w=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,$=g-S;let k=1+Math.sign($)*w;Math.abs($)<E?k=1:Math.abs($)>E*2&&(k=1+Math.sign($)*w*2),Wy(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let w=0;if(g){const $=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;w=Math.min(...this.bufferManagers.map(j=>{var Y,J;return(J=(Y=j.getLiveSegmentsToLoadState(this.manifest))===null||Y===void 0?void 0:Y.to)!==null&&J!==void 0?J:0}))-$}w&&this.liveLoadBufferLength$.getValue()!==w&&this.liveLoadBufferLength$.next(w)}));let m=0;this.representationSubscription.add(it({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:g,bufferLength:S})=>ee(this,void 0,void 0,function*(){if(R(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,w=Go(this.manifestUrlString,ge.DASH_CMAF_OFFSET_P),$=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min($,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),j=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,Y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,J=this.isActiveLowLatency?S:g;let q=Je.None;if(this.isActiveLowLatency?q=Je.ActiveLowLatency:J<k+Y&&J>=k?q=Je.LiveWithTargetOffset:w!==0&&J<k&&(q=Je.LiveForwardBuffering),isFinite(g)&&(m=g>m?g:m),q===Je.LiveForwardBuffering||q===Je.LiveWithTargetOffset){const X=m-(k+j),te=this.normolizeLiveOffset(Math.trunc(w+X/E)),B=Math.abs(te-w);let L;!g||B<=this.tuning.dashCmafLive.offsetCalculationError?L=w:te>0&&B>this.tuning.dashCmafLive.offsetCalculationError?L=te:L=0,this.manifestUrlString=Ye(this.manifestUrlString,L,ge.DASH_CMAF_OFFSET_P)}q!==Je.None&&q!==Je.ActiveLowLatency&&(m=0,this.updateLive())})))}const l=F(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=F(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(F(this.forceEnded$,it({allBuffersFull:l,someBufferEnded:d}).pipe(he(({allBuffersFull:m,someBufferEnded:g})=>m&&g))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(F(...this.bufferManagers.map(m=>m.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 M(new Promise(m=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",m)})));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,g)=>{var S;return Math.max(m,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),v=this.manifest.representations.video.reduce(h,c);(f||v)&&(this.source.duration=Math.max(f,v)/1e3),this.audioBufferManager&&P(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Me.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Rs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new jy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Na.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return ee(this,void 0,void 0,function*(){R(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Ye(this.manifestUrlString,n,ge.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.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(){R(this.element),this.state$.setState(Me.RUNNING),this.subscription.add(F(...ol.map(e=>x(this.element,e)),x(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(x(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(x(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&La(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return ee(this,void 0,void 0,function*(){const s={[ye.VIDEO]:this.videoBufferManager,[ye.AUDIO]:this.audioBufferManager,[ye.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;R(this.element),R(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),La(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Me.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 ee(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:_.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return ee(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,s=[];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?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);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 Xy{constructor(e,t){this.fov=e,this.orientation=t}}class Zy{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var eT=`#define GLSLIFY 1
|
|
37
|
+
`}),N}return l==null||l.recordSwitch(L),L};var st=i=>new URL(i).hostname;const zo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Yt=i=>ee(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!zo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return zo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return le()}function Nu(i){return we()-i}function Wo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function WS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function As(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,l=0,d,c,h=!1,f="arraybuffer",v=7e3,m=2e3,g=()=>{if(u)return;R(d);const B=Nu(d);let L;if(B<m){L=m-B,setTimeout(g,L);return}m*=2,m>v&&(m=v),n&&n.abort(),n=new r,q()};const S=B=>(a=B,te),E=B=>(c=B,te),$=()=>(f="json",te),A=()=>{if(!u){if(--l>=0){g(),s&&s();return}u=!0,c&&c(),t&&t()}},P=B=>(h=B,te),q=()=>{d=we(),n=new r,n.open("get",i);let B=0,L,ae=0;const N=()=>(R(d),Math.max(d,Math.max(L||0,ae||0)));if(a&&n.addEventListener("progress",C=>{const Z=we();a.updateChunk&&C.loaded>B&&(a.updateChunk(N(),C.loaded-B),B=C.loaded,L=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;R(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const Z=n.response.byteLength-B;Z&&a.updateChunk&&a.updateChunk(N(),Z)}n.responseType==="json"&&!Object.values(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),h){const C=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=we(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),te},te={withBitrateReporting:S,withParallel:P,withJSONResponse:$,withRetryCount:B=>(l=B,te),withRetryInterval:(B,L)=>(k(B)&&(m=B),k(L)&&(v=L),te),withTimeout:B=>(o=B,te),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return te}const QS=100,KS=2e3,JS=500;let XS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-JS;if(t-e>KS){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>QS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class ZS{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=As(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const fs=1e4,zr=3,eb=6e4,tb=10,ib=1,sb=500;class rb{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new XS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||k(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{WS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ZS(zr,fs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,l=null,d=!1;const c=()=>{const A=a&&(!d||d===this.rep);return A||t("Not running!"),A},h=(A,P,q)=>{u&&u.abort(),u=As(this.urlResolver.resolve(A,!1),P,q,()=>this._retryCallback()).withTimeout(fs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zr).withFinally(()=>{u=null}).send()},f=(A,P,q)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),P,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=A=>{const P=s.playbackRate;s.playbackRate!==A&&(t(`Playback rate switch: ${P}=>${A}`),s.playbackRate=A)},m=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const q=we()-1e4;let z=0;for(let G=0;G<this.bufferStates.length;G++){const X=this.bufferStates[G];A=Math.min(A,X.buf),X.ts<q&&z++}this.bufferStates.splice(0,z),t(`update playback rate; minBuffer=${A} drop=${z} jitter=${this.sourceJitter}`);let J=A-ib;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?v(1.15):J>1?v(1.1):J>.3?v(1.05):v(1)}},S=A=>{let P;const q=()=>P&&P.start?P.start.length:0,z=C=>P.start[C]/1e3,J=C=>P.dur[C]/1e3,G=C=>P.fragIndex+C,X=(C,Z)=>({chunkIdx:G(C),startTS:z(C),dur:J(C),discontinuity:Z}),te=()=>{let C=0;if(P&&P.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=Z;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let Se=P.dur.length-1;for(;Se>=0&&(pe-=P.dur[Se],!(pe<=0));--Se);C=Math.min(Se,P.dur.length-1-ue),C=Math.max(C,0)}return X(C,!0)},B=C=>{const Z=q();if(!(Z<=0)){if(k(C)){for(let ue=0;ue<Z;ue++)if(z(ue)>C)return X(ue)}return te()}},L=C=>{const Z=q(),ue=C?C.chunkIdx+1:0,pe=ue-P.fragIndex;if(!(Z<=0)){if(!C||pe<0||pe-Z>tb)return t(`Resync: offset=${pe} bChunks=${Z} chunk=`+JSON.stringify(C)),te();if(!(pe>=Z))return X(ue-P.fragIndex,!1)}},ae=(C,Z,ue)=>{l&&l.abort(),l=As(this.urlResolver.resolve(C,!0,this.lowLatency),Z,ue,()=>this._retryCallback()).withTimeout(fs).withRetryCount(zr).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(C,Z)=>{ae(A,ue=>{if(!c())return;P=ue;const pe=!!P.lowLatency;pe!==this.lowLatency&&m(pe);let Se=0;for(let ze=0;ze<P.dur.length;++ze)Se+=P.dur[ze];Se>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/P.dur.length)),r({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,C(B(Z))},()=>this._handleNetworkError())},nextChunk:L}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{const{videoElement:P,logger:q}=this.params;let z=S(e.jidxUrl),J,G,X,te,B=0,L,ae,N;const C=()=>{L&&(clearTimeout(L),L=void 0);const Q=Math.max(sb,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+Q,ke=we(),Ce=Math.min(1e4,Ee-ke);B=ke;const zt=()=>{l||c()&&z.seek(()=>{c()&&(B=we(),Z(),C())})};Ce>0?L=window.setTimeout(()=>{this.paused?C():zt()},Ce):zt()},Z=()=>{let Q;for(;Q=z.nextChunk(te);)te=Q,bi(Q);const Ee=z.nextChunk(X);if(Ee){if(X&&Ee.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?C():(E(),this._initPlayerWith(e));return}ze(Ee)}else C()},ue=(Q,Ee)=>{if(!c()||!this.sourceBuffer)return;let ke,Ce,zt;const yi=at=>{window.setTimeout(()=>{c()&&ue(Q,Ee)},at)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),yi(100);else{const at=we(),xe=P.currentTime;!this.paused&&P.buffered.length>1&&ae===xe&&at-N>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),ae!==xe&&(ae=xe,N=at);const Wt=this._getBufferSizeSec();if(Wt>30)q(`Buffered ${Wt} seconds; delaying appendBuffer`),yi(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:at,buf:Wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ti){if(Ti.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),zt=this.sourceBuffer.buffered.length,zt!==0&&(ke=this.sourceBuffer.buffered.start(0),Ce=xe,Ce-ke>4&&this.sourceBuffer.remove(ke,Ce-3)),yi(1e3);else throw Ti}}},pe=()=>{G&&J&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(X)]),ue(G,function(){G=null,Z()}))},Se=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),ze=Q=>{c()&&f(Se(Q),(Ee,ke)=>{if(c()){if(ke/=1e3,G=Ee,X=Q,n=Q.startTS,ke){const Ce=Math.min(10,Q.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ce:Ce}pe()}},()=>this._handleNetworkError())},bi=Q=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(Q),!1)))},qt=Q=>{c()&&(e.cachedHeader=Q,ue(Q,()=>{J=!0,pe()}))};a=!0,z.seek(Q=>{if(c()){if(B=we(),!Q){C();return}te=Q,!K(A)||Q.startTS>A?ze(Q):(X=Q,Z())}},A),e.cachedHeader?qt(e.cachedHeader):h(e.headerUrl,qt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},d}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=we();if(this.chunkRateEstimator.addInterval(h,v,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:g}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nu(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&l(),f},notifySwitch:c=>{const h=we();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=As(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(fs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Yt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},eb))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Fu{constructor(){this.onDroopedVideoFramesLimit$=new D,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new D,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Mt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&di(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(x(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Rs(this.droppedFramesChecker.checkTime).pipe(he(()=>this.playing),he(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(tt(this.droppedFramesChecker.checkTime)),s=F(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>ys(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var H;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const ab=[H.PAUSED,H.PLAYING,H.READY],nb=[H.PAUSED,H.PLAYING,H.READY];class ob{constructor(e){this.subscription=new re,this.videoState=new ce(H.STOPPED),this.representations$=new b([]),this.textTracksManager=new Et,this.droppedFramesManager=new Fu,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new hn,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const l=r.isBuffering;this.params.output.isBuffering$.next(l);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const l=r.manifest,d=[];for(const c of l){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Ks(c.name))!==null&&n!==void 0?n:Ot(c.video),v=c.bitrate/1e3,m=Object.assign({},c.video);if(!f)continue;const g={id:h,quality:f,bitrate:v,size:m};d.push({track:g,representation:c})}this.representations$.next(d),this.params.output.availableVideoTracks$.next(d.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const l=r.quality,d=(u=this.representations$.getValue().find(({representation:c})=>c===l))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(l.headerUrl,this.params.source.url).hostname),k(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:l,duration:d}=r;this.params.dependencies.throughputEstimator.addRawSpeed(l,d);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(a)return;const l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(nb.includes(r)&&(l||d)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&ab.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Ye(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(n===p.PAUSED)this.videoState.setState(H.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)})}return;case H.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Ye(this.params.source.url,c))}return;default:return j(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:r})};F(this.videoState.stateChangeStarted$.pipe(w(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Ut(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(st(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Gt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===H.READY&&this.videoState.setState(H.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fe(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(it({zeroTime:this.zeroTime$.pipe(he(k)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(qi(this.video,this.params.desiredState.isLooped,t)).add(jt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Si(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&$d(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case H.MANIFEST_READY:case H.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return j(r.to)}},t)).add(F(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(tt(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ht(this.video)}createLiveDashPlayer(){const e=new rb({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),l=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&k(u)?u:Js(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=d==null?void 0:d.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(h||c!==f)&&this.setVideoTrack(d),v&&this.setAutoQuality(l),h||v||c!==f){const m=(n=o.find(({track:g})=>g.id===c))===null||n===void 0?void 0:n.representation;R(m,"Representations missing"),this.dash.startPlay(m,l)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;R(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===H.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var ye;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ye||(ye={}));var Je;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(Je||(Je={}));var xs;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(xs||(xs={}));var Be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Be||(Be={}));var U;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(U||(U={}));var fi;(function(i){i.MP4="mp4",i.WEBM="webm"})(fi||(fi={}));var Os;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Os||(Os={}));var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(oe||(oe={}));var li=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const lb=300,ub=(i,e=lb)=>new Ns(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(wd(n=>{const o=n[0];if(!o)return;let u,l;o.contentBoxSize&&o.contentBoxSize[0]?(l=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,l=o.contentRect.height),k(u)&&k(l)&&t.next({width:u,height:l})},e));return a.observe(i),()=>a.disconnect()});class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Vu extends Qo{constructor(){super(),this.listeners||Qo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Uu=class{constructor(){Object.defineProperty(this,"signal",{value:new Vu,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Uu.prototype[Symbol.toStringTag]="AbortController",Vu.prototype[Symbol.toStringTag]="AbortSignal");function Hu(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function db(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Hu({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);const h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,l)=>{const d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{d.addEventListener("abort",()=>v(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}const Xs=Hu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ju=Xs?db({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mi=Xs?ju.fetch:window.fetch;Xs?ju.Request:window.Request;const hi=Xs?Uu:window.AbortController;var La=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const cb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},hb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=hb?cb:window.requestIdleCallback;var Wr,Qr;const fb=16;let Gu=!1;try{Gu=Fa().browser===yl.Safari&&parseInt((Qr=(Wr=navigator.userAgent.match(/Version\/(\d+)/))===null||Wr===void 0?void 0:Wr[1])!==null&&Qr!==void 0?Qr:"",10)<=fb}catch(i){console.error(i)}class pb{constructor(e){this.bufferFull$=new D,this.error$=new D,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:_.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ee(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ee(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ee(this,void 0,void 0,function*(){return new Promise(t=>{let s;Gu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:_.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:j(t)}}}var Jo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ue{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 Yu extends Ue{}class mb extends Ue{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class vb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class gb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Sb extends Ue{constructor(e){super(e),this.data=this.content}}class pt extends Ue{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class bb extends pt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class yb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Tb extends Ue{parseChildrenBoxes(){return $t(this.content)}}var xt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(xt||(xt={}));class Eb extends pt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=xt.MONOSCOPIC;break;case 1:this.stereoMode=xt.TOP_BOTTOM;break;case 2:this.stereoMode=xt.LEFT_RIGHT;break;case 3:this.stereoMode=xt.STEREO_CUSTOM;break;case 4:this.stereoMode=xt.RIGHT_LEFT;break}this.cursor+=1}}class $b extends pt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class wb extends pt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ab extends Ue{parseChildrenBoxes(){return $t(this.content)}}class kb extends pt{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 Pb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Rb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class Ib extends pt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Cb extends Ue{parseChildrenBoxes(){return $t(this.content)}}class _b extends pt{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 Db extends pt{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 Lb extends pt{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 xb={ftyp:mb,moov:vb,moof:gb,mdat:Sb,sidx:bb,trak:yb,mdia:Ab,mfhd:Ib,tkhd:kb,traf:Cb,tfhd:_b,tfdt:Db,trun:Lb,minf:Pb,sv3d:Tb,st3d:Eb,prhd:$b,proj:Rb,equi:wb,unknown:Yu};class Ob{createBox(e,t){const s=xb[e];return s?new s(t):new Yu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Zs.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Zs=new Ob;function Ii(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(n=>n.charCodeAt(0));let r=i.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===s[a.length]?a.push(t[r]):a.length&&(a=[],r--),a.length===4){const o=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+o>i.buffer.byteLength?null:Zs.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function xa(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=Ii(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function $t(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Zs.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Mb=new TextDecoder("ascii"),Bb=i=>Mb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Nb=i=>{const e=Zs.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:U.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Fb=i=>{const e=xa(i,"mdat"),t=xa(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],a=s.source.byteOffset,o=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,a,o)},Vb=(i,e)=>{const t=xa(i,"traf"),s=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,l)=>u+l,0):n=s.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Ub=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ii(i,"sv3d")){e.is3dVideo=!0;const s=Ii(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=Ii(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Ii(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Hb={validateData:Bb,parseInit:Ub,getIndexRange:()=>{},parseSegments:Nb,parseFeedableSegmentChunk:Fb,getSegmentEndTime:Vb};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var I;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(I||(I={}));const Xo={[T.EBML]:{type:I.Master},[T.EBMLVersion]:{type:I.UnsignedInteger},[T.EBMLReadVersion]:{type:I.UnsignedInteger},[T.EBMLMaxIDLength]:{type:I.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[T.DocType]:{type:I.String},[T.DocTypeVersion]:{type:I.UnsignedInteger},[T.DocTypeReadVersion]:{type:I.UnsignedInteger},[T.Void]:{type:I.Binary},[T.Segment]:{type:I.Master},[T.SeekHead]:{type:I.Master},[T.Seek]:{type:I.Master},[T.SeekID]:{type:I.Binary},[T.SeekPosition]:{type:I.UnsignedInteger},[T.Info]:{type:I.Master},[T.TimestampScale]:{type:I.UnsignedInteger},[T.Duration]:{type:I.Float},[T.Tracks]:{type:I.Master},[T.TrackEntry]:{type:I.Master},[T.Video]:{type:I.Master},[T.Projection]:{type:I.Master},[T.ProjectionType]:{type:I.UnsignedInteger},[T.ProjectionPrivate]:{type:I.Master},[T.Chapters]:{type:I.Master},[T.Cluster]:{type:I.Master},[T.Timestamp]:{type:I.UnsignedInteger},[T.SilentTracks]:{type:I.Master},[T.SilentTrackNumber]:{type:I.UnsignedInteger},[T.Position]:{type:I.UnsignedInteger},[T.PrevSize]:{type:I.UnsignedInteger},[T.SimpleBlock]:{type:I.Binary},[T.BlockGroup]:{type:I.Master},[T.EncryptedBlock]:{type:I.Binary},[T.Attachments]:{type:I.Master},[T.Tags]:{type:I.Master},[T.Cues]:{type:I.Master},[T.CuePoint]:{type:I.Master},[T.CueTime]:{type:I.UnsignedInteger},[T.CueTrackPositions]:{type:I.Master},[T.CueTrack]:{type:I.UnsignedInteger},[T.CueClusterPosition]:{type:I.UnsignedInteger},[T.CueRelativePosition]:{type:I.UnsignedInteger},[T.CueDuration]:{type:I.UnsignedInteger},[T.CueBlockNumber]:{type:I.UnsignedInteger},[T.CueCodecState]:{type:I.UnsignedInteger},[T.CueReference]:{type:I.Master},[T.CueRefTime]:{type:I.UnsignedInteger}},qu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Ms(i,t),r=s in Xo,a=r?Xo[s].type:I.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,d=Ms(u),c=l*Math.pow(2,(o-1)*8)+d,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ms=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(i,e)=>{switch(e){case I.SignedInteger:return i.getInt8(0);case I.UnsignedInteger:return Ms(i);case I.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(i);case I.UTF8:return new TextDecoder("utf-8").decode(i);case I.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case I.Master:return i;case I.Binary:return i;default:j(e)}},pi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=qu(s);if(!e(r))return;r.type===I.Master&&pi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},jb=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=qu(i);return pi(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=Ze(o,n):a===T.DocType?t=Ze(o,n):a===T.DocTypeReadVersion&&(s=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},zu=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Gb=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],Yb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,l,d=!1;const c=0;return pi(i,({tag:h,type:f,value:v,valueSize:m})=>{if(h===T.SeekID){const g=Ze(v,f);l=Ms(g)}else h!==T.SeekPosition&&(l=void 0);return h===T.Segment?(e=v.byteOffset,t=v.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=Ze(v,f):h===T.Duration?r=Ze(v,f):h===T.SeekPosition&&l===T.Cues?u=Ze(v,f):h===T.Tracks?pi(v,({tag:g,type:S,value:E})=>g===T.ProjectionType?(d=Ze(E,S)===1,!1):!0):a&&n&&zu.includes(h)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:Os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},qb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zb=(i,e)=>{let t=!1,s=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return pi(i,({tag:o,type:u,value:l})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=Ze(l,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=Ze(l,u));break;default:t&&zu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:l,position:d}=o,c=a[u+1];return{status:U.NONE,time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Wb=i=>{let e=0,t=!1;try{pi(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Gb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Qb={validateData:jb,parseInit:Yb,getIndexRange:qb,parseSegments:zb,parseFeedableSegmentChunk:Wb};var Kb=ht,Jb=Ni,Xb=Ae,Zb=Xb("match"),ey=function(i){var e;return Kb(i)&&((e=i[Zb])!==void 0?!!e:Jb(i)=="RegExp")},ty=ji,iy=String,sy=function(i){if(ty(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return iy(i)},ry=ft,ay=function(){var i=ry(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},ny=Le,oy=rt,ly=Us,uy=ay,Zo=RegExp.prototype,dy=function(i){var e=i.flags;return e===void 0&&!("flags"in Zo)&&!oy(i,"flags")&&ly(Zo,i)?ny(uy,i):e},pn=Ve,cy=Ys,hy=Math.floor,Kr=pn("".charAt),fy=pn("".replace),Jr=pn("".slice),py=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,my=/\$([$&'`]|\d{1,2})/g,vy=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=my;return r!==void 0&&(r=cy(r),u=py),fy(a,u,function(l,d){var c;switch(Kr(d,0)){case"$":return"$";case"&":return i;case"`":return Jr(e,0,t);case"'":return Jr(e,n);case"<":c=r[Jr(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var f=hy(h/10);return f===0?l:f<=o?s[f-1]===void 0?Kr(d,1):s[f-1]+Kr(d,1):l}c=s[h-1]}return c===void 0?"":c})},gy=qe,Sy=Le,mn=Ve,el=Va,by=ve,yy=Fi,Ty=ey,ii=sy,Ey=Gs,$y=dy,wy=vy,Ay=Ae,ky=Ay("replace"),Py=TypeError,Wu=mn("".indexOf),Ry=mn("".replace),tl=mn("".slice),Iy=Math.max,il=function(i,e,t){return t>i.length?-1:e===""?t:Wu(i,e,t)};gy({target:"String",proto:!0},{replaceAll:function(e,t){var s=el(this),r,a,n,o,u,l,d,c,h,f=0,v=0,m="";if(!yy(e)){if(r=Ty(e),r&&(a=ii(el($y(e))),!~Wu(a,"g")))throw Py("`.replaceAll` does not allow non-global regexes");if(n=Ey(e,ky),n)return Sy(n,e,s,t);if(r)return Ry(ii(s),e,t)}for(o=ii(s),u=ii(e),l=by(t),l||(t=ii(t)),d=u.length,c=Iy(1,d),f=il(o,u,0);f!==-1;)h=l?ii(t(u,f,o)):wy(u,o,f,[],void 0,t),m+=tl(o,v,f)+h,v=f+d,f=il(o,u,f+c);return v<o.length&&(m+=tl(o,v)),m}});var Cy=un,_y=Cy("String","replaceAll"),Dy=_y,Ly=Dy,xy=Ly,Oy=xy,sl=Fs(Oy);const My=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},rl=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ri=(i,e)=>{let t=i;t=sl(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=sl(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},By=(i,e)=>{var t,s,r,a,n,o,u,l,d,c,h,f,v,m,g,S,E,$,A,P,q,z,J,G,X,te,B,L,ae,N,C,Z,ue,pe,Se,ze,bi,qt,Q,Ee,ke,Ce;const yi=new DOMParser().parseFromString(i,"application/xml"),at={video:[],audio:[],text:[]},xe=yi.children[0],Wt=xe.getElementsByTagName("Period")[0],Ti=(r=(s=(t=xe.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",td=Wt.children,id=xe.getAttribute("type")==="dynamic",Sn=xe.getAttribute("availabilityStartTime"),sd=Sn?new Date(Sn).getTime():void 0;let wt;const bn=xe.getAttribute("mediaPresentationDuration"),yn=Wt.getAttribute("duration"),er=xe.getElementsByTagName("vk:Attrs")[0],Tn=er==null?void 0:er.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(bn)wt=rl(bn);else if(yn){const He=rl(yn);k(He)&&(wt=He)}else Tn&&(wt=parseInt(Tn,10));let rd=0;const tr=(n=(a=xe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],ad=tr.includes(xs.WEBM_AS_IN_FFMPEG)||tr.includes(xs.WEBM_AS_IN_SPEC)?fi.WEBM:fi.MP4;for(const He of td){const zi=He.getAttribute("mimeType"),nd=He.getAttribute("codecs"),En=(o=He.getAttribute("contentType"))!==null&&o!==void 0?o:zi==null?void 0:zi.split("/")[0],od=(l=(u=He.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&l!==void 0?l:[],$n=He.querySelectorAll("Representation"),ld=He.querySelector("SegmentTemplate");if(En===ye.TEXT){for(const me of $n){const mt=me.getAttribute("id")||"",Wi=He.getAttribute("lang"),Qt=(h=(c=(d=me.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",ir=new URL(Qt||Ti,e).toString(),sr=mt.includes("_auto");at[ye.TEXT].push({id:mt,lang:Wi,isAuto:sr,kind:ye.TEXT,url:ir})}continue}for(const me of $n){const mt=(f=me.getAttribute("mimeType"))!==null&&f!==void 0?f:zi,Wi=(m=(v=me.getAttribute("codecs"))!==null&&v!==void 0?v:nd)!==null&&m!==void 0?m:"",Qt=(S=(g=me.getAttribute("contentType"))!==null&&g!==void 0?g:mt==null?void 0:mt.split("/")[0])!==null&&S!==void 0?S:En,ir=($=(E=He.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&$!==void 0?$:[],sr=parseInt((A=me.getAttribute("width"))!==null&&A!==void 0?A:"",10),wn=parseInt((P=me.getAttribute("height"))!==null&&P!==void 0?P:"",10),An=parseInt((q=me.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,kn=(z=me.getAttribute("frameRate"))!==null&&z!==void 0?z:"",ud=(J=me.getAttribute("quality"))!==null&&J!==void 0?J:void 0,dd=kn?My(kn):void 0,cd=(G=me.getAttribute("id"))!==null&&G!==void 0?G:(rd++).toString(10),hd=Qt==="video"?`${wn}p`:Qt==="audio"?`${An}Kbps`:Wi,fd=`${cd}@${hd}`,pd=(B=(te=(X=me.querySelector("BaseURL"))===null||X===void 0?void 0:X.textContent)===null||te===void 0?void 0:te.trim())!==null&&B!==void 0?B:"",Pn=new URL(pd||Ti,e).toString(),md=[...tr,...od,...ir];let rr;const vd=me.querySelector("SegmentBase"),At=(L=me.querySelector("SegmentTemplate"))!==null&&L!==void 0?L:ld;if(vd){const kt=(N=(ae=me.querySelector("SegmentBase Initialization"))===null||ae===void 0?void 0:ae.getAttribute("range"))!==null&&N!==void 0?N:"",[Pt,nr]=kt.split("-").map(Kt=>parseInt(Kt,10)),vt={from:Pt,to:nr},Ei=(C=me.querySelector("SegmentBase"))===null||C===void 0?void 0:C.getAttribute("indexRange"),[or,Qi]=Ei?Ei.split("-").map(Kt=>parseInt(Kt,10)):[],$i=Ei?{from:or,to:Qi}:void 0;rr={type:Be.BYTE_RANGE,url:Pn,initRange:vt,indexRange:$i}}else if(At){const kt={representationId:(Z=me.getAttribute("id"))!==null&&Z!==void 0?Z:void 0,bandwidth:(ue=me.getAttribute("bandwidth"))!==null&&ue!==void 0?ue:void 0},Pt=parseInt((pe=At.getAttribute("timescale"))!==null&&pe!==void 0?pe:"",10),nr=(Se=At.getAttribute("initialization"))!==null&&Se!==void 0?Se:"",vt=At.getAttribute("media"),Ei=(bi=parseInt((ze=At.getAttribute("startNumber"))!==null&&ze!==void 0?ze:"",10))!==null&&bi!==void 0?bi:1,or=ri(nr,kt);if(!vt)throw new ReferenceError("No media attribute in SegmentTemplate");const Qi=(qt=At.querySelectorAll("SegmentTimeline S"))!==null&&qt!==void 0?qt:[],$i=[];let Kt=0,lr="",ur=0;if(Qi.length){let Ki=Ei,je=0;for(const Jt of Qi){const We=parseInt((Q=Jt.getAttribute("d"))!==null&&Q!==void 0?Q:"",10),Rt=parseInt((Ee=Jt.getAttribute("r"))!==null&&Ee!==void 0?Ee:"",10)||0,Ji=parseInt((ke=Jt.getAttribute("t"))!==null&&ke!==void 0?ke:"",10);je=Number.isFinite(Ji)?Ji:je;const dr=We/Pt*1e3,cr=je/Pt*1e3;for(let Xi=0;Xi<Rt+1;Xi++){const Sd=ri(vt,Object.assign(Object.assign({},kt),{segmentNumber:Ki.toString(10),segmentTime:(je+Xi*We).toString(10)})),Rn=(cr!=null?cr:0)+Xi*dr,bd=Rn+dr;Ki++,$i.push({time:{from:Rn,to:bd},url:Sd})}je+=(Rt+1)*We,Kt+=(Rt+1)*dr}ur=je/Pt*1e3,lr=ri(vt,Object.assign(Object.assign({},kt),{segmentNumber:Ki.toString(10),segmentTime:je.toString(10)}))}else if(k(wt)){const je=parseInt((Ce=At.getAttribute("duration"))!==null&&Ce!==void 0?Ce:"",10)/Pt*1e3,Jt=Math.ceil(wt/je);let We=0;for(let Rt=1;Rt<Jt;Rt++){const Ji=ri(vt,Object.assign(Object.assign({},kt),{segmentNumber:Rt.toString(10),segmentTime:We.toString(10)}));$i.push({time:{from:We,to:We+je},url:Ji}),We+=je}ur=We,lr=ri(vt,Object.assign(Object.assign({},kt),{segmentNumber:Jt.toString(10),segmentTime:We.toString(10)}))}const gd={time:{from:ur,to:1/0},url:lr};rr={type:Be.TEMPLATE,baseUrl:Pn,segmentTemplateUrl:vt,initUrl:or,totalSegmentsDurationMs:Kt,segments:$i,nextSegmentBeyondManifest:gd,timescale:Pt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!mt)continue;const ar={video:ye.VIDEO,audio:ye.AUDIO,text:ye.TEXT}[Qt];ar&&at[ar].push({id:fd,kind:ar,segmentReference:rr,profiles:md,duration:wt,bitrate:An,mime:mt,codecs:Wi,width:sr,height:wn,fps:dd,quality:ud})}}return{dynamic:id,liveAvailabilityStartTime:sd,duration:wt,container:ad,representations:at}},Ny=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ks(a):void 0)!==null&&n!==void 0?n:Ot({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Fy=({id:i,bitrate:e})=>({id:i,bitrate:e}),Vy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=nt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:nt(i,-1)},Uy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),al=i=>"url"in i,si=i=>i.type===Be.TEMPLATE,Oa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class nl{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:d}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.playingRepresentationInit$=new b(void 0),this.error$=new D,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new hi,this.destroyAbortController=new hi,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){const h=this.representations.get(c);R(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new pb(this.sourceBuffer),this.subscription.add(x(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(x(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),v=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(R(f,"No init buffer for starting representation"),R(v,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield M(void 0);this.searchGaps(v,h),yield yield M(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);R(h,`No such representation ${c}`);let f=this.segments.get(c),v=this.initData.get(c);if(K(v)||K(f)?yield yield M(this.loadInit(h,"high",!1)):v instanceof Promise&&(yield yield M(v)),f=this.segments.get(c),R(f,"No segments for starting representation"),v=this.initData.get(c),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();k(m)&&(this.isLive||(f.forEach(g=>g.status=U.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,function(c){var h;return Ie(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield M(void 0);for(const E of this.representations.keys()){const $=c.find(q=>q.id===E);$&&this.representations.set(E,$);const A=this.representations.get(E);if(!A||!si(A.segmentReference))return yield M(void 0);const P=this.getActualLiveStartingSegments(A.segmentReference);this.segments.set(A.id,P)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,v=this.representations.get(f);R(v);const m=this.segments.get(f);R(m,"No segments for starting representation");const g=this.initData.get(f);if(R(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return yield M(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield M(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield M(this.sourceBufferTaskQueue.append(g,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(d!=null&&d.dynamic),this.container=s,s){case fi.MP4:this.containerParser=Hb;break;case fi.WEBM:this.containerParser=Qb;break;default:j(s)}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 hi,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(R(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(l=>e>=l.time.from&&e<l.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=li(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const l=li(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{const d=nt(o,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===U.FED&&!o.length&&li(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=nt(s,-1);u&&u.status===U.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;k(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=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<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,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 s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!si(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:U.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],l=(a=(r=nt(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,d=o==null?void 0:o.findIndex(c=>Math.floor(l)>=Math.floor(c.time.from)&&Math.floor(l)<=Math.floor(c.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(d+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!si(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=ri(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||o.push({status:U.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;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,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const m=h<=s&&f>=s,g=h>s||m||v===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===U.NONE||c===U.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!La(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==Be.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===U.NONE||h.status===U.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ee(this,void 0,void 0,function*(){t.segmentReference.type===Be.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return ee(this,void 0,void 0,function*(){e.status=U.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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Re(o,function(){return Ie(this,arguments,function*(){const d=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const c=new DataView(d);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=U.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){if(!Oa(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,s="auto"){return ee(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=U.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 Re(n,function(){return Ie(this,arguments,function*(){const u=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){if(!Oa(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(si(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:nt(e,0).byte.from,to:nt(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(u,l)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!si(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:l,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(s=li((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:_.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){return ee(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=s,o.loadedBytes>o.feedingBytes){const l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(l);d!=null&&d.byteLength&&(u.status=U.PARTIALLY_FED,o.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,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,l=e.byteLength;for(const d of this.activeSegments){const{segment:c}=d,h=u===Be.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:l;if(d.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,g=h?c.byte.to-s:e.byteLength,S=m<r,E=g<=r;if(c.status===U.DOWNLOADING&&S&&E){c.status=U.DOWNLOADED;const $=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append($,a).then(A=>A&&!a.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(d.loadedBytes=Math.min(f,r-m),d.loadedBytes>d.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+m+d.feedingBytes,d.loadedBytes-d.feedingBytes),A=d.loadedBytes===f?$:this.containerParser.parseFeedableSegmentChunk($);A!=null&&A.byteLength&&(c.status=U.PARTIALLY_FED,d.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(P=>{if(a.aborted)n();else if(P)d.fedBytes+=A.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=U.FED,al(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===U.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=U.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===U.PARTIALLY_FED||e.status===U.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=U.NONE),e.status=U.PARTIALLY_EJECTED):e.status=U.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ko(()=>dn(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ee(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Re(this.destroyAbortController.signal,function(){return Ie(this,arguments,function*(){const o=Ts(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>ee(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&si(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),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ee(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=l=>{var d;a=Math.min(a,l.time.from),n=Math.max(n,l.time.to);const c=al(l)?(d=l.size)!==null&&d!==void 0?d:0:l.byte.to-l.byte.from;r+=c};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===U.FED&&u(d)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const l of this.segments.values())for(const d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;d.status===U.FED&&u(d)}}if(o=isFinite(a)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){const d=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===U.NONE&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(c)){a=d,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const c of d)c.time.from>e+l&&c.status===U.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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==U.FED&&a!==U.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);u||(l.length===1?r.status=U.PARTIALLY_EJECTED:r.status=U.NONE)}}}var Ma=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Hy=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ca.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},ui;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(ui||(ui={}));class jy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new hi,this.subscription=new re,this.fetchManifest=Re(this.abortAllController.signal,function(r){return Ie(this,arguments,function*(){let a=r;this.requestQuic&&(a=Ma(a));const n=yield yield M(Mi(a,{signal:this.abortAllController.signal}).catch(Ai));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Re(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?ui.HEADER:ui.PARAM,range:n,onProgress:o,priority:u="auto",signal:l,measureThroughput:d=!0,isLowLatency:c=!1}={}){var h,f;return Ie(this,arguments,function*(){let v=r;const m=new Headers;if(n)switch(a){case ui.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case ui.PARAM:{const L=new URL(v,location.href);L.searchParams.append("bytes",`${n.from}-${n.to}`),v=L.toString();break}default:j(a)}this.requestQuic&&(v=Ma(v));let g=this.abortAllController.signal,S;if(l){const L=new hi;if(S=F(x(this.abortAllController.signal,"abort"),x(l,"abort")).subscribe(()=>{try{L.abort()}catch(ae){Ai(ae)}}),this.abortAllController.signal.aborted||l.aborted)try{L.abort()}catch(ae){Ai(ae)}g=L.signal}const E=le(),$=yield yield M(Mi(v,{priority:u,headers:m,signal:g}).catch(Ai)),A=le();if(!$)return S==null||S.unsubscribe(),yield M(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(A-E),!$.ok||!$.body)return S==null||S.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${$.status}: ${$.statusText}`)));if(this.onHeadersReceived($.headers),!o&&!d)return S==null||S.unsubscribe(),yield M($.arrayBuffer());const[P,q]=$.body.tee(),z=P.getReader();d&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,c));let J=0,G=new Uint8Array(0),X=!1;const te=L=>{S==null||S.unsubscribe(),X=!0,Ai(L)},B=Re(g,function({done:L,value:ae}){return Ie(this,arguments,function*(){if(J===0&&this.lastRequestFirstBytes$.next(le()-E),g.aborted)return S==null||S.unsubscribe(),yield M(void 0);if(!L&&ae){const N=new Uint8Array(G.length+ae.length);N.set(G),N.set(ae,G.length),G=N,J+=ae.byteLength,o==null||o(new DataView(G.buffer),J),yield yield M(z==null?void 0:z.read().then(B,te))}})}.bind(this));return yield yield M(z==null?void 0:z.read().then(B,te)),S==null||S.unsubscribe(),yield M(X?null:G.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,function(r,a,n){var o;return Ie(this,arguments,function*(){if(r.type!==Be.BYTE_RANGE)return yield M(null);const{from:u,to:l}=r.initRange;let d=u,c=l,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=l+1===f,h&&(d=Math.min(f,u),c=Math.max(v,l))),d=Math.min(d,0);const m=yield yield M(this.fetch(r.url,{range:{from:d,to:c},priority:n,measureThroughput:!1}));if(!m)return yield M(null);const g=new DataView(m,u-d,l-d+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let $;if(h)$=new DataView(m,E.from-d,E.to-E.from+1);else{const P=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!P)return yield M(null);$=new DataView(P)}const A=a.parseSegments($,S,E);return yield M({init:S,dataView:new DataView(m),segments:A})})}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,function(r,a){return Ie(this,arguments,function*(){if(r.type!==Be.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(l=>Object.assign(Object.assign({},l),{status:U.NONE,size:void 0}));return yield M({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Hy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ee(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:j(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ai=i=>{if(!Oa(i))throw i},Ba=1e3,Bs=(i,e,t)=>t*e+(1-t)*i,Qu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Gy=(i,e,t,s)=>{let r=0,a=t;const n=Qu(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class vn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new b(e.initial),this.debounced$=new b(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Xe(`raw_${s}`),this.smoothedSeries$=new Xe(`smoothed_${s}`),this.reportedSeries$=new Xe(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(K(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Yy extends vn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Bs(this.slow,e,this.params.emaAlphaSlow),this.fast=Bs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class qy extends vn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Bs(this.emaSmoothed,e,this.params.emaAlpha);const s=Gy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class zy extends vn{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?Bs(this.smoothed,e,this.params.emaAlpha):e}}class Na{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Yy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new qy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new zy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const Wy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Ct=()=>window.ManagedMediaSource||window.MediaSource,Ku=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Qy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Ky=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,ol=["timeupdate","progress","play","seeked","stalled","waiting"];var Me;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Me||(Me={}));let Jy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new ce(Me.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new D,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.isLive$=new b(!1),this.liveDuration$=new b(0),this.liveAvailabilityStartTime$=new b(void 0),this.bufferLength$=new b(0),this.liveLoadBufferLength$=new b(0),this.livePositionFromPlayer$=new b(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new D,this.gapWatchdogStarted=!1,this.destroyController=new hi,this.initManifest=Re(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){this.element=t,this.manifestUrlString=Ye(s,r,ge.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Me.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Me.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,function(){var t;return Ie(this,arguments,function*(){const s=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(null);let r;try{r=By(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var l,d,c,h;return!!(!((d=(l=this.element)===null||l===void 0?void 0:l.canPlayType)===null||d===void 0)&&d.call(l,o)&&(!((h=(c=Ct())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===ye.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 M(Object.assign(Object.assign({},r),{representations:Ds(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){R(this.manifest),R(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Me.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(x(m,"error").pipe(he(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:_.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?Ky():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Ku())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={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 nl(ye.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],k(s)&&(this.audioBufferManager=new nl(ye.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),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(Rs(Ba).subscribe(m=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=Go(this.manifestUrlString,ge.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ye(this.manifestUrlString,S+Ba,ge.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(F(...ol.map(m=>x(this.element,m))).pipe(w(m=>this.element?li(this.element.buffered,this.element.currentTime*1e3):0),fe(),he(m=>!!m),Li(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(he(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,$=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=g-S;let P=1+Math.sign(A)*$;Math.abs(A)<E?P=1:Math.abs(A)>E*2&&(P=1+Math.sign(A)*$*2),Wy(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let $=0;if(g){const A=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;$=Math.min(...this.bufferManagers.map(q=>{var z,J;return(J=(z=q.getLiveSegmentsToLoadState(this.manifest))===null||z===void 0?void 0:z.to)!==null&&J!==void 0?J:0}))-A}$&&this.liveLoadBufferLength$.getValue()!==$&&this.liveLoadBufferLength$.next($)}));let m=0;this.representationSubscription.add(it({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:g,bufferLength:S})=>ee(this,void 0,void 0,function*(){if(R(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,$=Go(this.manifestUrlString,ge.DASH_CMAF_OFFSET_P),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,z=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,J=this.isActiveLowLatency?S:g;let G=Je.None;if(this.isActiveLowLatency?G=Je.ActiveLowLatency:J<P+z&&J>=P?G=Je.LiveWithTargetOffset:$!==0&&J<P&&(G=Je.LiveForwardBuffering),isFinite(g)&&(m=g>m?g:m),G===Je.LiveForwardBuffering||G===Je.LiveWithTargetOffset){const X=m-(P+q),te=this.normolizeLiveOffset(Math.trunc($+X/E)),B=Math.abs(te-$);let L;!g||B<=this.tuning.dashCmafLive.offsetCalculationError?L=$:te>0&&B>this.tuning.dashCmafLive.offsetCalculationError?L=te:L=0,this.manifestUrlString=Ye(this.manifestUrlString,L,ge.DASH_CMAF_OFFSET_P)}G!==Je.None&&G!==Je.ActiveLowLatency&&(m=0,this.updateLive())})))}const l=F(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=F(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(F(this.forceEnded$,it({allBuffersFull:l,someBufferEnded:d}).pipe(he(({allBuffersFull:m,someBufferEnded:g})=>m&&g))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(F(...this.bufferManagers.map(m=>m.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 M(new Promise(m=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",m)})));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,g)=>{var S;return Math.max(m,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),v=this.manifest.representations.video.reduce(h,c);(f||v)&&(this.source.duration=Math.max(f,v)/1e3),this.audioBufferManager&&k(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Me.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Rs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new jy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Na.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return ee(this,void 0,void 0,function*(){R(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Ye(this.manifestUrlString,n,ge.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.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(){R(this.element),this.state$.setState(Me.RUNNING),this.subscription.add(F(...ol.map(e=>x(this.element,e)),x(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(x(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(x(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&La(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return ee(this,void 0,void 0,function*(){const s={[ye.VIDEO]:this.videoBufferManager,[ye.AUDIO]:this.audioBufferManager,[ye.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;R(this.element),R(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),La(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Me.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 ee(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:_.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return ee(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,s=[];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?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);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 Xy{constructor(e,t){this.fov=e,this.orientation=t}}class Zy{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var eT=`#define GLSLIFY 1
|
|
38
38
|
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,tT=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
@@ -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 iT{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,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 Xy(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zy(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"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(eT,this.gl.VERTEX_SHADER),s=this.createShader(tT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,l=e+s,d=t+r,c=e-s,h=t+r;return[a,n,o,u,l,d,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}}const sT=(i,e)=>new Ns(t=>{if(!window.IntersectionObserver)return;const s=()=>!!window.documentPictureInPicture.window||!!document.pictureInPictureElement,r={root:null},a=new IntersectionObserver((o,u)=>{o.forEach(l=>t.next(l.isIntersecting||s()))},Object.assign(Object.assign({},r),e));a.observe(i);const n=x(document,"visibilitychange").pipe(A(o=>!document.hidden||s())).subscribe(o=>t.next(o));return()=>{a.unobserve(i),n.unsubscribe}});class Ju{constructor(e){this.subscription=new re,this.videoState=new ce(oe.STOPPED),this.elementSize$=new b(void 0),this.elementVisible$=new b(!0),this.textTracksManager=new Et,this.droppedFramesManager=new Fu,this.videoTracks$=new b([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new qS,this.textTracks=[],this.syncPlayback=()=>{var t,s,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===z.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==oe.STOPPED&&n!==p.STOPPED){const d=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-d,u.forcePrecise)}if(n===p.STOPPED){a!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case oe.STOPPED:this.videoState.startTransitionTo(oe.READY),this.prepare();return;case oe.READY:n===p.PAUSED?(this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.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)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new iT(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.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=Vt(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(st(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Jy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=jt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:_.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,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$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(A(l=>l.map(({track:d})=>d)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(he(P),Pe()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qi(this.video,t.isLooped,r)),this.subscription.add(Ht(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(gi(this.video,t.playbackRate,s.playbackRateState$,r)),a(ub(this.video),this.elementSize$),a(sT(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var d;if(l===Me.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();R(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=Fy(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of v){const E=Ny(S);if(E){c.push({track:E,representation:S});const w=!this.params.tuning.isAudioDisabled&&Vy(f,v,S);w&&this.audioRepresentations.set(S.id,w)}}this.videoTracks$.next(c);for(const S of m){const E=Uy(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();R(g),this.player.initRepresentations(g.id,(d=this.audioRepresentations.get(g.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else l===Me.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},r));const n=l=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(F(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,x(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==Me.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const{width:E,height:w}=S,{width:$,height:k}=c,j=Math.min(E,w)+"p",Y=Math.min($,k)+"p";return Ps(j,Y)&&Ps(j,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(ye.VIDEO,m).catch(n);const g=this.audioRepresentations.get(c.id);g&&this.player.switchRepresentation(ye.AUDIO,g.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(fe(),A(l=>{var d;return l&&((d=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===l))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&(!((d=this.params.tuning.spherical)===null||d===void 0)&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider 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(A(({to:l})=>l===p.READY),fe());this.subscription.add(F(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(F(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),l=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,d=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===l))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=oi(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!u&&(r=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.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),g=Js(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:d:d!=null?d:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Gt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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 rT extends Ju{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class aT extends Ju{constructor(e){super(e),this.liveOffset=new hn}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(it({interval:Rs(Ba),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===oe.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(it({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({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(),s=this.videoState.getState(),r=t===p.PAUSED&&s===oe.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 Ke={};var W;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const Ai=(i,e)=>new Ns(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class nT{constructor(e){this.subscription=new re,this.videoState=new ce(W.INITIALIZING),this.textTracksManager=new Et,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==W.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:G(t)}break;case p.READY:switch(t){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:G(t)}break;case p.PLAYING:switch(t){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:G(t)}break;case p.PAUSED:switch(t){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case W.PLAYING:this.pause();break;default:G(t)}break;default:G(s)}},this.video=Vt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(st(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:_.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);dn(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){R(Ke.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=l=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=jt(this.video),a=(l,d)=>this.subscription.add(l.subscribe(d,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(qi(this.video,e.isLooped,s)),this.subscription.add(Ht(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(gi(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(Ai(this.hls,Ke.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)===null||d===void 0?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),a(Ai(this.hls,Ke.Events.MANIFEST_PARSED).pipe(A(({levels:l})=>l.reduce((d,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:m,height:g}=c,S=(f=Ks((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Bi({width:m,height:g});if(!S)return d;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,w={id:v.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:g},fps:E};return this.trackLevels.set(v,{track:w,level:c}),d.push(w),d},[]))),t.availableVideoTracks$),a(Ai(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){const d=[];for(const c of l.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,m="internal";d.push({id:h,url:f,language:v,type:m})}e.internalTextTracks.startTransitionTo(d)}}),a(Ai(this.hls,Ke.Events.LEVEL_LOADING).pipe(A(({url:l})=>st(l))),t.hostname$),this.subscription.add(ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:s}));const n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))===null||d===void 0?void 0:d.track},o=Ai(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(A(({level:l})=>n(this.hls.levels[l])));o.pipe(he(P)).subscribe(t.currentVideoTrack$,s),this.subscription.add(ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var d;if(K(l))return;const c=(d=this.trackLevels.get(l.id))===null||d===void 0?void 0:d.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=F(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ee(this,void 0,void 0,function*(){this.videoState.startTransitionTo(W.PLAYING),(yield Gt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:t})))||(this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(W.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(W.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const ll="X-Playback-Duration";var ul=i=>ee(void 0,void 0,void 0,function*(){var e;const t=yield Oi(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(ll)?parseInt(t.headers.get(ll),10):void 0});const oT=i=>{let e=null;if(i.QUALITY&&(e=Ks(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Bi({width:t,height:s})}return e!=null?e:null},lT=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){const c=Ds(l[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=oT(c);let v;c.BANDWIDTH&&(v=parseInt(c.BANDWIDTH,10)/1e3||void 0),!v&&c["AVERAGE-BANDWIDTH"]&&(v=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let g;if(c.RESOLUTION){const[E,w]=c.RESOLUTION.split("x").map($=>parseInt($,10));E&&w&&(g={width:E,height:w})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:v,size:g,fps:m})}if(d){const c=Ds(d[1].split(",").map(m=>m.split("=")).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,v=c.NAME;h&&f&&n.push({type:"internal",id:f,label:v,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},uT=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Xr=0;const gn=(i,e=i,t)=>ee(void 0,void 0,void 0,function*(){const r=yield(yield Oi(i)).text();Xr+=1;try{const{qualityManifests:a,textTracks:n}=lT(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(Xr<=t.manifestRetryMaxCount)return yield uT(Ts(Xr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gn(i,e,t)}return{qualityManifests:[],textTracks:[]}});var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class dT{constructor(e){var t;this.subscription=new re,this.videoState=new ce(ie.STOPPED),this.textTracksManager=new Et,this.manifests$=new b([]),this.liveOffset=new hn,this.manifestStartTime$=new b(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(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u||l){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===z.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return G(r)}},this.params=e,this.video=Vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_e.INVARIANT,url:this.params.source.url},gn(Ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(st(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=jt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ht(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(gi(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(fe(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&P(l.to)){const c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(st(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===z.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,l;const d=(l=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||l===void 0?void 0:l.getTime();this.manifestStartTime$.next(d||void 0)},s)),this.subscription.add(it({startTime:this.manifestStartTime$.pipe(he(P)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[l,"mq"],[d,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===y.HLS_LIVE_CMAF?ge.DASH_CMAF_OFFSET_P:ge.OFFSET_P,u=Ye(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),ul(u).then(l=>{var d;if(!K(l))this.maxSeekBackTime$.next(l);else{const c=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(K(c)||!isFinite(c))try{Oi(u).then(h=>h.text()).then(h=>{var f;const v=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(v){const m=new URL(v,u).toString();ul(m).then(g=>{K(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Gt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ne||(ne={}));class cT{constructor(e){this.subscription=new re,this.videoState=new ce(ne.STOPPED),this.textTracksManager=new Et,this.manifests$=new b([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===z.Requested&&this.seek(d.position),s){case ne.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return G(s)}},this.params=e,this.video=Vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_e.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(st(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gn(Ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},r=jt(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(qi(this.video,t.isLooped,s)),this.subscription.add(Ht(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(gi(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const f=this.manifests$.getValue().find(v=>v.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(st(f.url));const v=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(v!==m){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(v),g.playbackRate=v)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from===ne.CHANGING_MANIFEST&&this.videoState.setState(l.to),u.state===z.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!Ad()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(F(x(o,"addtrack"),x(o,"removetrack"),x(o,"change"),Ne(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.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[l,d]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(l||""));d&&l&&n.searchParams.set(d,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Gt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));class hT{constructor(e){this.subscription=new re,this.videoState=new ce(de.STOPPED),this.trackUrls={},this.textTracksManager=new Et,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.autoVideoTrackLimits.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(l&&a!==de.READY&&!d){this.handleQualityLimitTransition(l.to.max);return}if(a===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(d){const{currentTime:h}=this.video;this.prepare(),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[d.to.id])===null||s===void 0?void 0:s.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)!==p.PAUSED&&c.state===z.Requested&&this.seek(c.position),a){case de.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(a)}},this.params=e,this.video=Vt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},r=jt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(qi(this.video,t.isLooped,s)),this.subscription.add(Ht(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(gi(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY);const l=this.params.desiredState.videoTrack.getTransition();if(l&&P(l.to)){this.params.desiredState.videoTrack.setState(l.to),this.params.output.currentVideoTrack$.next(this.trackUrls[l.to.id].track);const d=this.params.desiredState.playbackRate.getState(),c=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(d!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;R(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];R(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Ma(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(st(s))}playIfAllowed(){Gt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,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=(s=Object.values(this.trackUrls).find(c=>!Ot(c.track.quality)&&Ps(c.track.quality,e)))===null||s===void 0?void 0:s.track,l=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,d=(a=this.trackUrls[l!=null?l:"0"])===null||a===void 0?void 0:a.track;if(u&&d&&da(d.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Ot(f.track.quality)&&ui(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(l=>l.track);n=Js(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 dl=["stun:videostun.mycdn.me:80"],fT=1e3,pT=3,Zr=()=>null;class mT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ee(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 ee(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:dl}]};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 ee(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 ee(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:_.WTF,message:e.message})}onPeerConnectionStream(e){return ee(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 ee(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),fT)}normalizeOptions(e={}){const t={stunServerList:dl,maxRetryNumber:pT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class vT{constructor(e){this.videoState=new ce(se.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:s===p.PAUSED?(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Vt(e.container),this.liveStreamClient=new mT(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,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};F(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=jt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ht(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return G(n.to)}},s)).add(F(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(st(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:_e.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Gt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class cl{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 ea,ta,ia,sa,ps,ra,ms,aa,vs,na,gs,oa,Ss,la,bs,ua;const Xu=Fa().device===kd.Android,bt=document.createElement("video"),gT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ST='video/mp4; codecs="hev1.1.6.L93.B0"',Zu='video/webm; codecs="vp09.00.10.08"',ed='video/webm; codecs="av01.0.00M.08"',bT='audio/mp4; codecs="mp4a.40.2"',yT='audio/webm; codecs="opus"',_t={mms:Ku(),mse:Qy(),hls:!!(!((ea=bt.canPlayType)===null||ea===void 0)&&ea.call(bt,"application/x-mpegurl")||!((ta=bt.canPlayType)===null||ta===void 0)&&ta.call(bt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Oe={mp4:!!(!((ia=bt.canPlayType)===null||ia===void 0)&&ia.call(bt,"video/mp4")),webm:!!(!((sa=bt.canPlayType)===null||sa===void 0)&&sa.call(bt,"video/webm")),cmaf:!0},et={h264:!!(!((ra=(ps=Ct())===null||ps===void 0?void 0:ps.isTypeSupported)===null||ra===void 0)&&ra.call(ps,gT)),h265:!!(!((aa=(ms=Ct())===null||ms===void 0?void 0:ms.isTypeSupported)===null||aa===void 0)&&aa.call(ms,ST)),vp9:!!(!((na=(vs=Ct())===null||vs===void 0?void 0:vs.isTypeSupported)===null||na===void 0)&&na.call(vs,Zu)),av1:!!(!((oa=(gs=Ct())===null||gs===void 0?void 0:gs.isTypeSupported)===null||oa===void 0)&&oa.call(gs,ed)),aac:!!(!((la=(Ss=Ct())===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||la===void 0)&&la.call(Ss,bT)),opus:!!(!((ua=(bs=Ct())===null||bs===void 0?void 0:bs.isTypeSupported)===null||ua===void 0)&&ua.call(bs,yT))},ki=(et.h264||et.h265)&&et.aac;var St;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(St||(St={}));var dt;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(dt||(dt={}));let Dt;const TT=()=>ee(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:ed})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Zu})}))]);Dt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{TT()}catch(i){console.error(i)}const Mi=_t.hls&&Oe.mp4,ET=()=>Object.keys(et).filter(i=>et[i]),$T=(i,e=!1,t=!1)=>{const s=_t.mse||_t.mms&&t;return i.filter(r=>{switch(r){case y.DASH_SEP:return s&&Oe.mp4&&ki;case y.DASH_WEBM:return s&&Oe.webm&&et.vp9&&et.opus;case y.DASH_WEBM_AV1:return s&&Oe.webm&&et.av1&&et.opus;case y.DASH_LIVE:return _t.mse&&Oe.mp4&&ki;case y.DASH_LIVE_CMAF:return s&&Oe.mp4&&ki&&Oe.cmaf;case y.DASH_ONDEMAND:return s&&Oe.mp4&&ki;case y.HLS:case y.HLS_ONDEMAND:return Mi||e&&_t.mse&&Oe.mp4&&ki;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Mi;case y.MPEG:return Oe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return _t.webrtc&&_t.ws&&et.h264&&(Oe.mp4||Oe.webm);default:return G(r)}})},Pi=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case St.VP9:return[e,t];case St.AV1:return[t,e];case St.NONE:return[];case St.SMOOTH:return Dt?Dt[t].smooth?[t,e]:Dt[e].smooth?[e,t]:[t,e]:[e,t];case St.POWER_EFFICIENT:return Dt?Dt[t].powerEfficient?[t,e]:Dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:G(i)}return[e,t]},wT=({webmCodec:i,androidPreferredFormat:e})=>{if(Xu)switch(e){case dt.MPEG:return[y.MPEG,...Pi(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case dt.HLS:return[y.HLS,y.HLS_ONDEMAND,...Pi(i),y.DASH_SEP,y.DASH_ONDEMAND,y.MPEG];case dt.DASH:return[...Pi(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Mi?[...Pi(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]:[...Pi(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},AT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(Xu)switch(i){case dt.DASH:{o=a;break}case dt.HLS:case dt.MPEG:{o=n;break}}else Mi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},hl=i=>i?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var kT=i=>new Ns(e=>{const t=new re,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:l,to:d})=>`${l}-${d}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(A(({type:l})=>l!==void 0)),n=new D;let o=0,u="unknown";return t.add(s.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const PT={chunkDuration:5e3,maxParallelRequests:5};class RT{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new D,this.noAvailableProvidersError$=new D,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),autoVideoTrackLimits$:new b(void 0),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new D,warning$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new b(void 0),isLowLatency$:new b(!1),canChangePlaybackSpeed$:new b(!0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),inPiP$:new b(!1),inFullscreen$:new b(!1),element$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=$T([...AT(this.params.tuning),...wT(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>P(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new cl(a);const n=[...hl(!0),...hl(!1)];this.chromecastFormatsIterator=new cl(n.filter(o=>P(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(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==z.None;if(this.params.desiredState.seekState.setState({state:z.Requested,position:r?s.position:t,forcePrecise:r?s.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 $e.SCREEN:return this.createScreenProvider(t);case $e.CHROMECAST:return this.createChromecastProvider(t);default:return G(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[y.HLS_ONDEMAND]||t[y.HLS]);return R(o),new rT(Object.assign(Object.assign({},n),{source:o,sourceHls:u}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new aT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),Mi||!this.params.tuning.useHlsJs?new cT(Object.assign(Object.assign({},n),{source:o})):new nT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new dT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new hT(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new ob(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},PT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new vT({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return G(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return R(o),new $S({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?$e.CHROMECAST:$e.SCREEN}chooseFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case $e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return G(e)}}skipFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.next();case $e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return G(e)}}handleNoFormatsError(e){switch(e){case $e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case $e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return G(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Ds(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,s=0;return e.add(F(this.providerOutput.error$,kT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(r=>({id:`ProviderHangup:${r}`,category:_.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(he(({to:a})=>a===p.PLAYING),Pe()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===$e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider($e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===_.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:$e.SCREEN)}})),e}}const IT=5e3,fl="one_video_throughput",pl="one_video_rtt",ct=window.navigator.connection,ml=()=>{const i=ct==null?void 0:ct.downlink;if(P(i)&&i!==10)return i*1e3},vl=()=>{const i=ct==null?void 0:ct.rtt;if(P(i)&&i!==3e3)return i},gl=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class _i{constructor(e){var t,s;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=_i.load(fl)||(e.useBrowserEstimation?ml():void 0)||IT,a=(s=(t=_i.load(pl))!==null&&t!==void 0?t:e.useBrowserEstimation?vl():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(gl(r,a,e.rttPenaltyRequestSize)),this.throughput=Na.getSmoothedValue(r,-1,e),this.rtt=Na.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=ml();u&&this.throughput.next(u);const l=vl();P(l)&&this.rtt.next(l)};ct&&"onchange"in ct&&this.subscription.add(x(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hr.set(fl,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hr.set(pl,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(it({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:n,rtt:o})=>gl(n,o,e.rttPenaltyRequestSize)),he(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=le();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(x(e,"progress").pipe(Pe()).subscribe(a=>{t=a.loaded,s=le()}));break;case 1:case 0:r.add(x(e,"loadstart").subscribe(()=>{t=0,s=le()}));break}r.add(x(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,l=o-s;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=d=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=({done:d,value:c})=>ee(this,void 0,void 0,function*(){if(d)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=le()}o=le()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());yield s==null?void 0:s.read().then(l,u)}});this.concurrentDownloads.add(e),s==null||s.read().then(l,u)}addRawSpeed(e,t,s=1,r=!1){if(_i.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=hr.get(e);if(P(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Sl={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,backgroundVideoQualityLimit:_e.Q_480P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:_e.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:St.VP9,androidPreferredFormat:dt.MPEG,preferCMAF:!1,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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},CT=i=>{var e;return Object.assign(Object.assign({},Pd(i,Sl)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Sl.configName]})};var bl=({seekState:i,position$:e})=>F(i.stateChangeEnded$.pipe(A(({to:t})=>{var s;return t.state===z.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),he(P)),e.pipe(he(()=>i.getState().state===z.None))),_T=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return R(e,`Wrong container or containerId {${i.container}}`),e};const DT=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(he(r=>r.length>0),Pe()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class BT{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Rd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ce(p.STOPPED),seekState:new ce({state:z.None}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({}),cameraOrientation:new ce({x:0,y:0})},this.info={playbackState$:new b(p.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),canChangePlaybackSpeed$:new b(void 0),atLiveEdge$:new b(void 0),atLiveDurationEdge$:new b(void 0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),surface$:new b(gt.NONE),chromecastState$:new b(be.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new D,ready$:new D,started$:new D,playing$:new D,paused$:new D,stopped$:new D,willStart$:new D,willResume$:new D,willPause$:new D,willStop$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D},this.experimental={element$:new b(void 0),tuningConfigName$:new b([]),enableDebugTelemetry$:new b(!1),dumpTelemetry:jS},this.initLogs(),this.tuning=CT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new _d({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _i(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),l=`Player.${String(s)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:_.WTF,message:d,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new RT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?x(document,"visibilitychange").pipe(Pe()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===be.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()===be.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){R(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(he(s=>s.length>0),Pe()).subscribe(s=>{this.setVideoTrackIdByQuality(s,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;R(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return DT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.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(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===z.None?void 0:t.position;return P(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e===p.STOPPED),Pe()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:z.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),fe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,u)=>Ot(o)?1:Ot(u)?-1:ui(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(fe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(fe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(fe()).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(A(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(it({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:u})=>{const l=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<l/1e3}),fe(),Di(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(it({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),fe(),Di(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),fe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),fe()).subscribe(this.info.volume$)).add(bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(F(e.providerOutput.endedEvent$.pipe(ks(!0)),e.providerOutput.seekedEvent$.pipe(ks(!1))).pipe(fe()).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(A(n=>({id:n?`No${n}`:"NoProviders",category:_.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(Pe(),A(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Pe(),A(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Pe(),A(()=>le()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n===p.PLAYING),Pe()).subscribe(()=>s.next(!1)));let r=0;const a=F(e.providerOutput.isBuffering$,t,s).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),fe());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(F(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 l=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:l==null?void 0:l.videoWidth,height:l==null?void 0:l.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(F(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(),l=this.chromecastInitializer.castState$.getValue();let d;l===be.CONNECTED?d=gt.SECOND_SCREEN:u?n?d=gt.PIP:o?d=gt.FULLSCREEN:d=gt.INLINE:d=gt.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(A(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 re;this.subscription.add(t),this.subscription.add(e.current$.pipe(fe((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(s=>s.length>0),Pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Js(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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(F(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),HS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>US(s)),this.providerContainer.current$.subscribe(({type:s})=>hs("provider",s)),t.duration$.subscribe(s=>hs("duration",s)),t.availableVideoTracks$.pipe(he(s=>!!s.length),Pe()).subscribe(s=>hs("tracks",s)),this.events.fatalError$.subscribe(new Xe("fatalError")),this.events.managedError$.subscribe(new Xe("managedError")),t.position$.subscribe(new Xe("position")),t.currentVideoTrack$.pipe(A(s=>s==null?void 0:s.quality)).subscribe(new Xe("quality")),this.info.currentBuffer$.subscribe(new Xe("buffer")),t.isBuffering$.subscribe(new Xe("isBuffering"))].forEach(s=>this.subscription.add(s)),hs("codecs",ET())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ee(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:_.DOM,message:String(r)})})});this.subscription.add(F(x(document,"visibilitychange"),x(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const NT=`@vkontakte/videoplayer-core@${Id}`;export{be as ChromecastState,ca as HttpConnectionType,UT as Observable,p as PlaybackState,BT as Player,NT as SDK_VERSION,HT as Subject,jT as Subscription,gt as Surface,Id as VERSION,GT as ValueSubject,y as VideoFormat,YT 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 iT{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,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 Xy(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zy(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"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(eT,this.gl.VERTEX_SHADER),s=this.createShader(tT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,l=e+s,d=t+r,c=e-s,h=t+r;return[a,n,o,u,l,d,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}}const sT=(i,e)=>new Ns(t=>{if(!window.IntersectionObserver)return;const s=()=>{var o;return!!(!((o=window.documentPictureInPicture)===null||o===void 0)&&o.window)||!!document.pictureInPictureElement},r={root:null},a=new IntersectionObserver((o,u)=>{o.forEach(l=>t.next(l.isIntersecting||s()))},Object.assign(Object.assign({},r),e));a.observe(i);const n=x(document,"visibilitychange").pipe(w(o=>!document.hidden||s())).subscribe(o=>t.next(o));return()=>{a.unobserve(i),n.unsubscribe}});class Ju{constructor(e){this.subscription=new re,this.videoState=new ce(oe.STOPPED),this.elementSize$=new b(void 0),this.elementVisible$=new b(!0),this.textTracksManager=new Et,this.droppedFramesManager=new Fu,this.videoTracks$=new b([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new qS,this.textTracks=[],this.syncPlayback=()=>{var t,s,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===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==oe.STOPPED&&n!==p.STOPPED){const d=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-d,u.forcePrecise)}if(n===p.STOPPED){a!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case oe.STOPPED:this.videoState.startTransitionTo(oe.READY),this.prepare();return;case oe.READY:n===p.PAUSED?(this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.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)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return j(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new iT(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.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=Ut(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(st(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Jy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=Gt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:_.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,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$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(w(l=>l.map(({track:d})=>d)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(he(k),Pe()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qi(this.video,t.isLooped,r)),this.subscription.add(jt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Si(this.video,t.playbackRate,s.playbackRateState$,r)),a(ub(this.video),this.elementSize$),a(sT(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var d;if(l===Me.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();R(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=Fy(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of v){const E=Ny(S);if(E){c.push({track:E,representation:S});const $=!this.params.tuning.isAudioDisabled&&Vy(f,v,S);$&&this.audioRepresentations.set(S.id,$)}}this.videoTracks$.next(c);for(const S of m){const E=Uy(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();R(g),this.player.initRepresentations(g.id,(d=this.audioRepresentations.get(g.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else l===Me.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},r));const n=l=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(F(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,x(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==Me.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=Ot(S),$=Ot(c);if(E&&$)return Ps(E,$)&&Ps(E,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(ye.VIDEO,m).catch(n);const g=this.audioRepresentations.get(c.id);g&&this.player.switchRepresentation(ye.AUDIO,g.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(fe(),w(l=>{var d;return l&&((d=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===l))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&(!((d=this.params.tuning.spherical)===null||d===void 0)&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider 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(w(({to:l})=>l===p.READY),fe());this.subscription.add(F(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(F(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),l=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,d=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===l))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=li(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!u&&(r=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.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),g=Js(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:d:d!=null?d:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Yt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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),Ht(this.video)}}class rT extends Ju{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class aT extends Ju{constructor(e){super(e),this.liveOffset=new hn}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(it({interval:Rs(Ba),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===oe.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(it({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({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(),s=this.videoState.getState(),r=t===p.PAUSED&&s===oe.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 Ke={};var W;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const ki=(i,e)=>new Ns(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class nT{constructor(e){this.subscription=new re,this.videoState=new ce(W.INITIALIZING),this.textTracksManager=new Et,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==W.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:j(t)}break;case p.READY:switch(t){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:j(t)}break;case p.PLAYING:switch(t){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:j(t)}break;case p.PAUSED:switch(t){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case W.PLAYING:this.pause();break;default:j(t)}break;default:j(s)}},this.video=Ut(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(st(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),Ht(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);dn(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){R(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){R(Ke.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=l=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Gt(this.video),a=(l,d)=>this.subscription.add(l.subscribe(d,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(qi(this.video,e.isLooped,s)),this.subscription.add(jt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Si(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ki(this.hls,Ke.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)===null||d===void 0?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),a(ki(this.hls,Ke.Events.MANIFEST_PARSED).pipe(w(({levels:l})=>l.reduce((d,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:m,height:g}=c,S=(f=Ks((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Ot({width:m,height:g});if(!S)return d;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,$={id:v.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:g},fps:E};return this.trackLevels.set(v,{track:$,level:c}),d.push($),d},[]))),t.availableVideoTracks$),a(ki(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){const d=[];for(const c of l.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,m="internal";d.push({id:h,url:f,language:v,type:m})}e.internalTextTracks.startTransitionTo(d)}}),a(ki(this.hls,Ke.Events.LEVEL_LOADING).pipe(w(({url:l})=>st(l))),t.hostname$),this.subscription.add(ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:s}));const n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))===null||d===void 0?void 0:d.track},o=ki(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(w(({level:l})=>n(this.hls.levels[l])));o.pipe(he(k)).subscribe(t.currentVideoTrack$,s),this.subscription.add(ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var d;if(K(l))return;const c=(d=this.trackLevels.get(l.id))===null||d===void 0?void 0:d.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=F(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ee(this,void 0,void 0,function*(){this.videoState.startTransitionTo(W.PLAYING),(yield Yt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:t})))||(this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(W.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(W.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const ll="X-Playback-Duration";var ul=i=>ee(void 0,void 0,void 0,function*(){var e;const t=yield Mi(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(ll)?parseInt(t.headers.get(ll),10):void 0});const oT=i=>{let e=null;if(i.QUALITY&&(e=Ks(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ot({width:t,height:s})}return e!=null?e:null},lT=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
+
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){const c=Ds(l[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=oT(c);let v;c.BANDWIDTH&&(v=parseInt(c.BANDWIDTH,10)/1e3||void 0),!v&&c["AVERAGE-BANDWIDTH"]&&(v=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let g;if(c.RESOLUTION){const[E,$]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));E&&$&&(g={width:E,height:$})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:v,size:g,fps:m})}if(d){const c=Ds(d[1].split(",").map(m=>m.split("=")).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,v=c.NAME;h&&f&&n.push({type:"internal",id:f,label:v,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},uT=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Xr=0;const gn=(i,e=i,t)=>ee(void 0,void 0,void 0,function*(){const r=yield(yield Mi(i)).text();Xr+=1;try{const{qualityManifests:a,textTracks:n}=lT(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(Xr<=t.manifestRetryMaxCount)return yield uT(Ts(Xr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gn(i,e,t)}return{qualityManifests:[],textTracks:[]}});var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class dT{constructor(e){var t;this.subscription=new re,this.videoState=new ce(ie.STOPPED),this.textTracksManager=new Et,this.manifests$=new b([]),this.liveOffset=new hn,this.manifestStartTime$=new b(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(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u||l){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return j(r)}},this.params=e,this.video=Ut(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_e.INVARIANT,url:this.params.source.url},gn(Ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(st(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Gt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(jt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Si(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(fe(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&k(l.to)){const c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(st(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,l;const d=(l=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||l===void 0?void 0:l.getTime();this.manifestStartTime$.next(d||void 0)},s)),this.subscription.add(it({startTime:this.manifestStartTime$.pipe(he(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ht(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[l,"mq"],[d,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===y.HLS_LIVE_CMAF?ge.DASH_CMAF_OFFSET_P:ge.OFFSET_P,u=Ye(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),ul(u).then(l=>{var d;if(!K(l))this.maxSeekBackTime$.next(l);else{const c=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(K(c)||!isFinite(c))try{Mi(u).then(h=>h.text()).then(h=>{var f;const v=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(v){const m=new URL(v,u).toString();ul(m).then(g=>{K(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Yt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ne||(ne={}));class cT{constructor(e){this.subscription=new re,this.videoState=new ce(ne.STOPPED),this.textTracksManager=new Et,this.manifests$=new b([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===Y.Requested&&this.seek(d.position),s){case ne.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return j(s)}},this.params=e,this.video=Ut(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_e.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(st(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gn(Ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Gt(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(qi(this.video,t.isLooped,s)),this.subscription.add(jt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Si(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const f=this.manifests$.getValue().find(v=>v.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(st(f.url));const v=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(v!==m){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(v),g.playbackRate=v)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from===ne.CHANGING_MANIFEST&&this.videoState.setState(l.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!Ad()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(F(x(o,"addtrack"),x(o,"removetrack"),x(o,"change"),Ne(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ht(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.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[l,d]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(l||""));d&&l&&n.searchParams.set(d,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Yt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));class hT{constructor(e){this.subscription=new re,this.videoState=new ce(de.STOPPED),this.trackUrls={},this.textTracksManager=new Et,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.autoVideoTrackLimits.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(l&&a!==de.READY&&!d){this.handleQualityLimitTransition(l.to.max);return}if(a===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(d){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[d.to.id])===null||s===void 0?void 0:s.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)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),a){case de.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return j(a)}},this.params=e,this.video=Ut(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Gt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(qi(this.video,t.isLooped,s)),this.subscription.add(jt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Si(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY);const l=this.params.desiredState.videoTrack.getTransition();if(l&&k(l.to)){this.params.desiredState.videoTrack.setState(l.to),this.params.output.currentVideoTrack$.next(this.trackUrls[l.to.id].track);const d=this.params.desiredState.playbackRate.getState(),c=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(d!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ht(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;R(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];R(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Ma(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(st(s))}playIfAllowed(){Yt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,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=(s=Object.values(this.trackUrls).find(c=>!Mt(c.track.quality)&&Ps(c.track.quality,e)))===null||s===void 0?void 0:s.track,l=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,d=(a=this.trackUrls[l!=null?l:"0"])===null||a===void 0?void 0:a.track;if(u&&d&&da(d.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Mt(f.track.quality)&&di(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(l=>l.track);n=Js(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 dl=["stun:videostun.mycdn.me:80"],fT=1e3,pT=3,Zr=()=>null;class mT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ee(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 ee(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:dl}]};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 ee(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 ee(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:_.WTF,message:e.message})}onPeerConnectionStream(e){return ee(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 ee(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),fT)}normalizeOptions(e={}){const t={stunServerList:dl,maxRetryNumber:pT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class vT{constructor(e){this.videoState=new ce(se.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:s===p.PAUSED?(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return j(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ut(e.container),this.liveStreamClient=new mT(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),Ht(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};F(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Gt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),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)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(jt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return j(n.to)}},s)).add(F(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(tt(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(st(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:_e.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Yt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class cl{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 ea,ta,ia,sa,ps,ra,ms,aa,vs,na,gs,oa,Ss,la,bs,ua;const Xu=Fa().device===kd.Android,bt=document.createElement("video"),gT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ST='video/mp4; codecs="hev1.1.6.L93.B0"',Zu='video/webm; codecs="vp09.00.10.08"',ed='video/webm; codecs="av01.0.00M.08"',bT='audio/mp4; codecs="mp4a.40.2"',yT='audio/webm; codecs="opus"',_t={mms:Ku(),mse:Qy(),hls:!!(!((ea=bt.canPlayType)===null||ea===void 0)&&ea.call(bt,"application/x-mpegurl")||!((ta=bt.canPlayType)===null||ta===void 0)&&ta.call(bt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Oe={mp4:!!(!((ia=bt.canPlayType)===null||ia===void 0)&&ia.call(bt,"video/mp4")),webm:!!(!((sa=bt.canPlayType)===null||sa===void 0)&&sa.call(bt,"video/webm")),cmaf:!0},et={h264:!!(!((ra=(ps=Ct())===null||ps===void 0?void 0:ps.isTypeSupported)===null||ra===void 0)&&ra.call(ps,gT)),h265:!!(!((aa=(ms=Ct())===null||ms===void 0?void 0:ms.isTypeSupported)===null||aa===void 0)&&aa.call(ms,ST)),vp9:!!(!((na=(vs=Ct())===null||vs===void 0?void 0:vs.isTypeSupported)===null||na===void 0)&&na.call(vs,Zu)),av1:!!(!((oa=(gs=Ct())===null||gs===void 0?void 0:gs.isTypeSupported)===null||oa===void 0)&&oa.call(gs,ed)),aac:!!(!((la=(Ss=Ct())===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||la===void 0)&&la.call(Ss,bT)),opus:!!(!((ua=(bs=Ct())===null||bs===void 0?void 0:bs.isTypeSupported)===null||ua===void 0)&&ua.call(bs,yT))},Pi=(et.h264||et.h265)&&et.aac;var St;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(St||(St={}));var dt;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(dt||(dt={}));let Dt;const TT=()=>ee(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:ed})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Zu})}))]);Dt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{TT()}catch(i){console.error(i)}const Bi=_t.hls&&Oe.mp4,ET=()=>Object.keys(et).filter(i=>et[i]),$T=(i,e=!1,t=!1)=>{const s=_t.mse||_t.mms&&t;return i.filter(r=>{switch(r){case y.DASH_SEP:return s&&Oe.mp4&Πcase y.DASH_WEBM:return s&&Oe.webm&&et.vp9&&et.opus;case y.DASH_WEBM_AV1:return s&&Oe.webm&&et.av1&&et.opus;case y.DASH_LIVE:return _t.mse&&Oe.mp4&Πcase y.DASH_LIVE_CMAF:return s&&Oe.mp4&&Pi&&Oe.cmaf;case y.DASH_ONDEMAND:return s&&Oe.mp4&Πcase y.HLS:case y.HLS_ONDEMAND:return Bi||e&&_t.mse&&Oe.mp4&Πcase y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Bi;case y.MPEG:return Oe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return _t.webrtc&&_t.ws&&et.h264&&(Oe.mp4||Oe.webm);default:return j(r)}})},Ri=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case St.VP9:return[e,t];case St.AV1:return[t,e];case St.NONE:return[];case St.SMOOTH:return Dt?Dt[t].smooth?[t,e]:Dt[e].smooth?[e,t]:[t,e]:[e,t];case St.POWER_EFFICIENT:return Dt?Dt[t].powerEfficient?[t,e]:Dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:j(i)}return[e,t]},wT=({webmCodec:i,androidPreferredFormat:e})=>{if(Xu)switch(e){case dt.MPEG:return[y.MPEG,...Ri(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case dt.HLS:return[y.HLS,y.HLS_ONDEMAND,...Ri(i),y.DASH_SEP,y.DASH_ONDEMAND,y.MPEG];case dt.DASH:return[...Ri(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Bi?[...Ri(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]:[...Ri(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},AT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(Xu)switch(i){case dt.DASH:{o=a;break}case dt.HLS:case dt.MPEG:{o=n;break}}else Bi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},hl=i=>i?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var kT=i=>new Ns(e=>{const t=new re,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:l,to:d})=>`${l}-${d}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(w(({type:l})=>l!==void 0)),n=new D;let o=0,u="unknown";return t.add(s.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const PT={chunkDuration:5e3,maxParallelRequests:5};class RT{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new D,this.noAvailableProvidersError$=new D,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),autoVideoTrackLimits$:new b(void 0),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new D,warning$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new b(void 0),isLowLatency$:new b(!1),canChangePlaybackSpeed$:new b(!0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),inPiP$:new b(!1),inFullscreen$:new b(!1),element$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=$T([...AT(this.params.tuning),...wT(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>k(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new cl(a);const n=[...hl(!0),...hl(!1)];this.chromecastFormatsIterator=new cl(n.filter(o=>k(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.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 $e.SCREEN:return this.createScreenProvider(t);case $e.CHROMECAST:return this.createChromecastProvider(t);default:return j(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[y.HLS_ONDEMAND]||t[y.HLS]);return R(o),new rT(Object.assign(Object.assign({},n),{source:o,sourceHls:u}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new aT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),Bi||!this.params.tuning.useHlsJs?new cT(Object.assign(Object.assign({},n),{source:o})):new nT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new dT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new hT(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new ob(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},PT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new vT({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return j(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return R(o),new $S({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?$e.CHROMECAST:$e.SCREEN}chooseFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case $e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return j(e)}}skipFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.next();case $e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return j(e)}}handleNoFormatsError(e){switch(e){case $e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case $e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return j(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Ds(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,s=0;return e.add(F(this.providerOutput.error$,kT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:_.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(he(({to:a})=>a===p.PLAYING),Pe()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===$e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider($e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===_.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:$e.SCREEN)}})),e}}const IT=5e3,fl="one_video_throughput",pl="one_video_rtt",ct=window.navigator.connection,ml=()=>{const i=ct==null?void 0:ct.downlink;if(k(i)&&i!==10)return i*1e3},vl=()=>{const i=ct==null?void 0:ct.rtt;if(k(i)&&i!==3e3)return i},gl=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Di{constructor(e){var t,s;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Di.load(fl)||(e.useBrowserEstimation?ml():void 0)||IT,a=(s=(t=Di.load(pl))!==null&&t!==void 0?t:e.useBrowserEstimation?vl():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(gl(r,a,e.rttPenaltyRequestSize)),this.throughput=Na.getSmoothedValue(r,-1,e),this.rtt=Na.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=ml();u&&this.throughput.next(u);const l=vl();k(l)&&this.rtt.next(l)};ct&&"onchange"in ct&&this.subscription.add(x(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hr.set(fl,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hr.set(pl,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(it({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>gl(n,o,e.rttPenaltyRequestSize)),he(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=le();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(x(e,"progress").pipe(Pe()).subscribe(a=>{t=a.loaded,s=le()}));break;case 1:case 0:r.add(x(e,"loadstart").subscribe(()=>{t=0,s=le()}));break}r.add(x(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,l=o-s;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=d=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=({done:d,value:c})=>ee(this,void 0,void 0,function*(){if(d)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=le()}o=le()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());yield s==null?void 0:s.read().then(l,u)}});this.concurrentDownloads.add(e),s==null||s.read().then(l,u)}addRawSpeed(e,t,s=1,r=!1){if(Di.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=hr.get(e);if(k(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Sl={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,backgroundVideoQualityLimit:_e.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:_e.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:St.VP9,androidPreferredFormat:dt.MPEG,preferCMAF:!1,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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},CT=i=>{var e;return Object.assign(Object.assign({},Pd(i,Sl)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Sl.configName]})};var bl=({seekState:i,position$:e})=>F(i.stateChangeEnded$.pipe(w(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),he(k)),e.pipe(he(()=>i.getState().state===Y.None))),_T=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return R(e,`Wrong container or containerId {${i.container}}`),e};const DT=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(he(r=>r.length>0),Pe()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class BT{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Rd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ce(p.STOPPED),seekState:new ce({state:Y.None}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({}),cameraOrientation:new ce({x:0,y:0})},this.info={playbackState$:new b(p.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),canChangePlaybackSpeed$:new b(void 0),atLiveEdge$:new b(void 0),atLiveDurationEdge$:new b(void 0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),surface$:new b(gt.NONE),chromecastState$:new b(be.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new D,ready$:new D,started$:new D,playing$:new D,paused$:new D,stopped$:new D,willStart$:new D,willResume$:new D,willPause$:new D,willStop$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D},this.experimental={element$:new b(void 0),tuningConfigName$:new b([]),enableDebugTelemetry$:new b(!1),dumpTelemetry:jS},this.initLogs(),this.tuning=CT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new _d({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Di(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),l=`Player.${String(s)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:_.WTF,message:d,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new RT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?x(document,"visibilitychange").pipe(Pe()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.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()===be.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()===be.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){R(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(he(s=>s.length>0),Pe()).subscribe(s=>{this.setVideoTrackIdByQuality(s,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;R(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return DT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.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(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return k(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e===p.STOPPED),Pe()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:Y.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(n=>n.destination),fe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>Mt(o)?1:Mt(u)?-1:di(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(fe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(fe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(fe()).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(w(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(it({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:u})=>{const l=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<l/1e3}),fe(),Li(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(it({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),fe(),Li(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),fe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),fe()).subscribe(this.info.volume$)).add(bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(F(e.providerOutput.endedEvent$.pipe(ks(!0)),e.providerOutput.seekedEvent$.pipe(ks(!1))).pipe(fe()).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(w(n=>({id:n?`No${n}`:"NoProviders",category:_.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(Pe(),w(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Pe(),w(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Pe(),w(()=>le()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n===p.PLAYING),Pe()).subscribe(()=>s.next(!1)));let r=0;const a=F(e.providerOutput.isBuffering$,t,s).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),fe());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(F(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 l=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:l==null?void 0:l.videoWidth,height:l==null?void 0:l.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(F(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(),l=this.chromecastInitializer.castState$.getValue();let d;l===be.CONNECTED?d=gt.SECOND_SCREEN:u?n?d=gt.PIP:o?d=gt.FULLSCREEN:d=gt.INLINE:d=gt.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(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 re;this.subscription.add(t),this.subscription.add(e.current$.pipe(fe((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(s=>s.length>0),Pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Js(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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(F(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),HS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>US(s)),this.providerContainer.current$.subscribe(({type:s})=>hs("provider",s)),t.duration$.subscribe(s=>hs("duration",s)),t.availableVideoTracks$.pipe(he(s=>!!s.length),Pe()).subscribe(s=>hs("tracks",s)),this.events.fatalError$.subscribe(new Xe("fatalError")),this.events.managedError$.subscribe(new Xe("managedError")),t.position$.subscribe(new Xe("position")),t.currentVideoTrack$.pipe(w(s=>s==null?void 0:s.quality)).subscribe(new Xe("quality")),this.info.currentBuffer$.subscribe(new Xe("buffer")),t.isBuffering$.subscribe(new Xe("isBuffering"))].forEach(s=>this.subscription.add(s)),hs("codecs",ET())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ee(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:_.DOM,message:String(r)})})});this.subscription.add(F(x(document,"visibilitychange"),x(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const NT=`@vkontakte/videoplayer-core@${Id}`;export{be as ChromecastState,ca as HttpConnectionType,UT as Observable,p as PlaybackState,BT as Player,NT as SDK_VERSION,HT as Subject,jT as Subscription,gt as Surface,Id as VERSION,GT as ValueSubject,y as VideoFormat,YT as VideoQuality};
|