@vkontakte/videoplayer-core 2.0.95 → 2.0.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- 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.96
|
|
3
|
+
* Wed, 13 Dec 2023 12:11:59 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as S,Subject as x,Subscription as ae,isNonNullable as k,ErrorCategory as L,isNullable as ie,fromEvent as B,assertNever as H,merge as V,tap as Is,map as w,observableFrom as De,filterChanged as ve,assertNonNullable as P,debounce as je,getHighestQuality as Tl,timeout as El,getCurrentBrowser as Ua,CurrentClientBrowser as yd,combine as Ne,once as ge,mapTo as ui,filter as re,now as me,videoSizeToQuality as Vt,isInvariantQuality as Oi,isHigher as Ii,isLower as ws,isHigherOrEqual as pa,isLowerOrEqual as Td,Observable as Hs,interval as Cs,VideoQuality as He,videoQualityToHeight as $l,abortable as Oe,getExponentialDelay as kn,throttle as Al,CurrentClientDevice as _l,safeStorage as vr,fillWithDefault as wl,Logger as kl}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as BT,Subject as NT,Subscription as FT,ValueSubject as UT,VideoQuality as VT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Pl from"lodash/debounce.js";const Rl="2.0.95";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var we;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(we||(we={}));var $e;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})($e||($e={}));var Mi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Mi||(Mi={}));var W;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(W||(W={}));var At;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(At||(At={}));function ue(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function M(s){return this instanceof M?(this.v=s,this):new M(s)}function Me(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(v,g){a.push([h,f,v,g])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(v){c(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Dl=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Il{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S($e.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new S($e.NOT_AVAILABLE),this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=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||Dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();ie(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();ie(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return H(r.sessionState)}})).add(V(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Is(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),De([i.getCastState()])).pipe(ve(),w(Cl),Is(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===$e.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(ie(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===$e.CONNECTED?k(this.connection$.getValue())?$e.CONNECTED:$e.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Cl=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return $e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return $e.AVAILABLE;case cast.framework.CastState.CONNECTING:return $e.CONNECTING;case cast.framework.CastState.CONNECTED:return $e.CONNECTED;default:return H(s)}};var mr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Gs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qe=function(s){try{return!!s()}catch(e){return!0}},xl=qe,Ys=!xl(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ed=Ys,$d=Function.prototype,va=$d.call,Ll=Ed&&$d.bind.bind(va,va),ze=Ed?Ll:function(s){return function(){return va.apply(s,arguments)}},Ad=ze,Ol=Ad({}.toString),Ml=Ad("".slice),Vi=function(s){return Ml(Ol(s),8,-1)},Bl=ze,Nl=qe,Fl=Vi,gr=Object,Ul=Bl("".split),Vl=Nl(function(){return!gr("z").propertyIsEnumerable(0)})?function(s){return Fl(s)=="String"?Ul(s,""):gr(s)}:gr,Hi=function(s){return s==null},Hl=Hi,Gl=TypeError,Va=function(s){if(Hl(s))throw Gl("Can't call method on "+s);return s},Yl=Vl,jl=Va,Gi=function(s){return Yl(jl(s))},pi={},ss=function(s){return s&&s.Math==Math&&s},_e=ss(typeof globalThis=="object"&&globalThis)||ss(typeof window=="object"&&window)||ss(typeof self=="object"&&self)||ss(typeof mr=="object"&&mr)||function(){return this}()||mr||Function("return this")(),ma=typeof document=="object"&&document.all,ql=typeof ma=="undefined"&&ma!==void 0,_d={all:ma,IS_HTMLDDA:ql},wd=_d,zl=wd.all,Ee=wd.IS_HTMLDDA?function(s){return typeof s=="function"||s===zl}:function(s){return typeof s=="function"},Wl=_e,Ql=Ee,Pn=Wl.WeakMap,Kl=Ql(Pn)&&/native code/.test(String(Pn)),Rn=Ee,kd=_d,Jl=kd.all,vt=kd.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Rn(s)||s===Jl}:function(s){return typeof s=="object"?s!==null:Rn(s)},Xl=qe,Rt=!Xl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ht={},Zl=_e,Dn=vt,ga=Zl.document,ec=Dn(ga)&&Dn(ga.createElement),Ha=function(s){return ec?ga.createElement(s):{}},tc=Rt,ic=qe,sc=Ha,Pd=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Rt,ac=qe,Rd=rc&&ac(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),nc=vt,oc=String,dc=TypeError,mt=function(s){if(nc(s))return s;throw dc(oc(s)+" is not an object")},uc=Ys,rs=Function.prototype.call,Fe=uc?rs.bind(rs):function(){return rs.apply(rs,arguments)},Ga={},Sr=Ga,br=_e,lc=Ee,In=function(s){return lc(s)?s:void 0},Gt=function(s,e){return arguments.length<2?In(Sr[s])||In(br[s]):Sr[s]&&Sr[s][e]||br[s]&&br[s][e]},cc=ze,js=cc({}.isPrototypeOf),qs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Dd=_e,yr=qs,Cn=Dd.process,xn=Dd.Deno,Ln=Cn&&Cn.versions||xn&&xn.version,On=Ln&&Ln.v8,Ke,xs;On&&(Ke=On.split("."),xs=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!xs&&yr&&(Ke=yr.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=yr.match(/Chrome\/(\d+)/),Ke&&(xs=+Ke[1])));var Id=xs,Mn=Id,hc=qe,fc=_e,pc=fc.String,Cd=!!Object.getOwnPropertySymbols&&!hc(function(){var s=Symbol();return!pc(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mn&&Mn<41}),vc=Cd,xd=vc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",mc=Gt,gc=Ee,Sc=js,bc=xd,yc=Object,Ld=bc?function(s){return typeof s=="symbol"}:function(s){var e=mc("Symbol");return gc(e)&&Sc(e.prototype,yc(s))},Tc=String,zs=function(s){try{return Tc(s)}catch(e){return"Object"}},Ec=Ee,$c=zs,Ac=TypeError,Yt=function(s){if(Ec(s))return s;throw Ac($c(s)+" is not a function")},_c=Yt,wc=Hi,Ws=function(s,e){var t=s[e];return wc(t)?void 0:_c(t)},Tr=Fe,Er=Ee,$r=vt,kc=TypeError,Pc=function(s,e){var t,i;if(e==="string"&&Er(t=s.toString)&&!$r(i=Tr(t,s))||Er(t=s.valueOf)&&!$r(i=Tr(t,s))||e!=="string"&&Er(t=s.toString)&&!$r(i=Tr(t,s)))return i;throw kc("Can't convert object to primitive value")},Od={exports:{}},Rc=!0,Bn=_e,Dc=Object.defineProperty,Ic=function(s,e){try{Dc(Bn,s,{value:e,configurable:!0,writable:!0})}catch(t){Bn[s]=e}return e},Cc=_e,xc=Ic,Nn="__core-js_shared__",Lc=Cc[Nn]||xc(Nn,{}),Ya=Lc,Fn=Ya;(Od.exports=function(s,e){return Fn[s]||(Fn[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Md=Od.exports,Oc=Va,Mc=Object,Qs=function(s){return Mc(Oc(s))},Bc=ze,Nc=Qs,Fc=Bc({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return Fc(Nc(e),t)},Uc=ze,Vc=0,Hc=Math.random(),Gc=Uc(1 .toString),Bd=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Gc(++Vc+Hc,36)},Yc=_e,jc=Md,Un=ot,qc=Bd,zc=Cd,Wc=xd,si=Yc.Symbol,Ar=jc("wks"),Qc=Wc?si.for||si:si&&si.withoutSetter||qc,Pe=function(s){return Un(Ar,s)||(Ar[s]=zc&&Un(si,s)?si[s]:Qc("Symbol."+s)),Ar[s]},Kc=Fe,Vn=vt,Hn=Ld,Jc=Ws,Xc=Pc,Zc=Pe,eh=TypeError,th=Zc("toPrimitive"),ih=function(s,e){if(!Vn(s)||Hn(s))return s;var t=Jc(s,th),i;if(t){if(e===void 0&&(e="default"),i=Kc(t,s,e),!Vn(i)||Hn(i))return i;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(s,e)},sh=ih,rh=Ld,ja=function(s){var e=sh(s,"string");return rh(e)?e:e+""},ah=Rt,nh=Pd,oh=Rd,as=mt,Gn=ja,dh=TypeError,_r=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,wr="enumerable",kr="configurable",Pr="writable";Ht.f=ah?oh?function(e,t,i){if(as(e),t=Gn(t),as(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pr in i&&!i[Pr]){var r=uh(e,t);r&&r[Pr]&&(e[t]=i.value,i={configurable:kr in i?i[kr]:r[kr],enumerable:wr in i?i[wr]:r[wr],writable:!1})}return _r(e,t,i)}:_r:function(e,t,i){if(as(e),t=Gn(t),as(i),nh)try{return _r(e,t,i)}catch(r){}if("get"in i||"set"in i)throw dh("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ks=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},lh=Rt,ch=Ht,hh=Ks,Yi=lh?function(s,e,t){return ch.f(s,e,hh(1,t))}:function(s,e,t){return s[e]=t,s},fh=Md,ph=Bd,Yn=fh("keys"),qa=function(s){return Yn[s]||(Yn[s]=ph(s))},za={},vh=Kl,Nd=_e,mh=vt,gh=Yi,Rr=ot,Dr=Ya,Sh=qa,bh=za,jn="Object already initialized",Sa=Nd.TypeError,yh=Nd.WeakMap,Ls,Bi,Os,Th=function(s){return Os(s)?Bi(s):Ls(s,{})},Eh=function(s){return function(e){var t;if(!mh(e)||(t=Bi(e)).type!==s)throw Sa("Incompatible receiver, "+s+" required");return t}};if(vh||Dr.state){var tt=Dr.state||(Dr.state=new yh);tt.get=tt.get,tt.has=tt.has,tt.set=tt.set,Ls=function(s,e){if(tt.has(s))throw Sa(jn);return e.facade=s,tt.set(s,e),e},Bi=function(s){return tt.get(s)||{}},Os=function(s){return tt.has(s)}}else{var Jt=Sh("state");bh[Jt]=!0,Ls=function(s,e){if(Rr(s,Jt))throw Sa(jn);return e.facade=s,gh(s,Jt,e),e},Bi=function(s){return Rr(s,Jt)?s[Jt]:{}},Os=function(s){return Rr(s,Jt)}}var Fd={set:Ls,get:Bi,has:Os,enforce:Th,getterFor:Eh},$h=Ys,Ud=Function.prototype,qn=Ud.apply,zn=Ud.call,Vd=typeof Reflect=="object"&&Reflect.apply||($h?zn.bind(qn):function(){return zn.apply(qn,arguments)}),Ah=Vi,_h=ze,Hd=function(s){if(Ah(s)==="Function")return _h(s)},Wa={},Gd={},Yd={}.propertyIsEnumerable,jd=Object.getOwnPropertyDescriptor,wh=jd&&!Yd.call({1:2},1);Gd.f=wh?function(e){var t=jd(this,e);return!!t&&t.enumerable}:Yd;var kh=Rt,Ph=Fe,Rh=Gd,Dh=Ks,Ih=Gi,Ch=ja,xh=ot,Lh=Pd,Wn=Object.getOwnPropertyDescriptor;Wa.f=kh?Wn:function(e,t){if(e=Ih(e),t=Ch(t),Lh)try{return Wn(e,t)}catch(i){}if(xh(e,t))return Dh(!Ph(Rh.f,e,t),e[t])};var Oh=qe,Mh=Ee,Bh=/#|\.prototype\./,ji=function(s,e){var t=Fh[Nh(s)];return t==Vh?!0:t==Uh?!1:Mh(e)?Oh(e):!!e},Nh=ji.normalize=function(s){return String(s).replace(Bh,".").toLowerCase()},Fh=ji.data={},Uh=ji.NATIVE="N",Vh=ji.POLYFILL="P",qd=ji,Qn=Hd,Hh=Yt,Gh=Ys,Yh=Qn(Qn.bind),Js=function(s,e){return Hh(s),e===void 0?s:Gh?Yh(s,e):function(){return s.apply(e,arguments)}},ns=_e,jh=Vd,qh=Hd,zh=Ee,Wh=Wa.f,Qh=qd,Xt=Ga,Kh=Js,Zt=Yi,Kn=ot,Jh=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return jh(s,this,arguments)};return e.prototype=s.prototype,e},Ze=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ns:r?ns[t]:(ns[t]||{}).prototype,o=i?Xt:Xt[t]||Zt(Xt,t,{})[t],u=o.prototype,d,l,c,h,f,v,g,T,A;for(h in e)d=Qh(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Kn(n,h),v=o[h],l&&(s.dontCallGetSet?(A=Wh(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof v==typeof f)&&(s.bind&&l?T=Kh(f,ns):s.wrap&&l?T=Jh(f):a&&zh(f)?T=qh(f):T=f,(s.sham||f&&f.sham||v&&v.sham)&&Zt(T,"sham",!0),Zt(o,h,T),a&&(c=t+"Prototype",Kn(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],h,f),s.real&&u&&(d||!u[h])&&Zt(u,h,f)))},ba=Rt,Xh=ot,zd=Function.prototype,Zh=ba&&Object.getOwnPropertyDescriptor,Qa=Xh(zd,"name"),ef=Qa&&function(){}.name==="something",tf=Qa&&(!ba||ba&&Zh(zd,"name").configurable),sf={EXISTS:Qa,PROPER:ef,CONFIGURABLE:tf},Wd={},rf=Math.ceil,af=Math.floor,nf=Math.trunc||function(e){var t=+e;return(t>0?af:rf)(t)},of=nf,Ka=function(s){var e=+s;return e!==e||e===0?0:of(e)},df=Ka,uf=Math.max,lf=Math.min,cf=function(s,e){var t=df(s);return t<0?uf(t+e,0):lf(t,e)},hf=Ka,ff=Math.min,pf=function(s){return s>0?ff(hf(s),9007199254740991):0},vf=pf,Ja=function(s){return vf(s.length)},mf=Gi,gf=cf,Sf=Ja,Jn=function(s){return function(e,t,i){var r=mf(e),a=Sf(r),n=gf(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},bf={includes:Jn(!0),indexOf:Jn(!1)},yf=ze,Ir=ot,Tf=Gi,Ef=bf.indexOf,$f=za,Xn=yf([].push),Af=function(s,e){var t=Tf(s),i=0,r=[],a;for(a in t)!Ir($f,a)&&Ir(t,a)&&Xn(r,a);for(;e.length>i;)Ir(t,a=e[i++])&&(~Ef(r,a)||Xn(r,a));return r},Qd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_f=Af,wf=Qd,kf=Object.keys||function(e){return _f(e,wf)},Pf=Rt,Rf=Rd,Df=Ht,If=mt,Cf=Gi,xf=kf;Wd.f=Pf&&!Rf?Object.defineProperties:function(e,t){If(e);for(var i=Cf(t),r=xf(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],i[o]);return e};var Lf=Gt,Kd=Lf("document","documentElement"),Of=mt,Mf=Wd,Zn=Qd,Bf=za,Nf=Kd,Ff=Ha,Uf=qa,eo=">",to="<",ya="prototype",Ta="script",Jd=Uf("IE_PROTO"),Cr=function(){},Xd=function(s){return to+Ta+eo+s+to+"/"+Ta+eo},io=function(s){s.write(Xd("")),s.close();var e=s.parentWindow.Object;return s=null,e},Vf=function(){var s=Ff("iframe"),e="java"+Ta+":",t;return s.style.display="none",Nf.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Xd("document.F=Object")),t.close(),t.F},os,ks=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&os?io(os):Vf():io(os);for(var s=Zn.length;s--;)delete ks[ya][Zn[s]];return ks()};Bf[Jd]=!0;var Zd=Object.create||function(e,t){var i;return e!==null?(Cr[ya]=Of(e),i=new Cr,Cr[ya]=null,i[Jd]=e):i=ks(),t===void 0?i:Mf.f(i,t)},Hf=qe,Gf=!Hf(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Yf=ot,jf=Ee,qf=Qs,zf=qa,Wf=Gf,so=zf("IE_PROTO"),Ea=Object,Qf=Ea.prototype,eu=Wf?Ea.getPrototypeOf:function(s){var e=qf(s);if(Yf(e,so))return e[so];var t=e.constructor;return jf(t)&&e instanceof t?t.prototype:e instanceof Ea?Qf:null},Kf=Yi,Xa=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Kf(s,e,t),s},Jf=qe,Xf=Ee,Zf=vt,ep=Zd,ro=eu,tp=Xa,ip=Pe,$a=ip("iterator"),tu=!1,ht,xr,Lr;[].keys&&(Lr=[].keys(),"next"in Lr?(xr=ro(ro(Lr)),xr!==Object.prototype&&(ht=xr)):tu=!0);var sp=!Zf(ht)||Jf(function(){var s={};return ht[$a].call(s)!==s});sp?ht={}:ht=ep(ht);Xf(ht[$a])||tp(ht,$a,function(){return this});var iu={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:tu},rp=Pe,ap=rp("toStringTag"),su={};su[ap]="z";var Za=String(su)==="[object z]",np=Za,op=Ee,Ps=Vi,dp=Pe,up=dp("toStringTag"),lp=Object,cp=Ps(function(){return arguments}())=="Arguments",hp=function(s,e){try{return s[e]}catch(t){}},qi=np?Ps:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=hp(e=lp(s),up))=="string"?t:cp?Ps(e):(i=Ps(e))=="Object"&&op(e.callee)?"Arguments":i},fp=Za,pp=qi,vp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},mp=Za,gp=Ht.f,Sp=Yi,bp=ot,yp=vp,Tp=Pe,ao=Tp("toStringTag"),en=function(s,e,t,i){if(s){var r=t?s:s.prototype;bp(r,ao)||gp(r,ao,{configurable:!0,value:e}),i&&!mp&&Sp(r,"toString",yp)}},Ep=iu.IteratorPrototype,$p=Zd,Ap=Ks,_p=en,wp=pi,kp=function(){return this},Pp=function(s,e,t,i){var r=e+" Iterator";return s.prototype=$p(Ep,{next:Ap(+!i,t)}),_p(s,r,!1,!0),wp[r]=kp,s},Rp=Ze,Dp=Fe,ru=sf,Ip=Pp,Cp=eu,xp=en,no=Xa,Lp=Pe,oo=pi,au=iu,Op=ru.PROPER;ru.CONFIGURABLE;au.IteratorPrototype;var ds=au.BUGGY_SAFARI_ITERATORS,Or=Lp("iterator"),uo="keys",us="values",lo="entries",Mp=function(){return this},Bp=function(s,e,t,i,r,a,n){Ip(t,e,i);var o=function(A){if(A===r&&h)return h;if(!ds&&A in l)return l[A];switch(A){case uo:return function(){return new t(this,A)};case us:return function(){return new t(this,A)};case lo:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Or]||l["@@iterator"]||r&&l[r],h=!ds&&c||o(r),f=e=="Array"&&l.entries||c,v,g,T;if(f&&(v=Cp(f.call(new s)),v!==Object.prototype&&v.next&&(xp(v,u,!0,!0),oo[u]=Mp)),Op&&r==us&&c&&c.name!==us&&(d=!0,h=function(){return Dp(c,this)}),r)if(g={values:o(us),keys:a?h:o(uo),entries:o(lo)},n)for(T in g)(ds||d||!(T in l))&&no(l,T,g[T]);else Rp({target:e,proto:!0,forced:ds||d},g);return n&&l[Or]!==h&&no(l,Or,h,{name:r}),oo[e]=h,g},Np=function(s,e){return{value:s,done:e}},Fp=Gi,co=pi,nu=Fd;Ht.f;var Up=Bp,ls=Np,ou="Array Iterator",Vp=nu.set,Hp=nu.getterFor(ou);Up(Array,"Array",function(s,e){Vp(this,{type:ou,target:Fp(s),index:0,kind:e})},function(){var s=Hp(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ls(void 0,!0)):t=="keys"?ls(i,!1):t=="values"?ls(e[i],!1):ls([i,e[i]],!1)},"values");co.Arguments=co.Array;var Gp=Pe,Yp=pi,jp=Gp("iterator"),qp=Array.prototype,zp=function(s){return s!==void 0&&(Yp.Array===s||qp[jp]===s)},Wp=qi,ho=Ws,Qp=Hi,Kp=pi,Jp=Pe,Xp=Jp("iterator"),du=function(s){if(!Qp(s))return ho(s,Xp)||ho(s,"@@iterator")||Kp[Wp(s)]},Zp=Fe,ev=Yt,tv=mt,iv=zs,sv=du,rv=TypeError,av=function(s,e){var t=arguments.length<2?sv(s):e;if(ev(t))return tv(Zp(t,s));throw rv(iv(s)+" is not iterable")},nv=Fe,fo=mt,ov=Ws,dv=function(s,e,t){var i,r;fo(s);try{if(i=ov(s,"return"),!i){if(e==="throw")throw t;return t}i=nv(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return fo(i),t},uv=Js,lv=Fe,cv=mt,hv=zs,fv=zp,pv=Ja,po=js,vv=av,mv=du,vo=dv,gv=TypeError,Rs=function(s,e){this.stopped=s,this.result=e},mo=Rs.prototype,tn=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=uv(e,i),d,l,c,h,f,v,g,T=function(E){return d&&vo(d,"normal",E),new Rs(!0,E)},A=function(E){return r?(cv(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=mv(s),!l)throw gv(hv(s)+" is not iterable");if(fv(l)){for(c=0,h=pv(s);h>c;c++)if(f=A(s[c]),f&&po(mo,f))return f;return new Rs(!1)}d=vv(s,l)}for(v=a?s.next:d.next;!(g=lv(v,d)).done;){try{f=A(g.value)}catch(E){vo(d,"throw",E)}if(typeof f=="object"&&f&&po(mo,f))return f}return new Rs(!1)},Sv=ja,bv=Ht,yv=Ks,Tv=function(s,e,t){var i=Sv(e);i in s?bv.f(s,i,yv(0,t)):s[i]=t},Ev=Ze,$v=tn,Av=Tv;Ev({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $v(e,function(i,r){Av(t,i,r)},{AS_ENTRIES:!0}),t}});var _v=Ga,wv=_v.Object.fromEntries,kv={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},Pv=kv,Rv=_e,Dv=qi,Iv=Yi,go=pi,Cv=Pe,So=Cv("toStringTag");for(var Mr in Pv){var bo=Rv[Mr],Br=bo&&bo.prototype;Br&&Dv(Br)!==So&&Iv(Br,So,Mr),go[Mr]=go.Array}var xv=wv,Lv=xv,Ov=Lv,Mv=Ov,li=Gs(Mv),Bv=Vi,Xs=typeof process!="undefined"&&Bv(process)=="process",Nv=Ht,Fv=function(s,e,t){return Nv.f(s,e,t)},Uv=Gt,Vv=Fv,Hv=Pe,Gv=Rt,yo=Hv("species"),Yv=function(s){var e=Uv(s);Gv&&e&&!e[yo]&&Vv(e,yo,{configurable:!0,get:function(){return this}})},jv=js,qv=TypeError,zv=function(s,e){if(jv(e,s))return s;throw qv("Incorrect invocation")},Wv=ze,Qv=Ee,Aa=Ya,Kv=Wv(Function.toString);Qv(Aa.inspectSource)||(Aa.inspectSource=function(s){return Kv(s)});var uu=Aa.inspectSource,Jv=ze,Xv=qe,lu=Ee,Zv=qi,em=Gt,tm=uu,cu=function(){},im=[],hu=em("Reflect","construct"),sn=/^\s*(?:class|function)\b/,sm=Jv(sn.exec),rm=!sn.exec(cu),_i=function(e){if(!lu(e))return!1;try{return hu(cu,im,e),!0}catch(t){return!1}},fu=function(e){if(!lu(e))return!1;switch(Zv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rm||!!sm(sn,tm(e))}catch(t){return!0}};fu.sham=!0;var am=!hu||Xv(function(){var s;return _i(_i.call)||!_i(Object)||!_i(function(){s=!0})||s})?fu:_i,nm=am,om=zs,dm=TypeError,um=function(s){if(nm(s))return s;throw dm(om(s)+" is not a constructor")},To=mt,lm=um,cm=Hi,hm=Pe,fm=hm("species"),pu=function(s,e){var t=To(s).constructor,i;return t===void 0||cm(i=To(t)[fm])?e:lm(i)},pm=ze,vm=pm([].slice),mm=TypeError,gm=function(s,e){if(s<e)throw mm("Not enough arguments");return s},Sm=qs,vu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sm),Be=_e,bm=Vd,ym=Js,Eo=Ee,Tm=ot,mu=qe,$o=Kd,Em=vm,Ao=Ha,$m=gm,Am=vu,_m=Xs,_a=Be.setImmediate,wa=Be.clearImmediate,wm=Be.process,Nr=Be.Dispatch,km=Be.Function,_o=Be.MessageChannel,Pm=Be.String,Fr=0,Ci={},wo="onreadystatechange",Ni,Mt,Ur,Vr;mu(function(){Ni=Be.location});var rn=function(s){if(Tm(Ci,s)){var e=Ci[s];delete Ci[s],e()}},Hr=function(s){return function(){rn(s)}},ko=function(s){rn(s.data)},Po=function(s){Be.postMessage(Pm(s),Ni.protocol+"//"+Ni.host)};(!_a||!wa)&&(_a=function(e){$m(arguments.length,1);var t=Eo(e)?e:km(e),i=Em(arguments,1);return Ci[++Fr]=function(){bm(t,void 0,i)},Mt(Fr),Fr},wa=function(e){delete Ci[e]},_m?Mt=function(s){wm.nextTick(Hr(s))}:Nr&&Nr.now?Mt=function(s){Nr.now(Hr(s))}:_o&&!Am?(Ur=new _o,Vr=Ur.port2,Ur.port1.onmessage=ko,Mt=ym(Vr.postMessage,Vr)):Be.addEventListener&&Eo(Be.postMessage)&&!Be.importScripts&&Ni&&Ni.protocol!=="file:"&&!mu(Po)?(Mt=Po,Be.addEventListener("message",ko,!1)):wo in Ao("script")?Mt=function(s){$o.appendChild(Ao("script"))[wo]=function(){$o.removeChild(this),rn(s)}}:Mt=function(s){setTimeout(Hr(s),0)});var gu={set:_a,clear:wa},Su=function(){this.head=null,this.tail=null};Su.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var bu=Su,Rm=qs,Dm=/ipad|iphone|ipod/i.test(Rm)&&typeof Pebble!="undefined",Im=qs,Cm=/web0s(?!.*chrome)/i.test(Im),Ut=_e,Ro=Js,xm=Wa.f,Gr=gu.set,Lm=bu,Om=vu,Mm=Dm,Bm=Cm,Yr=Xs,Do=Ut.MutationObserver||Ut.WebKitMutationObserver,Io=Ut.document,Co=Ut.process,cs=Ut.Promise,xo=xm(Ut,"queueMicrotask"),ka=xo&&xo.value,ei,jr,qr,hs,Lo;if(!ka){var fs=new Lm,ps=function(){var s,e;for(Yr&&(s=Co.domain)&&s.exit();e=fs.get();)try{e()}catch(t){throw fs.head&&ei(),t}s&&s.enter()};!Om&&!Yr&&!Bm&&Do&&Io?(jr=!0,qr=Io.createTextNode(""),new Do(ps).observe(qr,{characterData:!0}),ei=function(){qr.data=jr=!jr}):!Mm&&cs&&cs.resolve?(hs=cs.resolve(void 0),hs.constructor=cs,Lo=Ro(hs.then,hs),ei=function(){Lo(ps)}):Yr?ei=function(){Co.nextTick(ps)}:(Gr=Ro(Gr,Ut),ei=function(){Gr(ps)}),ka=function(s){fs.head||ei(),fs.add(s)}}var Nm=ka,Fm=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},an=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Um=_e,vi=Um.Promise,yu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vm=yu,Hm=Xs,Gm=!Vm&&!Hm&&typeof window=="object"&&typeof document=="object",Ym=_e,xi=vi,jm=Ee,qm=qd,zm=uu,Wm=Pe,Qm=Gm,Km=yu,zr=Id,Oo=xi&&xi.prototype,Jm=Wm("species"),Pa=!1,Tu=jm(Ym.PromiseRejectionEvent),Xm=qm("Promise",function(){var s=zm(xi),e=s!==String(xi);if(!e&&zr===66||!(Oo.catch&&Oo.finally))return!0;if(!zr||zr<51||!/native code/.test(s)){var t=new xi(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jm]=i,Pa=t.then(function(){})instanceof i,!Pa)return!0}return!e&&(Qm||Km)&&!Tu}),zi={CONSTRUCTOR:Xm,REJECTION_EVENT:Tu,SUBCLASSING:Pa},mi={},Mo=Yt,Zm=TypeError,eg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw Zm("Bad Promise constructor");e=i,t=r}),this.resolve=Mo(e),this.reject=Mo(t)};mi.f=function(s){return new eg(s)};var tg=Ze,Ms=Xs,Pt=_e,Wi=Fe,ig=Xa,sg=en,rg=Yv,ag=Yt,Ra=Ee,ng=vt,og=zv,dg=pu,Eu=gu.set,nn=Nm,ug=Fm,lg=an,cg=bu,$u=Fd,Da=vi,on=zi,Au=mi,Zs="Promise",_u=on.CONSTRUCTOR,hg=on.REJECTION_EVENT;on.SUBCLASSING;var Wr=$u.getterFor(Zs),fg=$u.set,pg=Da&&Da.prototype,ri=Da,Qr=pg,wu=Pt.TypeError,Ia=Pt.document,dn=Pt.process,Ca=Au.f,vg=Ca,mg=!!(Ia&&Ia.createEvent&&Pt.dispatchEvent),ku="unhandledrejection",gg="rejectionhandled",Bo=0,Pu=1,Sg=2,un=1,Ru=2,vs,No,bg,Du=function(s){var e;return ng(s)&&Ra(e=s.then)?e:!1},Iu=function(s,e){var t=e.value,i=e.state==Pu,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Ru&&Tg(e),e.rejection=un),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(wu("Promise-chain cycle")):(d=Du(u))?Wi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Cu=function(s,e){s.notified||(s.notified=!0,nn(function(){for(var t=s.reactions,i;i=t.get();)Iu(i,s);s.notified=!1,e&&!s.rejection&&yg(s)}))},xu=function(s,e,t){var i,r;mg?(i=Ia.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Pt.dispatchEvent(i)):i={promise:e,reason:t},!hg&&(r=Pt["on"+s])?r(i):s===ku&&ug("Unhandled promise rejection",t)},yg=function(s){Wi(Eu,Pt,function(){var e=s.facade,t=s.value,i=Fo(s),r;if(i&&(r=lg(function(){Ms?dn.emit("unhandledRejection",t,e):xu(ku,e,t)}),s.rejection=Ms||Fo(s)?Ru:un,r.error))throw r.value})},Fo=function(s){return s.rejection!==un&&!s.parent},Tg=function(s){Wi(Eu,Pt,function(){var e=s.facade;Ms?dn.emit("rejectionHandled",e):xu(gg,e,s.value)})},ai=function(s,e,t){return function(i){s(e,i,t)}},oi=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=Sg,Cu(s,!0))},xa=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw wu("Promise can't be resolved itself");var i=Du(e);i?nn(function(){var r={done:!1};try{Wi(i,e,ai(xa,r,s),ai(oi,r,s))}catch(a){oi(r,a,s)}}):(s.value=e,s.state=Pu,Cu(s,!1))}catch(r){oi({done:!1},r,s)}}};_u&&(ri=function(e){og(this,Qr),ag(e),Wi(vs,this);var t=Wr(this);try{e(ai(xa,t),ai(oi,t))}catch(i){oi(t,i)}},Qr=ri.prototype,vs=function(e){fg(this,{type:Zs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:Bo,value:void 0})},vs.prototype=ig(Qr,"then",function(e,t){var i=Wr(this),r=Ca(dg(this,ri));return i.parent=!0,r.ok=Ra(e)?e:!0,r.fail=Ra(t)&&t,r.domain=Ms?dn.domain:void 0,i.state==Bo?i.reactions.add(r):nn(function(){Iu(r,i)}),r.promise}),No=function(){var s=new vs,e=Wr(s);this.promise=s,this.resolve=ai(xa,e),this.reject=ai(oi,e)},Au.f=Ca=function(s){return s===ri||s===bg?new No(s):vg(s)});tg({global:!0,constructor:!0,wrap:!0,forced:_u},{Promise:ri});sg(ri,Zs,!1,!0);rg(Zs);var Eg=Pe,Lu=Eg("iterator"),Ou=!1;try{var $g=0,Uo={next:function(){return{done:!!$g++}},return:function(){Ou=!0}};Uo[Lu]=function(){return this},Array.from(Uo,function(){throw 2})}catch(s){}var Ag=function(s,e){if(!e&&!Ou)return!1;var t=!1;try{var i={};i[Lu]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},_g=vi,wg=Ag,kg=zi.CONSTRUCTOR,Mu=kg||!wg(function(s){_g.all(s).then(void 0,function(){})}),Pg=Ze,Rg=Fe,Dg=Yt,Ig=mi,Cg=an,xg=tn,Lg=Mu;Pg({target:"Promise",stat:!0,forced:Lg},{all:function(e){var t=this,i=Ig.f(t),r=i.resolve,a=i.reject,n=Cg(function(){var o=Dg(t.resolve),u=[],d=0,l=1;xg(e,function(c){var h=d++,f=!1;l++,Rg(o,t,c).then(function(v){f||(f=!0,u[h]=v,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var Og=Ze,Mg=zi.CONSTRUCTOR,Vo=vi;Vo&&Vo.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(s){return this.then(void 0,s)}});var Bg=Ze,Ng=Fe,Fg=Yt,Ug=mi,Vg=an,Hg=tn,Gg=Mu;Bg({target:"Promise",stat:!0,forced:Gg},{race:function(e){var t=this,i=Ug.f(t),r=i.reject,a=Vg(function(){var n=Fg(t.resolve);Hg(e,function(o){Ng(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var Yg=Ze,jg=Fe,qg=mi,zg=zi.CONSTRUCTOR;Yg({target:"Promise",stat:!0,forced:zg},{reject:function(e){var t=qg.f(this);return jg(t.reject,void 0,e),t.promise}});var Wg=mt,Qg=vt,Kg=mi,Bu=function(s,e){if(Wg(s),Qg(e)&&e.constructor===s)return e;var t=Kg.f(s),i=t.resolve;return i(e),t.promise},Jg=Ze,Xg=Gt,Zg=Rc,eS=vi,tS=zi.CONSTRUCTOR,iS=Bu,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=Ze,La=vi,nS=qe,oS=Gt,dS=Ee,uS=pu,Ho=Bu,lS=La&&La.prototype,cS=!!La&&nS(function(){lS.finally.call({then:function(){}},function(){})});aS({target:"Promise",proto:!0,real:!0,forced:cS},{finally:function(s){var e=uS(this,oS("Promise")),t=dS(s);return this.then(t?function(i){return Ho(e,s()).then(function(){return i})}:s,t?function(i){return Ho(e,s()).then(function(){throw i})}:s)}});var hS=Gt,ln=hS,fS=ln,pS=fS("Promise","finally"),vS=pS,mS=vS,gS=mS,SS=gS,er=Gs(SS),Te;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var Je=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:H(t)}return s};const Go=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var D=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ce{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||k(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const bS=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return H(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const yS=5,TS=5,ES=500,Yo=7e3;class $S{constructor(e){this.subscription=new ae,this.loadMediaTimeoutSubscription=new ae,this.videoState=new ce(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===W.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}default:H(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 ae;this.subscription.add(e),this.subscription.add(V(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 x;e.add(r.pipe(je(ES)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(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===W.Applying||Math.abs(o-a)>yS)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(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(),D(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:H(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:W.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&D(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=Tl(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=Je(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return k(u)&&(o.metadata.title=u),k(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===W.Applying||i.state===W.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(El(Yo).subscribe(()=>a(`timeout(${Yo})`)))});er(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===W.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:L.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var AS=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},_S=s=>{const e=new S(1/0),t=new x,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,v,g;const T=li(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(m=>m.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const m=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:m*1e3)!==null&&f!==void 0?f:NaN;k($)&&!isNaN($)&&e.next($)}const A=(v=T["x-delivery-type"])!==null&&v!==void 0?v:Mi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),v(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ci=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},wS=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ci}),!0),kS=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Xe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=ie(r),d=new ae;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},jt=(s,e,t)=>Xe(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),gt=(s,e,t,i)=>Xe(e,()=>({muted:s.muted,volume:s.volume}),r=>{k(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Dt=(s,e,t,i)=>Xe(e,()=>s.playbackRate,r=>{k(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),PS=s=>["__",s.language,s.label].join("|"),RS=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class dt{constructor(){this.available$=new x,this.current$=new S(void 0),this.error$=new x,this.subscription=new ae,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Xe(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(Xe(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(Xe(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(V(B(e,"addtrack"),B(e,"removetrack"),De(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(B(e,"change"),De(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;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){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(dt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:PS(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(ie(e)||!RS(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){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const cn=s=>{s.removeAttribute("src"),s.load()},DS=s=>{try{s.pause(),s.playbackRate=0,cn(s),s.remove()}catch(e){console.error(e)}};class IS{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 Oa=window.WeakMap?new WeakMap:new IS,St=s=>{let e=s.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),s.appendChild(e)),Oa.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=s=>{const e=Oa.get(s);Oa.delete(s),e?cn(s):DS(s)};class tr{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 Nu=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},jo=s=>{const e=Nu(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},CS=s=>{const e=Nu(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Ma=3;class xS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Ma&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ma))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Fu=(s,e,t=Ma)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const yt=s=>{const e=m=>B(s,m).pipe(ui(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>B(s,m))).pipe(w(m=>m.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=V(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Fu(s.buffered,s.currentTime))),n=Ua().browser===yd.Safari?Ne({play:e("play").pipe(ge()),playing:e("playing")}).pipe(ui(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(re(()=>!!(s.error||s.played.length)),w(()=>{var m;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(m=s.error)!==null&&m!==void 0?m:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new x,h=.3;let f;l.subscribe(m=>{s.loop&&k(f)&&k(m)&&f>=s.duration-h&&m<=h&&c.next(f),f=m});const v=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(CS(s));v.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(jo(s));return B(s,"fullscreenchange").pipe(w(()=>jo(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(re(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},hn=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var LS=Ze,OS=Qs,MS=Ja,BS=Ka;LS({target:"Array",proto:!0},{at:function(e){var t=OS(this),i=MS(t),r=BS(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var NS=ln,FS=NS("Array","at"),US=FS,VS=US,HS=VS,GS=HS,st=Gs(GS);let fn=!1,ct={};const YS=s=>{fn=s},jS=()=>{ct={}},qS=s=>{s(ct)},ms=(s,e)=>{var t;fn&&(ct.meta=(t=ct.meta)!==null&&t!==void 0?t:{},ct.meta[s]=e)};class rt{constructor(e){this.name=e}next(e){var t,i;if(!fn)return;ct.series=(t=ct.series)!==null&&t!==void 0?t:{};const r=(i=ct.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),ct.series[this.name]=r}}var Nt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Nt||(Nt={}));const zS=new rt("best_bitrate"),WS=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class QS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=me()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const gi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,v,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},m=E&&Vt(E),b=i.considerPlaybackRate&&k(o)?o:1,$=s.filter(U=>!Oi(U.quality)).sort((U,I)=>Ii(U.quality,I.quality)?-1:1),R=(f=st($,-1))===null||f===void 0?void 0:f.quality,j=(v=st($,0))===null||v===void 0?void 0:v.quality,X=ie(r)||k(r.min)&&k(r.max)&&ws(r.max,r.min)||k(r.min)&&j&&Ii(r.min,j)||k(r.max)&&R&&ws(r.max,R),F=b*WS(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),Y={},O=$.filter(U=>(m?ws(U.quality,m):!0)?(k(t)&&isFinite(t)&&k(U.bitrate)?t-a>=U.bitrate*F:!0)?i.lazyQualitySwitch&&k(i.minBufferToSwitchUp)&&u&&!Oi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Ii(U.quality,u.quality)?(Y[U.quality]=Nt.Buffer,!1):!!l&&pa(U.quality,l)?(Y[U.quality]=Nt.DroppedFramesLimit,!1):X||(ie(r.max)||Td(U.quality,r.max))&&(ie(r.min)||pa(U.quality,r.min))?!0:(Y[U.quality]=Nt.FitsQualityLimits,!1):(Y[U.quality]=Nt.FitsThroughput,!1):(Y[U.quality]=Nt.FitsContainer,!1))[0];O&&O.bitrate&&zS.next(O.bitrate);const G=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];G.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as S,Subject as x,Subscription as ae,isNonNullable as k,ErrorCategory as L,isNullable as ie,fromEvent as B,assertNever as H,merge as V,tap as Is,map as w,observableFrom as De,filterChanged as ve,assertNonNullable as P,debounce as je,getHighestQuality as Tl,timeout as El,getCurrentBrowser as Ua,CurrentClientBrowser as yd,combine as Ne,once as ge,mapTo as ui,filter as re,now as me,videoSizeToQuality as Vt,isInvariantQuality as Oi,isHigher as Ii,isLower as ws,isHigherOrEqual as pa,isLowerOrEqual as Td,Observable as Hs,interval as Cs,VideoQuality as He,videoQualityToHeight as $l,abortable as Oe,getExponentialDelay as kn,throttle as Al,CurrentClientDevice as _l,safeStorage as vr,fillWithDefault as wl,Logger as kl}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as BT,Subject as NT,Subscription as FT,ValueSubject as UT,VideoQuality as VT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Pl from"lodash/debounce.js";const Rl="2.0.96";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var we;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(we||(we={}));var $e;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})($e||($e={}));var Mi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Mi||(Mi={}));var W;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(W||(W={}));var At;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(At||(At={}));function ue(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function M(s){return this instanceof M?(this.v=s,this):new M(s)}function Me(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(v,g){a.push([h,f,v,g])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(v){c(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Dl=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Il{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S($e.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new S($e.NOT_AVAILABLE),this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=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||Dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();ie(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();ie(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return H(r.sessionState)}})).add(V(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Is(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),De([i.getCastState()])).pipe(ve(),w(Cl),Is(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===$e.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(ie(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===$e.CONNECTED?k(this.connection$.getValue())?$e.CONNECTED:$e.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Cl=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return $e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return $e.AVAILABLE;case cast.framework.CastState.CONNECTING:return $e.CONNECTING;case cast.framework.CastState.CONNECTED:return $e.CONNECTED;default:return H(s)}};var mr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Gs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qe=function(s){try{return!!s()}catch(e){return!0}},xl=qe,Ys=!xl(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ed=Ys,$d=Function.prototype,va=$d.call,Ll=Ed&&$d.bind.bind(va,va),ze=Ed?Ll:function(s){return function(){return va.apply(s,arguments)}},Ad=ze,Ol=Ad({}.toString),Ml=Ad("".slice),Vi=function(s){return Ml(Ol(s),8,-1)},Bl=ze,Nl=qe,Fl=Vi,gr=Object,Ul=Bl("".split),Vl=Nl(function(){return!gr("z").propertyIsEnumerable(0)})?function(s){return Fl(s)=="String"?Ul(s,""):gr(s)}:gr,Hi=function(s){return s==null},Hl=Hi,Gl=TypeError,Va=function(s){if(Hl(s))throw Gl("Can't call method on "+s);return s},Yl=Vl,jl=Va,Gi=function(s){return Yl(jl(s))},pi={},ss=function(s){return s&&s.Math==Math&&s},_e=ss(typeof globalThis=="object"&&globalThis)||ss(typeof window=="object"&&window)||ss(typeof self=="object"&&self)||ss(typeof mr=="object"&&mr)||function(){return this}()||mr||Function("return this")(),ma=typeof document=="object"&&document.all,ql=typeof ma=="undefined"&&ma!==void 0,_d={all:ma,IS_HTMLDDA:ql},wd=_d,zl=wd.all,Ee=wd.IS_HTMLDDA?function(s){return typeof s=="function"||s===zl}:function(s){return typeof s=="function"},Wl=_e,Ql=Ee,Pn=Wl.WeakMap,Kl=Ql(Pn)&&/native code/.test(String(Pn)),Rn=Ee,kd=_d,Jl=kd.all,vt=kd.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Rn(s)||s===Jl}:function(s){return typeof s=="object"?s!==null:Rn(s)},Xl=qe,Rt=!Xl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ht={},Zl=_e,Dn=vt,ga=Zl.document,ec=Dn(ga)&&Dn(ga.createElement),Ha=function(s){return ec?ga.createElement(s):{}},tc=Rt,ic=qe,sc=Ha,Pd=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Rt,ac=qe,Rd=rc&&ac(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),nc=vt,oc=String,dc=TypeError,mt=function(s){if(nc(s))return s;throw dc(oc(s)+" is not an object")},uc=Ys,rs=Function.prototype.call,Fe=uc?rs.bind(rs):function(){return rs.apply(rs,arguments)},Ga={},Sr=Ga,br=_e,lc=Ee,In=function(s){return lc(s)?s:void 0},Gt=function(s,e){return arguments.length<2?In(Sr[s])||In(br[s]):Sr[s]&&Sr[s][e]||br[s]&&br[s][e]},cc=ze,js=cc({}.isPrototypeOf),qs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Dd=_e,yr=qs,Cn=Dd.process,xn=Dd.Deno,Ln=Cn&&Cn.versions||xn&&xn.version,On=Ln&&Ln.v8,Ke,xs;On&&(Ke=On.split("."),xs=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!xs&&yr&&(Ke=yr.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=yr.match(/Chrome\/(\d+)/),Ke&&(xs=+Ke[1])));var Id=xs,Mn=Id,hc=qe,fc=_e,pc=fc.String,Cd=!!Object.getOwnPropertySymbols&&!hc(function(){var s=Symbol();return!pc(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mn&&Mn<41}),vc=Cd,xd=vc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",mc=Gt,gc=Ee,Sc=js,bc=xd,yc=Object,Ld=bc?function(s){return typeof s=="symbol"}:function(s){var e=mc("Symbol");return gc(e)&&Sc(e.prototype,yc(s))},Tc=String,zs=function(s){try{return Tc(s)}catch(e){return"Object"}},Ec=Ee,$c=zs,Ac=TypeError,Yt=function(s){if(Ec(s))return s;throw Ac($c(s)+" is not a function")},_c=Yt,wc=Hi,Ws=function(s,e){var t=s[e];return wc(t)?void 0:_c(t)},Tr=Fe,Er=Ee,$r=vt,kc=TypeError,Pc=function(s,e){var t,i;if(e==="string"&&Er(t=s.toString)&&!$r(i=Tr(t,s))||Er(t=s.valueOf)&&!$r(i=Tr(t,s))||e!=="string"&&Er(t=s.toString)&&!$r(i=Tr(t,s)))return i;throw kc("Can't convert object to primitive value")},Od={exports:{}},Rc=!0,Bn=_e,Dc=Object.defineProperty,Ic=function(s,e){try{Dc(Bn,s,{value:e,configurable:!0,writable:!0})}catch(t){Bn[s]=e}return e},Cc=_e,xc=Ic,Nn="__core-js_shared__",Lc=Cc[Nn]||xc(Nn,{}),Ya=Lc,Fn=Ya;(Od.exports=function(s,e){return Fn[s]||(Fn[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Md=Od.exports,Oc=Va,Mc=Object,Qs=function(s){return Mc(Oc(s))},Bc=ze,Nc=Qs,Fc=Bc({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return Fc(Nc(e),t)},Uc=ze,Vc=0,Hc=Math.random(),Gc=Uc(1 .toString),Bd=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Gc(++Vc+Hc,36)},Yc=_e,jc=Md,Un=ot,qc=Bd,zc=Cd,Wc=xd,si=Yc.Symbol,Ar=jc("wks"),Qc=Wc?si.for||si:si&&si.withoutSetter||qc,Pe=function(s){return Un(Ar,s)||(Ar[s]=zc&&Un(si,s)?si[s]:Qc("Symbol."+s)),Ar[s]},Kc=Fe,Vn=vt,Hn=Ld,Jc=Ws,Xc=Pc,Zc=Pe,eh=TypeError,th=Zc("toPrimitive"),ih=function(s,e){if(!Vn(s)||Hn(s))return s;var t=Jc(s,th),i;if(t){if(e===void 0&&(e="default"),i=Kc(t,s,e),!Vn(i)||Hn(i))return i;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(s,e)},sh=ih,rh=Ld,ja=function(s){var e=sh(s,"string");return rh(e)?e:e+""},ah=Rt,nh=Pd,oh=Rd,as=mt,Gn=ja,dh=TypeError,_r=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,wr="enumerable",kr="configurable",Pr="writable";Ht.f=ah?oh?function(e,t,i){if(as(e),t=Gn(t),as(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pr in i&&!i[Pr]){var r=uh(e,t);r&&r[Pr]&&(e[t]=i.value,i={configurable:kr in i?i[kr]:r[kr],enumerable:wr in i?i[wr]:r[wr],writable:!1})}return _r(e,t,i)}:_r:function(e,t,i){if(as(e),t=Gn(t),as(i),nh)try{return _r(e,t,i)}catch(r){}if("get"in i||"set"in i)throw dh("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ks=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},lh=Rt,ch=Ht,hh=Ks,Yi=lh?function(s,e,t){return ch.f(s,e,hh(1,t))}:function(s,e,t){return s[e]=t,s},fh=Md,ph=Bd,Yn=fh("keys"),qa=function(s){return Yn[s]||(Yn[s]=ph(s))},za={},vh=Kl,Nd=_e,mh=vt,gh=Yi,Rr=ot,Dr=Ya,Sh=qa,bh=za,jn="Object already initialized",Sa=Nd.TypeError,yh=Nd.WeakMap,Ls,Bi,Os,Th=function(s){return Os(s)?Bi(s):Ls(s,{})},Eh=function(s){return function(e){var t;if(!mh(e)||(t=Bi(e)).type!==s)throw Sa("Incompatible receiver, "+s+" required");return t}};if(vh||Dr.state){var tt=Dr.state||(Dr.state=new yh);tt.get=tt.get,tt.has=tt.has,tt.set=tt.set,Ls=function(s,e){if(tt.has(s))throw Sa(jn);return e.facade=s,tt.set(s,e),e},Bi=function(s){return tt.get(s)||{}},Os=function(s){return tt.has(s)}}else{var Jt=Sh("state");bh[Jt]=!0,Ls=function(s,e){if(Rr(s,Jt))throw Sa(jn);return e.facade=s,gh(s,Jt,e),e},Bi=function(s){return Rr(s,Jt)?s[Jt]:{}},Os=function(s){return Rr(s,Jt)}}var Fd={set:Ls,get:Bi,has:Os,enforce:Th,getterFor:Eh},$h=Ys,Ud=Function.prototype,qn=Ud.apply,zn=Ud.call,Vd=typeof Reflect=="object"&&Reflect.apply||($h?zn.bind(qn):function(){return zn.apply(qn,arguments)}),Ah=Vi,_h=ze,Hd=function(s){if(Ah(s)==="Function")return _h(s)},Wa={},Gd={},Yd={}.propertyIsEnumerable,jd=Object.getOwnPropertyDescriptor,wh=jd&&!Yd.call({1:2},1);Gd.f=wh?function(e){var t=jd(this,e);return!!t&&t.enumerable}:Yd;var kh=Rt,Ph=Fe,Rh=Gd,Dh=Ks,Ih=Gi,Ch=ja,xh=ot,Lh=Pd,Wn=Object.getOwnPropertyDescriptor;Wa.f=kh?Wn:function(e,t){if(e=Ih(e),t=Ch(t),Lh)try{return Wn(e,t)}catch(i){}if(xh(e,t))return Dh(!Ph(Rh.f,e,t),e[t])};var Oh=qe,Mh=Ee,Bh=/#|\.prototype\./,ji=function(s,e){var t=Fh[Nh(s)];return t==Vh?!0:t==Uh?!1:Mh(e)?Oh(e):!!e},Nh=ji.normalize=function(s){return String(s).replace(Bh,".").toLowerCase()},Fh=ji.data={},Uh=ji.NATIVE="N",Vh=ji.POLYFILL="P",qd=ji,Qn=Hd,Hh=Yt,Gh=Ys,Yh=Qn(Qn.bind),Js=function(s,e){return Hh(s),e===void 0?s:Gh?Yh(s,e):function(){return s.apply(e,arguments)}},ns=_e,jh=Vd,qh=Hd,zh=Ee,Wh=Wa.f,Qh=qd,Xt=Ga,Kh=Js,Zt=Yi,Kn=ot,Jh=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return jh(s,this,arguments)};return e.prototype=s.prototype,e},Ze=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ns:r?ns[t]:(ns[t]||{}).prototype,o=i?Xt:Xt[t]||Zt(Xt,t,{})[t],u=o.prototype,d,l,c,h,f,v,g,T,A;for(h in e)d=Qh(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Kn(n,h),v=o[h],l&&(s.dontCallGetSet?(A=Wh(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof v==typeof f)&&(s.bind&&l?T=Kh(f,ns):s.wrap&&l?T=Jh(f):a&&zh(f)?T=qh(f):T=f,(s.sham||f&&f.sham||v&&v.sham)&&Zt(T,"sham",!0),Zt(o,h,T),a&&(c=t+"Prototype",Kn(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],h,f),s.real&&u&&(d||!u[h])&&Zt(u,h,f)))},ba=Rt,Xh=ot,zd=Function.prototype,Zh=ba&&Object.getOwnPropertyDescriptor,Qa=Xh(zd,"name"),ef=Qa&&function(){}.name==="something",tf=Qa&&(!ba||ba&&Zh(zd,"name").configurable),sf={EXISTS:Qa,PROPER:ef,CONFIGURABLE:tf},Wd={},rf=Math.ceil,af=Math.floor,nf=Math.trunc||function(e){var t=+e;return(t>0?af:rf)(t)},of=nf,Ka=function(s){var e=+s;return e!==e||e===0?0:of(e)},df=Ka,uf=Math.max,lf=Math.min,cf=function(s,e){var t=df(s);return t<0?uf(t+e,0):lf(t,e)},hf=Ka,ff=Math.min,pf=function(s){return s>0?ff(hf(s),9007199254740991):0},vf=pf,Ja=function(s){return vf(s.length)},mf=Gi,gf=cf,Sf=Ja,Jn=function(s){return function(e,t,i){var r=mf(e),a=Sf(r),n=gf(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},bf={includes:Jn(!0),indexOf:Jn(!1)},yf=ze,Ir=ot,Tf=Gi,Ef=bf.indexOf,$f=za,Xn=yf([].push),Af=function(s,e){var t=Tf(s),i=0,r=[],a;for(a in t)!Ir($f,a)&&Ir(t,a)&&Xn(r,a);for(;e.length>i;)Ir(t,a=e[i++])&&(~Ef(r,a)||Xn(r,a));return r},Qd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_f=Af,wf=Qd,kf=Object.keys||function(e){return _f(e,wf)},Pf=Rt,Rf=Rd,Df=Ht,If=mt,Cf=Gi,xf=kf;Wd.f=Pf&&!Rf?Object.defineProperties:function(e,t){If(e);for(var i=Cf(t),r=xf(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],i[o]);return e};var Lf=Gt,Kd=Lf("document","documentElement"),Of=mt,Mf=Wd,Zn=Qd,Bf=za,Nf=Kd,Ff=Ha,Uf=qa,eo=">",to="<",ya="prototype",Ta="script",Jd=Uf("IE_PROTO"),Cr=function(){},Xd=function(s){return to+Ta+eo+s+to+"/"+Ta+eo},io=function(s){s.write(Xd("")),s.close();var e=s.parentWindow.Object;return s=null,e},Vf=function(){var s=Ff("iframe"),e="java"+Ta+":",t;return s.style.display="none",Nf.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Xd("document.F=Object")),t.close(),t.F},os,ks=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&os?io(os):Vf():io(os);for(var s=Zn.length;s--;)delete ks[ya][Zn[s]];return ks()};Bf[Jd]=!0;var Zd=Object.create||function(e,t){var i;return e!==null?(Cr[ya]=Of(e),i=new Cr,Cr[ya]=null,i[Jd]=e):i=ks(),t===void 0?i:Mf.f(i,t)},Hf=qe,Gf=!Hf(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Yf=ot,jf=Ee,qf=Qs,zf=qa,Wf=Gf,so=zf("IE_PROTO"),Ea=Object,Qf=Ea.prototype,eu=Wf?Ea.getPrototypeOf:function(s){var e=qf(s);if(Yf(e,so))return e[so];var t=e.constructor;return jf(t)&&e instanceof t?t.prototype:e instanceof Ea?Qf:null},Kf=Yi,Xa=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Kf(s,e,t),s},Jf=qe,Xf=Ee,Zf=vt,ep=Zd,ro=eu,tp=Xa,ip=Pe,$a=ip("iterator"),tu=!1,ht,xr,Lr;[].keys&&(Lr=[].keys(),"next"in Lr?(xr=ro(ro(Lr)),xr!==Object.prototype&&(ht=xr)):tu=!0);var sp=!Zf(ht)||Jf(function(){var s={};return ht[$a].call(s)!==s});sp?ht={}:ht=ep(ht);Xf(ht[$a])||tp(ht,$a,function(){return this});var iu={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:tu},rp=Pe,ap=rp("toStringTag"),su={};su[ap]="z";var Za=String(su)==="[object z]",np=Za,op=Ee,Ps=Vi,dp=Pe,up=dp("toStringTag"),lp=Object,cp=Ps(function(){return arguments}())=="Arguments",hp=function(s,e){try{return s[e]}catch(t){}},qi=np?Ps:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=hp(e=lp(s),up))=="string"?t:cp?Ps(e):(i=Ps(e))=="Object"&&op(e.callee)?"Arguments":i},fp=Za,pp=qi,vp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},mp=Za,gp=Ht.f,Sp=Yi,bp=ot,yp=vp,Tp=Pe,ao=Tp("toStringTag"),en=function(s,e,t,i){if(s){var r=t?s:s.prototype;bp(r,ao)||gp(r,ao,{configurable:!0,value:e}),i&&!mp&&Sp(r,"toString",yp)}},Ep=iu.IteratorPrototype,$p=Zd,Ap=Ks,_p=en,wp=pi,kp=function(){return this},Pp=function(s,e,t,i){var r=e+" Iterator";return s.prototype=$p(Ep,{next:Ap(+!i,t)}),_p(s,r,!1,!0),wp[r]=kp,s},Rp=Ze,Dp=Fe,ru=sf,Ip=Pp,Cp=eu,xp=en,no=Xa,Lp=Pe,oo=pi,au=iu,Op=ru.PROPER;ru.CONFIGURABLE;au.IteratorPrototype;var ds=au.BUGGY_SAFARI_ITERATORS,Or=Lp("iterator"),uo="keys",us="values",lo="entries",Mp=function(){return this},Bp=function(s,e,t,i,r,a,n){Ip(t,e,i);var o=function(A){if(A===r&&h)return h;if(!ds&&A in l)return l[A];switch(A){case uo:return function(){return new t(this,A)};case us:return function(){return new t(this,A)};case lo:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Or]||l["@@iterator"]||r&&l[r],h=!ds&&c||o(r),f=e=="Array"&&l.entries||c,v,g,T;if(f&&(v=Cp(f.call(new s)),v!==Object.prototype&&v.next&&(xp(v,u,!0,!0),oo[u]=Mp)),Op&&r==us&&c&&c.name!==us&&(d=!0,h=function(){return Dp(c,this)}),r)if(g={values:o(us),keys:a?h:o(uo),entries:o(lo)},n)for(T in g)(ds||d||!(T in l))&&no(l,T,g[T]);else Rp({target:e,proto:!0,forced:ds||d},g);return n&&l[Or]!==h&&no(l,Or,h,{name:r}),oo[e]=h,g},Np=function(s,e){return{value:s,done:e}},Fp=Gi,co=pi,nu=Fd;Ht.f;var Up=Bp,ls=Np,ou="Array Iterator",Vp=nu.set,Hp=nu.getterFor(ou);Up(Array,"Array",function(s,e){Vp(this,{type:ou,target:Fp(s),index:0,kind:e})},function(){var s=Hp(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ls(void 0,!0)):t=="keys"?ls(i,!1):t=="values"?ls(e[i],!1):ls([i,e[i]],!1)},"values");co.Arguments=co.Array;var Gp=Pe,Yp=pi,jp=Gp("iterator"),qp=Array.prototype,zp=function(s){return s!==void 0&&(Yp.Array===s||qp[jp]===s)},Wp=qi,ho=Ws,Qp=Hi,Kp=pi,Jp=Pe,Xp=Jp("iterator"),du=function(s){if(!Qp(s))return ho(s,Xp)||ho(s,"@@iterator")||Kp[Wp(s)]},Zp=Fe,ev=Yt,tv=mt,iv=zs,sv=du,rv=TypeError,av=function(s,e){var t=arguments.length<2?sv(s):e;if(ev(t))return tv(Zp(t,s));throw rv(iv(s)+" is not iterable")},nv=Fe,fo=mt,ov=Ws,dv=function(s,e,t){var i,r;fo(s);try{if(i=ov(s,"return"),!i){if(e==="throw")throw t;return t}i=nv(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return fo(i),t},uv=Js,lv=Fe,cv=mt,hv=zs,fv=zp,pv=Ja,po=js,vv=av,mv=du,vo=dv,gv=TypeError,Rs=function(s,e){this.stopped=s,this.result=e},mo=Rs.prototype,tn=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=uv(e,i),d,l,c,h,f,v,g,T=function(E){return d&&vo(d,"normal",E),new Rs(!0,E)},A=function(E){return r?(cv(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=mv(s),!l)throw gv(hv(s)+" is not iterable");if(fv(l)){for(c=0,h=pv(s);h>c;c++)if(f=A(s[c]),f&&po(mo,f))return f;return new Rs(!1)}d=vv(s,l)}for(v=a?s.next:d.next;!(g=lv(v,d)).done;){try{f=A(g.value)}catch(E){vo(d,"throw",E)}if(typeof f=="object"&&f&&po(mo,f))return f}return new Rs(!1)},Sv=ja,bv=Ht,yv=Ks,Tv=function(s,e,t){var i=Sv(e);i in s?bv.f(s,i,yv(0,t)):s[i]=t},Ev=Ze,$v=tn,Av=Tv;Ev({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $v(e,function(i,r){Av(t,i,r)},{AS_ENTRIES:!0}),t}});var _v=Ga,wv=_v.Object.fromEntries,kv={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},Pv=kv,Rv=_e,Dv=qi,Iv=Yi,go=pi,Cv=Pe,So=Cv("toStringTag");for(var Mr in Pv){var bo=Rv[Mr],Br=bo&&bo.prototype;Br&&Dv(Br)!==So&&Iv(Br,So,Mr),go[Mr]=go.Array}var xv=wv,Lv=xv,Ov=Lv,Mv=Ov,li=Gs(Mv),Bv=Vi,Xs=typeof process!="undefined"&&Bv(process)=="process",Nv=Ht,Fv=function(s,e,t){return Nv.f(s,e,t)},Uv=Gt,Vv=Fv,Hv=Pe,Gv=Rt,yo=Hv("species"),Yv=function(s){var e=Uv(s);Gv&&e&&!e[yo]&&Vv(e,yo,{configurable:!0,get:function(){return this}})},jv=js,qv=TypeError,zv=function(s,e){if(jv(e,s))return s;throw qv("Incorrect invocation")},Wv=ze,Qv=Ee,Aa=Ya,Kv=Wv(Function.toString);Qv(Aa.inspectSource)||(Aa.inspectSource=function(s){return Kv(s)});var uu=Aa.inspectSource,Jv=ze,Xv=qe,lu=Ee,Zv=qi,em=Gt,tm=uu,cu=function(){},im=[],hu=em("Reflect","construct"),sn=/^\s*(?:class|function)\b/,sm=Jv(sn.exec),rm=!sn.exec(cu),_i=function(e){if(!lu(e))return!1;try{return hu(cu,im,e),!0}catch(t){return!1}},fu=function(e){if(!lu(e))return!1;switch(Zv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rm||!!sm(sn,tm(e))}catch(t){return!0}};fu.sham=!0;var am=!hu||Xv(function(){var s;return _i(_i.call)||!_i(Object)||!_i(function(){s=!0})||s})?fu:_i,nm=am,om=zs,dm=TypeError,um=function(s){if(nm(s))return s;throw dm(om(s)+" is not a constructor")},To=mt,lm=um,cm=Hi,hm=Pe,fm=hm("species"),pu=function(s,e){var t=To(s).constructor,i;return t===void 0||cm(i=To(t)[fm])?e:lm(i)},pm=ze,vm=pm([].slice),mm=TypeError,gm=function(s,e){if(s<e)throw mm("Not enough arguments");return s},Sm=qs,vu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sm),Be=_e,bm=Vd,ym=Js,Eo=Ee,Tm=ot,mu=qe,$o=Kd,Em=vm,Ao=Ha,$m=gm,Am=vu,_m=Xs,_a=Be.setImmediate,wa=Be.clearImmediate,wm=Be.process,Nr=Be.Dispatch,km=Be.Function,_o=Be.MessageChannel,Pm=Be.String,Fr=0,Ci={},wo="onreadystatechange",Ni,Mt,Ur,Vr;mu(function(){Ni=Be.location});var rn=function(s){if(Tm(Ci,s)){var e=Ci[s];delete Ci[s],e()}},Hr=function(s){return function(){rn(s)}},ko=function(s){rn(s.data)},Po=function(s){Be.postMessage(Pm(s),Ni.protocol+"//"+Ni.host)};(!_a||!wa)&&(_a=function(e){$m(arguments.length,1);var t=Eo(e)?e:km(e),i=Em(arguments,1);return Ci[++Fr]=function(){bm(t,void 0,i)},Mt(Fr),Fr},wa=function(e){delete Ci[e]},_m?Mt=function(s){wm.nextTick(Hr(s))}:Nr&&Nr.now?Mt=function(s){Nr.now(Hr(s))}:_o&&!Am?(Ur=new _o,Vr=Ur.port2,Ur.port1.onmessage=ko,Mt=ym(Vr.postMessage,Vr)):Be.addEventListener&&Eo(Be.postMessage)&&!Be.importScripts&&Ni&&Ni.protocol!=="file:"&&!mu(Po)?(Mt=Po,Be.addEventListener("message",ko,!1)):wo in Ao("script")?Mt=function(s){$o.appendChild(Ao("script"))[wo]=function(){$o.removeChild(this),rn(s)}}:Mt=function(s){setTimeout(Hr(s),0)});var gu={set:_a,clear:wa},Su=function(){this.head=null,this.tail=null};Su.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var bu=Su,Rm=qs,Dm=/ipad|iphone|ipod/i.test(Rm)&&typeof Pebble!="undefined",Im=qs,Cm=/web0s(?!.*chrome)/i.test(Im),Ut=_e,Ro=Js,xm=Wa.f,Gr=gu.set,Lm=bu,Om=vu,Mm=Dm,Bm=Cm,Yr=Xs,Do=Ut.MutationObserver||Ut.WebKitMutationObserver,Io=Ut.document,Co=Ut.process,cs=Ut.Promise,xo=xm(Ut,"queueMicrotask"),ka=xo&&xo.value,ei,jr,qr,hs,Lo;if(!ka){var fs=new Lm,ps=function(){var s,e;for(Yr&&(s=Co.domain)&&s.exit();e=fs.get();)try{e()}catch(t){throw fs.head&&ei(),t}s&&s.enter()};!Om&&!Yr&&!Bm&&Do&&Io?(jr=!0,qr=Io.createTextNode(""),new Do(ps).observe(qr,{characterData:!0}),ei=function(){qr.data=jr=!jr}):!Mm&&cs&&cs.resolve?(hs=cs.resolve(void 0),hs.constructor=cs,Lo=Ro(hs.then,hs),ei=function(){Lo(ps)}):Yr?ei=function(){Co.nextTick(ps)}:(Gr=Ro(Gr,Ut),ei=function(){Gr(ps)}),ka=function(s){fs.head||ei(),fs.add(s)}}var Nm=ka,Fm=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},an=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Um=_e,vi=Um.Promise,yu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vm=yu,Hm=Xs,Gm=!Vm&&!Hm&&typeof window=="object"&&typeof document=="object",Ym=_e,xi=vi,jm=Ee,qm=qd,zm=uu,Wm=Pe,Qm=Gm,Km=yu,zr=Id,Oo=xi&&xi.prototype,Jm=Wm("species"),Pa=!1,Tu=jm(Ym.PromiseRejectionEvent),Xm=qm("Promise",function(){var s=zm(xi),e=s!==String(xi);if(!e&&zr===66||!(Oo.catch&&Oo.finally))return!0;if(!zr||zr<51||!/native code/.test(s)){var t=new xi(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jm]=i,Pa=t.then(function(){})instanceof i,!Pa)return!0}return!e&&(Qm||Km)&&!Tu}),zi={CONSTRUCTOR:Xm,REJECTION_EVENT:Tu,SUBCLASSING:Pa},mi={},Mo=Yt,Zm=TypeError,eg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw Zm("Bad Promise constructor");e=i,t=r}),this.resolve=Mo(e),this.reject=Mo(t)};mi.f=function(s){return new eg(s)};var tg=Ze,Ms=Xs,Pt=_e,Wi=Fe,ig=Xa,sg=en,rg=Yv,ag=Yt,Ra=Ee,ng=vt,og=zv,dg=pu,Eu=gu.set,nn=Nm,ug=Fm,lg=an,cg=bu,$u=Fd,Da=vi,on=zi,Au=mi,Zs="Promise",_u=on.CONSTRUCTOR,hg=on.REJECTION_EVENT;on.SUBCLASSING;var Wr=$u.getterFor(Zs),fg=$u.set,pg=Da&&Da.prototype,ri=Da,Qr=pg,wu=Pt.TypeError,Ia=Pt.document,dn=Pt.process,Ca=Au.f,vg=Ca,mg=!!(Ia&&Ia.createEvent&&Pt.dispatchEvent),ku="unhandledrejection",gg="rejectionhandled",Bo=0,Pu=1,Sg=2,un=1,Ru=2,vs,No,bg,Du=function(s){var e;return ng(s)&&Ra(e=s.then)?e:!1},Iu=function(s,e){var t=e.value,i=e.state==Pu,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Ru&&Tg(e),e.rejection=un),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(wu("Promise-chain cycle")):(d=Du(u))?Wi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Cu=function(s,e){s.notified||(s.notified=!0,nn(function(){for(var t=s.reactions,i;i=t.get();)Iu(i,s);s.notified=!1,e&&!s.rejection&&yg(s)}))},xu=function(s,e,t){var i,r;mg?(i=Ia.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Pt.dispatchEvent(i)):i={promise:e,reason:t},!hg&&(r=Pt["on"+s])?r(i):s===ku&&ug("Unhandled promise rejection",t)},yg=function(s){Wi(Eu,Pt,function(){var e=s.facade,t=s.value,i=Fo(s),r;if(i&&(r=lg(function(){Ms?dn.emit("unhandledRejection",t,e):xu(ku,e,t)}),s.rejection=Ms||Fo(s)?Ru:un,r.error))throw r.value})},Fo=function(s){return s.rejection!==un&&!s.parent},Tg=function(s){Wi(Eu,Pt,function(){var e=s.facade;Ms?dn.emit("rejectionHandled",e):xu(gg,e,s.value)})},ai=function(s,e,t){return function(i){s(e,i,t)}},oi=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=Sg,Cu(s,!0))},xa=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw wu("Promise can't be resolved itself");var i=Du(e);i?nn(function(){var r={done:!1};try{Wi(i,e,ai(xa,r,s),ai(oi,r,s))}catch(a){oi(r,a,s)}}):(s.value=e,s.state=Pu,Cu(s,!1))}catch(r){oi({done:!1},r,s)}}};_u&&(ri=function(e){og(this,Qr),ag(e),Wi(vs,this);var t=Wr(this);try{e(ai(xa,t),ai(oi,t))}catch(i){oi(t,i)}},Qr=ri.prototype,vs=function(e){fg(this,{type:Zs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:Bo,value:void 0})},vs.prototype=ig(Qr,"then",function(e,t){var i=Wr(this),r=Ca(dg(this,ri));return i.parent=!0,r.ok=Ra(e)?e:!0,r.fail=Ra(t)&&t,r.domain=Ms?dn.domain:void 0,i.state==Bo?i.reactions.add(r):nn(function(){Iu(r,i)}),r.promise}),No=function(){var s=new vs,e=Wr(s);this.promise=s,this.resolve=ai(xa,e),this.reject=ai(oi,e)},Au.f=Ca=function(s){return s===ri||s===bg?new No(s):vg(s)});tg({global:!0,constructor:!0,wrap:!0,forced:_u},{Promise:ri});sg(ri,Zs,!1,!0);rg(Zs);var Eg=Pe,Lu=Eg("iterator"),Ou=!1;try{var $g=0,Uo={next:function(){return{done:!!$g++}},return:function(){Ou=!0}};Uo[Lu]=function(){return this},Array.from(Uo,function(){throw 2})}catch(s){}var Ag=function(s,e){if(!e&&!Ou)return!1;var t=!1;try{var i={};i[Lu]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},_g=vi,wg=Ag,kg=zi.CONSTRUCTOR,Mu=kg||!wg(function(s){_g.all(s).then(void 0,function(){})}),Pg=Ze,Rg=Fe,Dg=Yt,Ig=mi,Cg=an,xg=tn,Lg=Mu;Pg({target:"Promise",stat:!0,forced:Lg},{all:function(e){var t=this,i=Ig.f(t),r=i.resolve,a=i.reject,n=Cg(function(){var o=Dg(t.resolve),u=[],d=0,l=1;xg(e,function(c){var h=d++,f=!1;l++,Rg(o,t,c).then(function(v){f||(f=!0,u[h]=v,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var Og=Ze,Mg=zi.CONSTRUCTOR,Vo=vi;Vo&&Vo.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(s){return this.then(void 0,s)}});var Bg=Ze,Ng=Fe,Fg=Yt,Ug=mi,Vg=an,Hg=tn,Gg=Mu;Bg({target:"Promise",stat:!0,forced:Gg},{race:function(e){var t=this,i=Ug.f(t),r=i.reject,a=Vg(function(){var n=Fg(t.resolve);Hg(e,function(o){Ng(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var Yg=Ze,jg=Fe,qg=mi,zg=zi.CONSTRUCTOR;Yg({target:"Promise",stat:!0,forced:zg},{reject:function(e){var t=qg.f(this);return jg(t.reject,void 0,e),t.promise}});var Wg=mt,Qg=vt,Kg=mi,Bu=function(s,e){if(Wg(s),Qg(e)&&e.constructor===s)return e;var t=Kg.f(s),i=t.resolve;return i(e),t.promise},Jg=Ze,Xg=Gt,Zg=Rc,eS=vi,tS=zi.CONSTRUCTOR,iS=Bu,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=Ze,La=vi,nS=qe,oS=Gt,dS=Ee,uS=pu,Ho=Bu,lS=La&&La.prototype,cS=!!La&&nS(function(){lS.finally.call({then:function(){}},function(){})});aS({target:"Promise",proto:!0,real:!0,forced:cS},{finally:function(s){var e=uS(this,oS("Promise")),t=dS(s);return this.then(t?function(i){return Ho(e,s()).then(function(){return i})}:s,t?function(i){return Ho(e,s()).then(function(){throw i})}:s)}});var hS=Gt,ln=hS,fS=ln,pS=fS("Promise","finally"),vS=pS,mS=vS,gS=mS,SS=gS,er=Gs(SS),Te;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var Je=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:H(t)}return s};const Go=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var D=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ce{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||k(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const bS=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return H(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const yS=5,TS=5,ES=500,Yo=7e3;class $S{constructor(e){this.subscription=new ae,this.loadMediaTimeoutSubscription=new ae,this.videoState=new ce(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===W.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:H(i)}break}default:H(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 ae;this.subscription.add(e),this.subscription.add(V(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 x;e.add(r.pipe(je(ES)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(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===W.Applying||Math.abs(o-a)>yS)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(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(),D(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:H(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:W.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&D(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=Tl(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=Je(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return k(u)&&(o.metadata.title=u),k(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===W.Applying||i.state===W.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(El(Yo).subscribe(()=>a(`timeout(${Yo})`)))});er(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===W.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:L.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var AS=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},_S=s=>{const e=new S(1/0),t=new x,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,v,g;const T=li(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(m=>m.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const m=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:m*1e3)!==null&&f!==void 0?f:NaN;k($)&&!isNaN($)&&e.next($)}const A=(v=T["x-delivery-type"])!==null&&v!==void 0?v:Mi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),v(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ci=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},wS=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ci}),!0),kS=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Xe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=ie(r),d=new ae;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},jt=(s,e,t)=>Xe(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),gt=(s,e,t,i)=>Xe(e,()=>({muted:s.muted,volume:s.volume}),r=>{k(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Dt=(s,e,t,i)=>Xe(e,()=>s.playbackRate,r=>{k(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),PS=s=>["__",s.language,s.label].join("|"),RS=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class dt{constructor(){this.available$=new x,this.current$=new S(void 0),this.error$=new x,this.subscription=new ae,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Xe(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(Xe(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(Xe(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(V(B(e,"addtrack"),B(e,"removetrack"),De(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(B(e,"change"),De(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;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){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(dt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:PS(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(ie(e)||!RS(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){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const cn=s=>{s.removeAttribute("src"),s.load()},DS=s=>{try{s.pause(),s.playbackRate=0,cn(s),s.remove()}catch(e){console.error(e)}};class IS{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 Oa=window.WeakMap?new WeakMap:new IS,St=s=>{let e=s.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),s.appendChild(e)),Oa.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=s=>{const e=Oa.get(s);Oa.delete(s),e?cn(s):DS(s)};class tr{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 Nu=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},jo=s=>{const e=Nu(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},CS=s=>{const e=Nu(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Ma=3;class xS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Ma&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ma))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Fu=(s,e,t=Ma)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const yt=s=>{const e=m=>B(s,m).pipe(ui(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>B(s,m))).pipe(w(m=>m.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=V(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Fu(s.buffered,s.currentTime))),n=Ua().browser===yd.Safari?Ne({play:e("play").pipe(ge()),playing:e("playing")}).pipe(ui(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(re(()=>!!(s.error||s.played.length)),w(()=>{var m;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(m=s.error)!==null&&m!==void 0?m:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new x,h=.3;let f;l.subscribe(m=>{s.loop&&k(f)&&k(m)&&f>=s.duration-h&&m<=h&&c.next(f),f=m});const v=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(CS(s));v.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(jo(s));return B(s,"fullscreenchange").pipe(w(()=>jo(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(re(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},hn=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var LS=Ze,OS=Qs,MS=Ja,BS=Ka;LS({target:"Array",proto:!0},{at:function(e){var t=OS(this),i=MS(t),r=BS(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var NS=ln,FS=NS("Array","at"),US=FS,VS=US,HS=VS,GS=HS,st=Gs(GS);let fn=!1,ct={};const YS=s=>{fn=s},jS=()=>{ct={}},qS=s=>{s(ct)},ms=(s,e)=>{var t;fn&&(ct.meta=(t=ct.meta)!==null&&t!==void 0?t:{},ct.meta[s]=e)};class rt{constructor(e){this.name=e}next(e){var t,i;if(!fn)return;ct.series=(t=ct.series)!==null&&t!==void 0?t:{};const r=(i=ct.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),ct.series[this.name]=r}}var Nt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Nt||(Nt={}));const zS=new rt("best_bitrate"),WS=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class QS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=me()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const gi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,v,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},m=E&&Vt(E),b=i.considerPlaybackRate&&k(o)?o:1,$=s.filter(U=>!Oi(U.quality)).sort((U,I)=>Ii(U.quality,I.quality)?-1:1),R=(f=st($,-1))===null||f===void 0?void 0:f.quality,j=(v=st($,0))===null||v===void 0?void 0:v.quality,X=ie(r)||k(r.min)&&k(r.max)&&ws(r.max,r.min)||k(r.min)&&j&&Ii(r.min,j)||k(r.max)&&R&&ws(r.max,R),F=b*WS(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),Y={},O=$.filter(U=>(m?ws(U.quality,m):!0)?(k(t)&&isFinite(t)&&k(U.bitrate)?t-a>=U.bitrate*F:!0)?i.lazyQualitySwitch&&k(i.minBufferToSwitchUp)&&u&&!Oi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Ii(U.quality,u.quality)?(Y[U.quality]=Nt.Buffer,!1):!!l&&pa(U.quality,l)?(Y[U.quality]=Nt.DroppedFramesLimit,!1):X||(ie(r.max)||Td(U.quality,r.max))&&(ie(r.min)||pa(U.quality,r.min))?!0:(Y[U.quality]=Nt.FitsQualityLimits,!1):(Y[U.quality]=Nt.FitsThroughput,!1):(Y[U.quality]=Nt.FitsContainer,!1))[0];O&&O.bitrate&&zS.next(O.bitrate);const G=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];G.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
|
|
7
7
|
[available tracks] ${s.map(U=>U.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
@@ -26,7 +26,7 @@ import{ValueSubject as S,Subject as x,Subscription as ae,isNonNullable as k,Erro
|
|
|
26
26
|
[selected track] ${G.quality}
|
|
27
27
|
`});const ne=G&&d&&d.history[G.id]&&me()-d.history[G.id]<=i.trackCooldown&&(!d.last||G.id!==d.last.id);if(G!=null&&G.id&&d&&!ne&&d.recordSelection(G),ne&&(d!=null&&d.last)){const U=d.last;return d==null||d.recordSwitch(U),c({message:`
|
|
28
28
|
[last selected] ${U.quality}
|
|
29
|
-
`}),U}return d==null||d.recordSwitch(G),G};var Ie=s=>new URL(s).hostname;const KS=300,Bs=(s,e=KS)=>new Hs(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Pl(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),k(u)&&k(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class ir{constructor(){this.onDroopedVideoFramesLimit$=new x,this.subscription=new ae,this.playing=!1,this.tracks=[],this.forceChecker$=new x,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&&!Oi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=i-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&&Ii(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,i)}}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(B(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Cs(this.droppedFramesChecker.checkTime).pipe(re(()=>this.playing),re(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(je(this.droppedFramesChecker.checkTime)),i=V(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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,i;const r=(i=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>ws(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||i===void 0?void 0:i[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}}const wi={};var Q;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const ye=(s,e)=>new Hs(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class qo{constructor(e){this.subscription=new ae,this.videoState=new ce(Q.DOWNLOADING_LIB),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.videoTracks$=new S([]),this.frameRatesByFrameHeight={},this.isLive$=new S(void 0),this.maxSeekBackTime$=new S(1/0),this.availableFrom$=new S(void 0),this.elementSize$=new S(void 0),this.liveOffset=new tr,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&t!==Q.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:H(t)}break}case p.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:H(t)}break}case p.PLAYING:{switch(t){case Q.PLAYING:break;case Q.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Q.READY:this.play();break;case Q.STOPPED:this.prepare();break;default:H(t)}break}case p.PAUSED:{switch(t){case Q.PLAYING:this.pause(),this.liveOffset.pause();break;case Q.PAUSED:break;case Q.READY:this.videoState.setState(Q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED);break;case Q.STOPPED:this.prepare();break;default:H(t)}break}default:H(i)}},this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:L.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);er(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(wi.MediaPlayer=r.MediaPlayer,wi.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){P(wi.MediaPlayer,"dashjs not loaded"),P(wi.Debug,"dashjs not loaded"),this.player=wi.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?hn(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&kS(this.player),AS(this.player),this.params.tuning.requestQuick&&wS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,b)=>this.subscription.add(m.subscribe(b,i));r(Bs(this.video),this.elementSize$),r(ye(this.player,"error").pipe(w(m=>{const b=typeof m.error=="object"?m.error.code:m.error,$=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${b}`,message:$}})),e.error$),r(ye(this.player,"playbackError").pipe(w(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=ye(this.player,"qualityChangeRendered").pipe(re(({mediaType:m})=>m==="video"),w(({newQuality:m})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m))===null||b===void 0?void 0:b.track}));a.pipe(re(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(re(({to:m})=>m===Q.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(Xe(t.videoTrack,()=>{var m,b;const $=this.player.getQualityFor("video");return(b=(m=this.videoTracks$.getValue().find(({bitrateInfo:R})=>R.qualityIndex===$))===null||m===void 0?void 0:m.track)===null||b===void 0?void 0:b.id},m=>{var b;if(ie(m))return;const $=(b=this.videoTracks$.getValue().find(({track:R})=>R.id===m))===null||b===void 0?void 0:b.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a.pipe(w(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Xe(t.autoVideoTrackSwitching,()=>{var m,b,$;return($=(b=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||$===void 0?void 0:$.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(ye(this.player,"bufferStateChanged").pipe(re(({mediaType:m})=>m==="video"),w(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(ye(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:b}})=>{var $,R;const j=this.player.getDashMetrics(),X=j.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),F=($=j.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&$!==void 0?$:Mi.HTTP1,Y=(R={1:!0,0:!1}[X])!==null&&R!==void 0?R:void 0;this.params.output.httpConnectionType$.next(F),this.params.output.httpConnectionReused$.next(Y),e.hostname$.next(Ie(b))}),r(ye(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:b,availableFrom:$}}})=>{this.isLive$.next(b),this.availableFrom$.next($.getTime()),b||e.duration$.next(m);const R=[],j=this.player.getQualityFor("video");let X;for(const F of this.player.getBitrateInfoListFor("video")){const Y=F.qualityIndex.toString(10),K=Vt(F),O=F.bitrate/1e3,G={width:F.width,height:F.height},ne=this.frameRatesByFrameHeight[F.height];if(K){const U={id:Y,quality:K,bitrate:O,size:G,fps:ne};R.push({track:U,bitrateInfo:F}),F.qualityIndex===j&&(X=U)}}this.videoTracks$.next(R),e.availableVideoTracks$.next(R.map(({track:F})=>F)),X&&e.currentVideoTrack$.next(X),this.videoState.setState(Q.STREAM_INITIALIZED),this.videoState.startTransitionTo(Q.READY)}),r(ye(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const b=m.requestEndDate.getTime()-m.firstByteDate.getTime(),$=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,b)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=gi(this.videoTracks$.getValue().map(({track:j})=>j),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const R=this.videoTracks$.getValue().find(({track:j})=>j===b);R!=null&&R.bitrateInfo&&this.player.setQualityFor("video",R==null?void 0:R.bitrateInfo.qualityIndex,!1)}),r(Ne({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(re(k))}).pipe(re(({isLive:m})=>m),w(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=ye(this.player,"playbackTimeUpdated").pipe(w(({time:m})=>m!=null?m:0));r(Ne({availableFrom:this.availableFrom$.pipe(re(k)),currentTime:n}),({availableFrom:m,currentTime:b})=>this.params.output.liveTime$.next(m+b*1e3)),r(n.pipe(re(()=>this.isLive$.getValue()===!1)),e.position$),r(ye(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(ye(this.player,"playbackEnded"),e.endedEvent$),r(ye(this.player,"playbackProgress").pipe(w(()=>Fu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(ye(this.player,"playbackPlaying"),()=>{this.videoState.setState(Q.PLAYING),D(t.playbackState,p.PLAYING)}),r(ye(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(ye(this.player,"playbackPaused"),()=>{this.videoState.setState(Q.PAUSED),D(t.playbackState,p.PAUSED)}),r(ye(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===Q.READY&&this.videoState.setState(Q.READY)}),r(this.isLive$,e.isLive$),r(Bs(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=_S(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(ye(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ne({isLive:this.isLive$,isShort:e.duration$.pipe(w(m=>m<60))}),({isLive:m,isShort:b})=>{const $=!m&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(re(m=>m>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(ye(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(ye(this.player,"playbackPlaying").pipe(ge(),ui(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(ye(this.player,"manifestLoaded"),m=>{var b,$,R,j,X,F,Y;if(!(($=(b=m.data)===null||b===void 0?void 0:b.Period)===null||$===void 0)&&$.AdaptationSet){const K=[];for(const O of(j=(R=m.data)===null||R===void 0?void 0:R.Period)===null||j===void 0?void 0:j.AdaptationSet)if(O.contentType==="text"){const G=(X=O.Representation)===null||X===void 0?void 0:X.id,ne=new URL((F=O.Representation)===null||F===void 0?void 0:F.BaseURL,(Y=m.data)===null||Y===void 0?void 0:Y.baseUri).toString(),U="internal",I=O.lang;K.push({id:G,url:ne,type:U,language:I})}t.internalTextTracks.startTransitionTo(K)}}),this.subscription.add(jt(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:g,inFullscreen$:T,pause$:A,playing$:E}=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:E,pause$:A,tracks$:this.videoTracks$.pipe(w(m=>m.map(({track:b})=>b)))}),this.subscription.add(gt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Dt(this.video,t.playbackRate,v,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(T.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Q.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Q.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=Je(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Te.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Q.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}bt(this.video),this.params.output.element$.next(void 0)}}var Qi=s=>{switch(s){case"mobile":return He.Q_144P;case"lowest":return He.Q_240P;case"low":return He.Q_360P;case"sd":case"medium":return He.Q_480P;case"hd":case"high":return He.Q_720P;case"fullhd":case"full":return He.Q_1080P;case"quadhd":case"quad":return He.Q_1440P;case"ultrahd":case"ultra":return He.Q_2160P}};const zo=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var It=s=>ue(void 0,void 0,void 0,function*(){const e=s.muted;try{yield s.play()}catch(t){if(!zo(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{yield s.play()}catch(i){return zo(i)&&(s.muted=!1,console.warn(i)),!1}}return!0});function ke(){return me()}function Uu(s){return ke()-s}function Wo(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function JS(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ds(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,g=2e3,T=()=>{if(u)return;P(l);const O=Uu(l);let G;if(O<g){G=g-O,setTimeout(T,G);return}g*=2,g>v&&(g=v),n&&n.abort(),n=new r,R()};const A=O=>(a=O,K),E=O=>(c=O,K),m=()=>(f="json",K),b=()=>{if(!u){if(--d>=0){T(),i&&i();return}u=!0,c&&c(),t&&t()}},$=O=>(h=O,K),R=()=>{l=ke(),n=new r,n.open("get",s);let O=0,G,ne=0;const U=()=>(P(l),Math.max(l,Math.max(G||0,ne||0)));if(a&&n.addEventListener("progress",I=>{const N=ke();a.updateChunk&&I.loaded>O&&(a.updateChunk(U(),I.loaded-O),O=I.loaded,G=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>b())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const N=n.response.byteLength-O;N&&a.updateChunk&&a.updateChunk(U(),N)}c&&c(),n&&e(n.response)}else b()}),n.addEventListener("error",()=>{b()}),h){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ne=ke(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),K},K={withBitrateReporting:A,withParallel:$,withJSONResponse:m,withRetryCount:O=>(d=O,K),withRetryInterval:(O,G)=>(k(O)&&(g=O),k(G)&&(v=G),K),withTimeout:O=>(o=O,K),withFinally:E,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return K}const XS=100,ZS=2e3,eb=500;let tb=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,i){return{start:e,end:t,bytes:i}}_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-eb;if(t-e>ZS){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=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;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>XS&&(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 ib{constructor(e,t,i,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=i,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 i=ke(),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=ke()-i,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=Ds(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=ke()}_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=ke();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(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=i,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 gs=1e4,Ss=3,sb=300,rb=2e3,ab=6e4,nb=10,ob=1,db=500;class ub{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 tb(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 i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,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):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}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:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{JS(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 ib(Ss,gs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const b=a&&(!l||l===this.rep);return b||t("Not running!"),b},h=(b,$,R)=>{u&&u.abort(),u=Ds(this.urlResolver.resolve(b,!1),$,R,()=>this._retryCallback()).withTimeout(gs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ss).withFinally(()=>{u=null}).send()},f=(b,$,R)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),$,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=b=>{const $=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${$}=>${b}`),i.playbackRate=b)},g=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const R=ke()-1e4;let j=0;for(let F=0;F<this.bufferStates.length;F++){const Y=this.bufferStates[F];b=Math.min(b,Y.buf),Y.ts<R&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${b} drop=${j} jitter=${this.sourceJitter}`);let X=b-ob;this.sourceJitter>=0?X-=this.sourceJitter/2:this.sourceJitter-=1,X>3?v(1.15):X>1?v(1.1):X>.3?v(1.05):v(1)}},A=b=>{let $;const R=()=>$&&$.start?$.start.length:0,j=I=>$.start[I]/1e3,X=I=>$.dur[I]/1e3,F=I=>$.fragIndex+I,Y=(I,N)=>({chunkIdx:F(I),startTS:j(I),dur:X(I),discontinuity:N}),K=()=>{let I=0;if($&&$.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=N;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let Se=$.dur.length-1;for(;Se>=0&&(pe-=$.dur[Se],!(pe<=0));--Se);I=Math.min(Se,$.dur.length-1-Z),I=Math.max(I,0)}return Y(I,!0)},O=I=>{const N=R();if(!(N<=0)){if(k(I)){for(let Z=0;Z<N;Z++)if(j(Z)>I)return Y(Z)}return K()}},G=I=>{const N=R(),Z=I?I.chunkIdx+1:0,pe=Z-$.fragIndex;if(!(N<=0)){if(!I||pe<0||pe-N>nb)return t(`Resync: offset=${pe} bChunks=${N} chunk=`+JSON.stringify(I)),K();if(!(pe>=N))return Y(Z-$.fragIndex,!1)}},ne=(I,N,Z)=>{d&&d.abort(),d=Ds(this.urlResolver.resolve(I,!0,this.lowLatency),N,Z,()=>this._retryCallback()).withTimeout(gs).withRetryCount(Ss).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,N)=>{ne(b,Z=>{if(!c())return;$=Z;const pe=!!$.lowLatency;pe!==this.lowLatency&&g(pe);let Se=0;for(let Ce=0;Ce<$.dur.length;++Ce)Se+=$.dur[Ce];Se>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,I(O(N))},()=>this._handleNetworkError())},nextChunk:G}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:b=>{const{videoElement:$,logger:R}=this.params;let j=A(e.jidxUrl),X,F,Y,K,O=0,G,ne,U;const I=()=>{G&&(clearTimeout(G),G=void 0);const ee=Math.max(db,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Re=O+ee,Ue=ke(),xe=Math.min(1e4,Re-Ue);O=Ue;const Ve=()=>{d||c()&&j.seek(()=>{c()&&(O=ke(),N(),I())})};xe>0?G=window.setTimeout(()=>{this.paused?I():Ve()},xe):Ve()},N=()=>{let ee;for(;ee=j.nextChunk(K);)K=ee,et(ee);const Re=j.nextChunk(Y);if(Re){if(Y&&Re.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?I():(E(),this._initPlayerWith(e));return}Ce(Re)}else I()},Z=(ee,Re)=>{if(!c()||!this.sourceBuffer)return;let Ue,xe,Ve;const qt=Ct=>{window.setTimeout(()=>{c()&&Z(ee,Re)},Ct)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),qt(100);else{const Ct=ke(),zt=$.currentTime;!this.paused&&$.buffered.length>1&&ne===zt&&Ct-U>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ne!==zt&&(ne=zt,U=Ct);const Wt=this._getBufferSizeSec();if(Wt>30)R(`Buffered ${Wt} seconds; delaying appendBuffer`),qt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Ct,buf:Wt}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Re&&Re()}catch(Ji){if(Ji.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Ue=this.sourceBuffer.buffered.start(0),xe=zt,xe-Ue>4&&this.sourceBuffer.remove(Ue,xe-3)),qt(1e3);else throw Ji}}},pe=()=>{F&&X&&(R([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Y)]),Z(F,function(){F=null,N()}))},Se=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ce=ee=>{c()&&f(Se(ee),(Re,Ue)=>{if(c()){if(Ue/=1e3,F=Re,Y=ee,n=ee.startTS,Ue){const xe=Math.min(10,ee.dur/Ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}pe()}},()=>this._handleNetworkError())},et=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(ee),!1)))},Tt=ee=>{c()&&(e.cachedHeader=ee,Z(ee,()=>{X=!0,pe()}))};a=!0,j.seek(ee=>{if(c()){if(O=ke(),!ee){I();return}K=ee,!ie(b)||ee.startTS>b?Ce(ee):(Y=ee,N())}},b),e.cachedHeader?Tt(e.cachedHeader):h(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=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,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=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=ke();if(this.chunkRateEstimator.addInterval(h,v,f)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:T}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Uu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=ke();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ds(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(gs).withRetryCount(Ss).withRetryInterval(sb,rb).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;It(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},ab))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const lb=[z.PAUSED,z.PLAYING,z.READY],cb=[z.PAUSED,z.PLAYING,z.READY];class hb{constructor(e){this.subscription=new ae,this.videoState=new ce(z.STOPPED),this.representations$=new S([]),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.maxSeekBackTime$=new S(1/0),this.zeroTime$=new S(void 0),this.liveOffset=new tr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Qi(c.name))!==null&&n!==void 0?n:Vt(c.video),v=c.bitrate/1e3,g=Object.assign({},c.video);if(!f)continue;const T={id:h,quality:f,bitrate:v,size:g};l.push({track:T,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.MANIFEST_READY&&this.videoState.setState(z.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),k(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{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!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(cb.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===W.Requested&&lb.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(Je(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(n===p.PAUSED)this.videoState.setState(z.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(z.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(z.PAUSED)})}return;case z.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(z.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(z.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(Je(this.params.source.url,c))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(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=St(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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===W.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ne({zeroTime:this.zeroTime$.pipe(re(k)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(jt(this.video,this.params.desiredState.isLooped,t)).add(gt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Dt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&$l(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case z.MANIFEST_READY:case z.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 z.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case z.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,De(["init"])).pipe(je(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),bt(this.video)}createLiveDashPlayer(){const e=new ub({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&k(u)?u:(a=gi(o.map(({track:v})=>v),{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}))===null||a===void 0?void 0:a.id,c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((c&&l||l!==h)&&this.setVideoTrack(l),f&&this.setAutoQuality(d),c||f||l!==h){const v=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(v,"Representations missing"),this.dash.startPlay(v,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===z.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Je(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Vu=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?Mi.HTTP1:(e=i)!==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}},wt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const fb=s=>{const e=document.createElement("a");return e.href=s,e.origin},pb=s=>{const e=document.createElement("a");return e.href=s,e.host};class Hu{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=li(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(pb(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ns{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=g=>{r(Ns._str2ua(g.substr(u))),u=g.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=ci(v)),this._lastXhr=new Hu(v,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const T=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:T,speed:8*g.length/(T/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-u>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const T=Date.now()-c;h>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:h,duration:T,speed:8*h/(T/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,T,A)=>this._params.onError(g,T,A))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ns._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class vb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ci(i)),new Hu(i,t,r=>{this.attachManifest(r,t,fb(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,v,g,T,A,E,m,b,$,R,j,X,F,Y,K,O;const G=d.getElementsByTagName("SegmentBase")[0],ne=G&&n(G,"indexRange").split("-"),U=G&&G.getElementsByTagName("Initialization")[0],I=U&&n(U,"range").split("-");if(!I||!ne){const et=d.parentElement;if((et==null?void 0:et.getAttribute("contentType"))==="text"){const Tt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),Re=(g=et.getAttribute("lang"))!==null&&g!==void 0?g:void 0;ee&&u.push({id:Tt,url:ee,language:Re})}return}const N=.1,Z=Number((T=d.attributes.getNamedItem("bandwidth"))===null||T===void 0?void 0:T.value),pe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Se;const Ce=(E=(A=d.attributes.getNamedItem("frameRate"))===null||A===void 0?void 0:A.value)!==null&&E!==void 0?E:void 0;Se=Ce?hn(Ce):void 0,o.push({width:Number((m=d.attributes.getNamedItem("width"))===null||m===void 0?void 0:m.value),height:Number((b=d.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:Z,baseURL:pe,failoverHosts:t,indexFrom:Number(ne[0]),indexTo:Number(ne[1]),initFrom:Number(I[0]),initTo:Number(I[1]),codecs:(R=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&R!==void 0?R:void 0,mimeType:(X=(j=d.attributes.getNamedItem("mimeType"))===null||j===void 0?void 0:j.value)!==null&&X!==void 0?X:void 0,fps:Se,bufferSize:N*Z/8,bufferLength:N,name:(Y=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Y!==void 0?Y:void 0,id:(O=(K=d.attributes.getNamedItem("id"))===null||K===void 0?void 0:K.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,u=v}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ns({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||ie(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var J;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const mb=[J.PAUSED,J.PLAYING];class gb{constructor(e){this.videoState=new ce(J.STOPPED),this.subscription=new ae,this.representations$=new S([]),this.currentRepresentation$=new S(void 0),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.elementSize$=new S(void 0),this.dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&Qi(u.name))!==null&&n!==void 0?n:Vt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const v={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:v,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(J.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===W.Requested&&mb.includes(t)&&this.seek(n.position,n.forcePrecise),t){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_LOADED),this.prepare();return;case J.MANIFEST_LOADED:this.videoState.startTransitionTo(J.INITIAL_REPRESENTATION_SELECTED);return;case J.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(J.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case J.METADATA_LOADED:this.videoState.startTransitionTo(J.READY),this.dash.updateRefsForCurrentTime();return;case J.READY:r===p.READY?D(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case J.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new xS(this.video),this.dash=new vb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:L.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=yt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{ie(this.params.desiredState.seekState.getState().state!==W.Applying)&&(this.videoState.getState()===J.PLAYING||this.videoState.getState()===J.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(w(o=>o.map(({track:u})=>u)))}),n(Bs(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===J.READY&&this.videoState.setState(J.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(J.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(V(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).pipe(w(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),T=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let A;if(!T&&k(f))A=f;else{const E=wt(this.video.buffered,this.video.currentTime*1e3),m=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(E/m,1);A=(u=gi(c.map(({track:R})=>R),{container:g,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:R})=>R===l))===null||o===void 0?void 0:o.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const $=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to)}return k(A)?(d=c.find(({track:E})=>E.id===A))===null||d===void 0?void 0:d.representation:void 0}),ve()).subscribe(this.currentRepresentation$,i)).add(Ne({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(re(o=>o.to===J.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(re(k))}).pipe(ge()).subscribe(()=>this.videoState.setState(J.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(re(k),ve((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=wt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ie(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=Vu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),ui(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(re(k)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return H(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}}var Ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ae||(Ae={}));var Fs;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Fs||(Fs={}));var Ye;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Ye||(Ye={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var hi;(function(s){s.MP4="mp4",s.WEBM="webm"})(hi||(hi={}));var Us;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Us||(Us={}));var he;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(he||(he={}));class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[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 Gu 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 Yu=class{constructor(){Object.defineProperty(this,"signal",{value:new Gu,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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Yu.prototype[Symbol.toStringTag]="AbortController",Gu.prototype[Symbol.toStringTag]="AbortSignal");function ju(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Sb(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!ju({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const sr=ju({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qu=sr?Sb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Fi=sr?qu.fetch:window.fetch;sr?qu.Request:window.Request;const di=sr?Yu:window.AbortController;var Ba=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const bb=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},yb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=yb?bb:window.requestIdleCallback;var Kr,Jr;let zu=!1;try{zu=Ua().browser===yd.Safari&&parseInt((Jr=(Kr=navigator.userAgent.match(/Version\/(\d+)/))===null||Kr===void 0?void 0:Kr[1])!==null&&Jr!==void 0?Jr:"",10)<16}catch(s){console.error(s)}class Tb{constructor(e){this.bufferFull$=new x,this.error$=new x,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return ue(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ue(this,void 0,void 0,function*(){return new Promise(t=>{let i;zu&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:L.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:H(t)}}}var Jo=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class ut{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 Wu extends ut{}class Eb extends ut{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class $b extends ut{parseChildrenBoxes(){return Si(this.content)}}class Ab extends ut{constructor(e){super(e),this.data=this.content}}class Ki extends ut{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _b extends Ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class wb extends ut{parseChildrenBoxes(){return Si(this.content)}}class kb extends ut{parseChildrenBoxes(){return Si(this.content)}}var Ft;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ft||(Ft={}));class Pb extends Ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ft.MONOSCOPIC;break;case 1:this.stereoMode=Ft.TOP_BOTTOM;break;case 2:this.stereoMode=Ft.LEFT_RIGHT;break;case 3:this.stereoMode=Ft.STEREO_CUSTOM;break;case 4:this.stereoMode=Ft.RIGHT_LEFT;break}this.cursor+=1}}class Rb extends Ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Db extends Ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ib extends ut{parseChildrenBoxes(){return Si(this.content)}}class Cb extends Ki{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 xb extends ut{parseChildrenBoxes(){return Si(this.content)}}class Lb extends ut{parseChildrenBoxes(){return Si(this.content)}}const Ob={ftyp:Eb,moov:$b,mdat:Ab,sidx:_b,trak:wb,mdia:Ib,tkhd:Cb,minf:xb,sv3d:kb,st3d:Pb,prhd:Rb,proj:Lb,equi:Db,unknown:Wu};class Mb{createBox(e,t){const i=Ob[e];return i?new i(t):new Wu(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return rr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const rr=new Mb;function Di(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const a=t.decode(new DataView(s.buffer,i,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+o>s.byteLength?null:rr.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Bb(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Di(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function Si(s){const e=[];let t=0;for(;t<s.byteLength;){const i=rr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Nb=new TextDecoder("ascii"),Fb=s=>Nb.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Ub=s=>{const e=rr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Vb=s=>{const e=Bb(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},Hb=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Di(s,"sv3d")){e.is3dVideo=!0;const i=Di(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Di(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Di(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Gb={validateData:Fb,parseInit:Hb,getIndexRange:()=>{},parseSegments:Ub,parseFeedableSegmentChunk:Vb};var _;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(_||(_={}));var C;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(C||(C={}));const Xo={[_.EBML]:{type:C.Master},[_.EBMLVersion]:{type:C.UnsignedInteger},[_.EBMLReadVersion]:{type:C.UnsignedInteger},[_.EBMLMaxIDLength]:{type:C.UnsignedInteger},[_.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[_.DocType]:{type:C.String},[_.DocTypeVersion]:{type:C.UnsignedInteger},[_.DocTypeReadVersion]:{type:C.UnsignedInteger},[_.Void]:{type:C.Binary},[_.Segment]:{type:C.Master},[_.SeekHead]:{type:C.Master},[_.Seek]:{type:C.Master},[_.SeekID]:{type:C.Binary},[_.SeekPosition]:{type:C.UnsignedInteger},[_.Info]:{type:C.Master},[_.TimestampScale]:{type:C.UnsignedInteger},[_.Duration]:{type:C.Float},[_.Tracks]:{type:C.Master},[_.TrackEntry]:{type:C.Master},[_.Video]:{type:C.Master},[_.Projection]:{type:C.Master},[_.ProjectionType]:{type:C.UnsignedInteger},[_.ProjectionPrivate]:{type:C.Master},[_.Chapters]:{type:C.Master},[_.Cluster]:{type:C.Master},[_.Timestamp]:{type:C.UnsignedInteger},[_.SilentTracks]:{type:C.Master},[_.SilentTrackNumber]:{type:C.UnsignedInteger},[_.Position]:{type:C.UnsignedInteger},[_.PrevSize]:{type:C.UnsignedInteger},[_.SimpleBlock]:{type:C.Binary},[_.BlockGroup]:{type:C.Master},[_.EncryptedBlock]:{type:C.Binary},[_.Attachments]:{type:C.Master},[_.Tags]:{type:C.Master},[_.Cues]:{type:C.Master},[_.CuePoint]:{type:C.Master},[_.CueTime]:{type:C.UnsignedInteger},[_.CueTrackPositions]:{type:C.Master},[_.CueTrack]:{type:C.UnsignedInteger},[_.CueClusterPosition]:{type:C.UnsignedInteger},[_.CueRelativePosition]:{type:C.UnsignedInteger},[_.CueDuration]:{type:C.UnsignedInteger},[_.CueBlockNumber]:{type:C.UnsignedInteger},[_.CueCodecState]:{type:C.UnsignedInteger},[_.CueReference]:{type:C.Master},[_.CueRefTime]:{type:C.UnsignedInteger}},Qu=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Vs(s,t),r=i in Xo,a=r?Xo[i].type:C.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=Vs(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Vs=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},at=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return Vs(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:H(e)}},fi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Qu(i);if(!e(r))return;r.type===C.Master&&fi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Yb=s=>{if(s.getUint32(0)!==_.EBML)return!1;let e,t,i;const r=Qu(s);return fi(r.value,({tag:a,type:n,value:o})=>(a===_.EBMLReadVersion?e=at(o,n):a===_.DocType?t=at(o,n):a===_.DocTypeReadVersion&&(i=at(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ku=[_.Info,_.SeekHead,_.Tracks,_.TrackEntry,_.Video,_.Projection,_.ProjectionType,_.ProjectionPrivate,_.Chapters,_.Cluster,_.Cues,_.Attachments,_.Tags],jb=[_.Timestamp,_.SilentTracks,_.SilentTrackNumber,_.Position,_.PrevSize,_.SimpleBlock,_.BlockGroup,_.EncryptedBlock],qb=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return fi(s,({tag:h,type:f,value:v,valueSize:g})=>{if(h===_.SeekID){const T=at(v,f);d=Vs(T)}else h!==_.SeekPosition&&(d=void 0);return h===_.Segment?(e=v.byteOffset,t=v.byteOffset+g):h===_.Info?a=!0:h===_.SeekHead?n=!0:h===_.TimestampScale?i=at(v,f):h===_.Duration?r=at(v,f):h===_.SeekPosition&&d===_.Cues?u=at(v,f):h===_.Tracks?fi(v,({tag:T,type:A,value:E})=>T===_.ProjectionType?(l=at(E,A)===1,!1):!0):a&&n&&Ku.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zb=s=>{if(ie(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wb=(s,e)=>{let t=!1,i=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return fi(s,({tag:o,type:u,value:d})=>{switch(o){case _.Cues:t=!0;break;case _.CuePoint:n&&r(n)&&a.push(n),n={};break;case _.CueTime:n&&(n.time=at(d,u));break;case _.CueTrackPositions:break;case _.CueClusterPosition:n&&(n.position=at(d,u));break;default:t&&Ku.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Qb=s=>{let e=0,t=!1;try{fi(s,i=>i.tag===_.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):jb.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[_.SimpleBlock,_.BlockGroup,_.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Kb={validateData:Yb,parseInit:qb,getIndexRange:zb,parseSegments:Wb,parseFeedableSegmentChunk:Qb},Ju=1e4,Jb=3e4,Xb=5e3,Zb=Ju,ey=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Qi(a):void 0)!==null&&n!==void 0?n:Vt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},ty=({id:s,bitrate:e})=>({id:s,bitrate:e}),iy=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=st(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:st(s,-1)},sy=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),bs=s=>{const e=[];let t=0,i=s.length-1;for(;t<Ju&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Zo{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new S(!1),this.fullyBuffered$=new S(!1),this.playingRepresentation$=new S(void 0),this.playingRepresentationInit$=new S(void 0),this.error$=new x,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ae,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new di,this.destroyAbortController=new di,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){const c=this.representations.get(l);P(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Tb(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const T=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=T,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id),v=this.parsedInitData.get(c.id);if(P(h,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield M(void 0);this.searchGaps(f,c),yield yield M(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v)})}.bind(this)),this.switchTo=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=l;const c=this.representations.get(l);P(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(ie(f)||ie(h)?yield yield M(this.loadInit(c,"high",!1)):f instanceof Promise&&(yield yield M(f)),h=this.segments.get(l),P(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal));const v=this.getCurrentPosition();k(v)&&(this.searchGaps(h,c),this.maintain(v))})}.bind(this)),this.seekLive=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield M(void 0);for(const T of this.representations.keys()){const A=l.find(b=>b.id===T);A&&this.representations.set(T,A);const E=this.representations.get(T);if(!E)return yield M(void 0);const m=bs(E.segmentReference.segments);this.segments.set(E.id,m)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=bs(h.segmentReference.segments),v=this.initData.get(h.id);if(P(v,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(v instanceof ArrayBuffer))return yield M(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield M(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(f,h),yield yield M(this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!(d!=null&&d.dynamic),this.container=i,i){case hi.MP4:this.containerParser=Gb;break;case hi.WEBM:this.containerParser=Kb;break;default:H(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),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 di,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=wt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=wt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=st(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&wt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=st(i,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;k(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n)return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=st(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=bs(o);this.segments.set(n.id,[...c])}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const g=h<=i&&f>=i,T=h>i||g||v===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=i+A||f<=i+A;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&T&&E&&this.sourceBuffer&&!Ba(this.sourceBuffer.buffered,i))&&T&&E});if(r===-1)return[];if(t!==Ye.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ye.BYTE_RANGE:{r=t.segmentReference.url,a={from:st(e,0).byte.from,to:st(e,-1).byte.to};break}case Ye.TEMPLATE:{const d=st(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:H(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield Oe(u,function(){return Me(this,arguments,function*(){const d=kn(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)}})})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(i=wt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===te.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=te.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Ye.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const T=f?h.byte.from-i:0,A=f?h.byte.to-i:e.byteLength,E=T<r,m=A<=r;if(h.status===te.DOWNLOADING&&E&&m){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const b=new DataView(e.buffer,e.byteOffset+T,v);this.sourceBufferTaskQueue.append(b,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(v,r-T),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+T+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===v?b:this.containerParser.parseFeedableSegmentChunk(b);$!=null&&$.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(R=>{if(a.aborted)n();else if(R)c.fedBytes+=$.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ko(()=>er(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Oe(this.destroyAbortController.signal,function(){return Me(this,arguments,function*(){const o=kn(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=>ue(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?bs(l):l),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return ue(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||ie(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ie(this.sourceBuffer)||ie(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var ni;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(ni||(ni={}));class ry{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.abortAllController=new di,this.subscription=new ae,this.fetchManifest=Oe(this.abortAllController.signal,function(r){return Me(this,arguments,function*(){let a=r;this.requestQuic&&(a=ci(a));const n=yield yield M(Fi(a,{signal:this.abortAllController.signal}).catch(ki));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Oe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?ni.HEADER:ni.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,v;return Me(this,arguments,function*(){let g=r;const T=new Headers;if(n)switch(a){case ni.HEADER:{T.append("Range",`bytes=${n.from}-${n.to}`);break}case ni.PARAM:{const N=new URL(g,location.href);N.searchParams.append("bytes",`${n.from}-${n.to}`),g=N.toString();break}default:H(a)}this.requestQuic&&(g=ci(g));let A=this.abortAllController.signal,E;if(d){const N=new di;if(E=V(B(this.abortAllController.signal,"abort"),B(d,"abort")).subscribe(()=>{try{N.abort()}catch(Z){ki(Z)}}),this.abortAllController.signal.aborted||d.aborted)try{N.abort()}catch(Z){ki(Z)}A=N.signal}const m=me(),b=yield yield M(Fi(g,{priority:u,headers:T,signal:A}).catch(ki)),$=me();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-m),!b)return E==null||E.unsubscribe(),yield M(null);if(!b.ok||!b.body)return E==null||E.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));this.onHeadersReceived(b.headers);const R=parseInt((h=b.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!R){const N=yield yield M(b.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(N.byteLength,me()-$),o==null||o(new DataView(N),N.byteLength),E==null||E.unsubscribe(),yield M(N)}if(!o&&!l)return E==null||E.unsubscribe(),yield M(b.arrayBuffer());const[j,X]=b.body.tee(),F=j.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(X));let Y=0;const K=new ArrayBuffer(R),O=new Uint8Array(K),G=new DataView(K);let ne=!1;const U=N=>{E==null||E.unsubscribe(),ne=!0,ki(N)},I=Oe(A,function({done:N,value:Z}){return Me(this,arguments,function*(){if(Y===0&&this.lastRequestFirstBytes$.next(me()-m),A.aborted)return E==null||E.unsubscribe(),yield M(void 0);!N&&Z&&(O.set(Z,Y),Y+=Z.byteLength,o==null||o(G,Y),yield yield M(F==null?void 0:F.read().then(I,U)))})}.bind(this));return yield yield M(F==null?void 0:F.read().then(I,U)),E==null||E.unsubscribe(),yield M(ne?null:K)})}.bind(this)),this.fetchByteRangeRepresentation=Oe(this.abortAllController.signal,function(r,a,n){var o;return Me(this,arguments,function*(){if(r.type!==Ye.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(v,d))),l=Math.min(l,0);const g=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!g)return yield M(null);const T=new DataView(g,u-l,d-l+1);if(!a.validateData(T))throw new Error("Invalid media file");const A=a.parseInit(T),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(A);if(!E)throw new ReferenceError("No way to load representation index");let m;if(h)m=new DataView(g,E.from-l,E.to-E.from+1);else{const $=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!$)return yield M(null);m=new DataView($)}const b=a.parseSegments(m,A,E);return yield M({init:A,dataView:new DataView(g),segments:b})})}.bind(this)),this.fetchTemplateRepresentation=Oe(this.abortAllController.signal,function(r,a){return Me(this,arguments,function*(){if(r.type!==Ye.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Vu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ye.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Ye.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:H(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ki=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var ay=vt,ny=Vi,oy=Pe,dy=oy("match"),uy=function(s){var e;return ay(s)&&((e=s[dy])!==void 0?!!e:ny(s)=="RegExp")},ly=qi,cy=String,hy=function(s){if(ly(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return cy(s)},fy=mt,py=function(){var s=fy(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},vy=Fe,my=ot,gy=js,Sy=py,ed=RegExp.prototype,by=function(s){var e=s.flags;return e===void 0&&!("flags"in ed)&&!my(s,"flags")&&gy(ed,s)?vy(Sy,s):e},pn=ze,yy=Qs,Ty=Math.floor,Xr=pn("".charAt),Ey=pn("".replace),Zr=pn("".slice),$y=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ay=/\$([$&'`]|\d{1,2})/g,_y=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Ay;return r!==void 0&&(r=yy(r),u=$y),Ey(a,u,function(d,l){var c;switch(Xr(l,0)){case"$":return"$";case"&":return s;case"`":return Zr(e,0,t);case"'":return Zr(e,n);case"<":c=r[Zr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ty(h/10);return f===0?d:f<=o?i[f-1]===void 0?Xr(l,1):i[f-1]+Xr(l,1):d}c=i[h-1]}return c===void 0?"":c})},wy=Ze,ky=Fe,vn=ze,td=Va,Py=Ee,Ry=Hi,Dy=uy,ti=hy,Iy=Ws,Cy=by,xy=_y,Ly=Pe,Oy=Ly("replace"),My=TypeError,Xu=vn("".indexOf),By=vn("".replace),id=vn("".slice),Ny=Math.max,sd=function(s,e,t){return t>s.length?-1:e===""?t:Xu(s,e,t)};wy({target:"String",proto:!0},{replaceAll:function(e,t){var i=td(this),r,a,n,o,u,d,l,c,h,f=0,v=0,g="";if(!Ry(e)){if(r=Dy(e),r&&(a=ti(td(Cy(e))),!~Xu(a,"g")))throw My("`.replaceAll` does not allow non-global regexes");if(n=Iy(e,Oy),n)return ky(n,e,i,t);if(r)return By(ti(i),e,t)}for(o=ti(i),u=ti(e),d=Py(t),d||(t=ti(t)),l=u.length,c=Ny(1,l),f=sd(o,u,0);f!==-1;)h=d?ti(t(u,f,o)):xy(u,o,f,[],void 0,t),g+=id(o,v,f)+h,v=f+l,f=sd(o,u,f+c);return v<o.length&&(g+=id(o,v)),g}});var Fy=ln,Uy=Fy("String","replaceAll"),Vy=Uy,Hy=Vy,Gy=Hy,Yy=Gy,rd=Gs(Yy);const ad=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ea=(s,e)=>{let t=s;t=rd(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=rd(t,n,(o,u)=>ie(a)?o:ie(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jy=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,v,g,T,A,E,m,b,$,R,j,X,F,Y,K,O,G,ne,U,I,N,Z,pe,Se,Ce,et,Tt,ee;const Ue=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Ve=Ue.children[0],qt=Ve.getElementsByTagName("Period")[0],Ct=qt.children,zt=Ve.getAttribute("type")==="dynamic",Wt=Ve.getAttribute("availabilityStartTime"),Ji=Wt?new Date(Wt).getTime():void 0;let xt;const mn=Ve.getAttribute("mediaPresentationDuration"),gn=qt.getAttribute("duration"),ar=Ve.getElementsByTagName("vk:Attrs")[0],Sn=ar==null?void 0:ar.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(mn)xt=ad(mn);else if(gn){const We=ad(gn);k(We)&&(xt=We)}else Sn&&(xt=parseInt(Sn,10));let nl=0;const nr=(i=(t=Ve.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],ol=nr.includes(Fs.WEBM_AS_IN_FFMPEG)||nr.includes(Fs.WEBM_AS_IN_SPEC)?hi.WEBM:hi.MP4;for(const We of Ct){const Xi=We.getAttribute("mimeType"),dl=We.getAttribute("codecs"),bn=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:Xi==null?void 0:Xi.split("/")[0],ul=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],yn=We.querySelectorAll("Representation"),ll=We.querySelector("SegmentTemplate");if(bn===Ae.TEXT){for(const be of yn){const Et=be.getAttribute("id")||"",Zi=We.getAttribute("lang"),Qt=(d=(u=(o=be.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",or=new URL(Qt,e).toString(),dr=Et.includes("_auto");xe[Ae.TEXT].push({id:Et,lang:Zi,isAuto:dr,kind:Ae.TEXT,url:or})}continue}for(const be of yn){const Et=(l=be.getAttribute("mimeType"))!==null&&l!==void 0?l:Xi,Zi=(h=(c=be.getAttribute("codecs"))!==null&&c!==void 0?c:dl)!==null&&h!==void 0?h:"",Qt=(v=(f=be.getAttribute("contentType"))!==null&&f!==void 0?f:Et==null?void 0:Et.split("/")[0])!==null&&v!==void 0?v:bn,or=(T=(g=We.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&T!==void 0?T:[],dr=parseInt((A=be.getAttribute("width"))!==null&&A!==void 0?A:"",10),Tn=parseInt((E=be.getAttribute("height"))!==null&&E!==void 0?E:"",10),En=parseInt((m=be.getAttribute("bandwidth"))!==null&&m!==void 0?m:"",10)/1e3,$n=(b=be.getAttribute("frameRate"))!==null&&b!==void 0?b:"",cl=($=be.getAttribute("quality"))!==null&&$!==void 0?$:void 0,hl=$n?hn($n):void 0,fl=(R=be.getAttribute("id"))!==null&&R!==void 0?R:(nl++).toString(10),pl=Qt==="video"?`${Tn}p`:Qt==="audio"?`${En}Kbps`:Zi,vl=`${fl}@${pl}`,ml=(F=(X=(j=be.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||X===void 0?void 0:X.trim())!==null&&F!==void 0?F:"",An=new URL(ml,e).toString(),gl=[...nr,...ul,...or];let ur;const Sl=be.querySelector("SegmentBase"),Lt=(Y=be.querySelector("SegmentTemplate"))!==null&&Y!==void 0?Y:ll;if(Sl){const bi=(O=(K=be.querySelector("SegmentBase Initialization"))===null||K===void 0?void 0:K.getAttribute("range"))!==null&&O!==void 0?O:"",[yi,cr]=bi.split("-").map(Kt=>parseInt(Kt,10)),Ti={from:yi,to:cr},Ei=(G=be.querySelector("SegmentBase"))===null||G===void 0?void 0:G.getAttribute("indexRange"),[hr,es]=Ei?Ei.split("-").map(Kt=>parseInt(Kt,10)):[],$i=Ei?{from:hr,to:es}:void 0;ur={type:Ye.BYTE_RANGE,url:An,initRange:Ti,indexRange:$i}}else if(Lt){const bi={representationId:(ne=be.getAttribute("id"))!==null&&ne!==void 0?ne:void 0,bandwidth:(U=be.getAttribute("bandwidth"))!==null&&U!==void 0?U:void 0},yi=parseInt((I=Lt.getAttribute("timescale"))!==null&&I!==void 0?I:"",10),cr=(N=Lt.getAttribute("initialization"))!==null&&N!==void 0?N:"",Ti=Lt.getAttribute("media"),Ei=(pe=parseInt((Z=Lt.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&pe!==void 0?pe:1,hr=ea(cr,bi);if(!Ti)throw new ReferenceError("No media attribute in SegmentTemplate");const es=(Se=Lt.querySelectorAll("SegmentTimeline S"))!==null&&Se!==void 0?Se:[],$i=[];let Kt=0;if(es.length){let fr=Ei,lt=0;for(const Ai of es){const $t=parseInt((Ce=Ai.getAttribute("d"))!==null&&Ce!==void 0?Ce:"",10),Ot=parseInt((et=Ai.getAttribute("r"))!==null&&et!==void 0?et:"",10)||0,ts=parseInt((Tt=Ai.getAttribute("t"))!==null&&Tt!==void 0?Tt:"",10);lt=Number.isFinite(ts)?ts:lt;const pr=$t/yi*1e3,_n=lt/yi*1e3;for(let is=0;is<Ot+1;is++){const bl=ea(Ti,Object.assign(Object.assign({},bi),{segmentNumber:fr.toString(10),segmentTime:(lt+is*$t).toString(10)})),wn=(_n||0)+is*pr,yl=wn+pr;fr++,$i.push({time:{from:wn,to:yl},url:bl})}lt+=(Ot+1)*$t,Kt+=(Ot+1)*pr}}else if(k(xt)){const lt=parseInt((ee=Lt.getAttribute("duration"))!==null&&ee!==void 0?ee:"",10)/yi*1e3,Ai=Math.ceil(xt/lt);let $t=0;for(let Ot=1;Ot<Ai;Ot++){const ts=ea(Ti,Object.assign(Object.assign({},bi),{segmentNumber:Ot.toString(10),segmentTime:$t.toString(10)}));$i.push({time:{from:$t,to:$t+lt},url:ts}),$t+=lt}}ur={type:Ye.TEMPLATE,baseUrl:An,initUrl:hr,totalSegmentsDurationMs:Kt,segments:$i}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!Et)continue;const lr={video:Ae.VIDEO,audio:Ae.AUDIO,text:Ae.TEXT}[Qt];lr&&xe[lr].push({id:vl,kind:lr,segmentReference:ur,profiles:gl,duration:xt,bitrate:En,mime:Et,codecs:Zi,width:dr,height:Tn,fps:hl,quality:cl})}}return{dynamic:zt,liveAvailabilityStartTime:Ji,duration:xt,container:ol,representations:xe}},Na=1e3,nd=["timeupdate","progress","play","seeked","stalled","waiting"];var Ge;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ge||(Ge={}));let qy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ae,this.representationSubscription=new ae,this.state$=new ce(Ge.NONE),this.currentVideoRepresentation$=new S(void 0),this.currentVideoRepresentationInit$=new S(void 0),this.error$=new x,this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.isLive$=new S(!1),this.liveDuration$=new S(0),this.liveAvailabilityStartTime$=new S(void 0),this.bufferLength$=new S(0),this.liveLoadBufferLength$=new S(0),this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new di,this.initManifest=Oe(this.destroyController.signal,function(t,i,r){var a;return Me(this,arguments,function*(){this.element=t,this.manifestUrlString=Je(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ge.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Ge.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Oe(this.destroyController.signal,function(){var t;return Me(this,arguments,function*(){const i=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!i)return yield M(this.manifest);let r;try{r=jy(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Ae.TEXT)};return 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:li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Oe(this.destroyController.signal,function(t,i){return Me(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ge.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Zo(Ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(i)&&(this.audioBufferManager=new Zo(Ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Cs(Na).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Go(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=Je(this.manifestUrlString,d+1e3,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(V(...nd.map(o=>B(this.element,o))).pipe(Al(Na),w(o=>this.element?wt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(v=>{var g,T;return(T=(g=v.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&T!==void 0?T:0}))-h}this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(u=>ue(this,void 0,void 0,function*(){P(this.element);const d=this.element.playbackRate,l=Go(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),c=Jb*d,h=Zb*d,f=Xb*d;o=u>o?u:o;const v=l===0&&u<f,g=l!==0&&u<c+f&&u>=c,T=l!==0&&u<c;if(T||g){const A=o-(c+h),E=Math.trunc(l+A/d);let m;u?E>0?m=E:m=0:m=l,this.manifestUrlString=Je(this.manifestUrlString,m,Te.DASH_CMAF_OFFSET_P)}(v||T||g)&&(yield this.updateLive(),o=0)})))}const a=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(V(this.forceEnded$,Ne({allBuffersFull:a,someBufferEnded:n}).pipe(re(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(V(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield M(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),k(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&k(i)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Ge.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Cs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ry({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,i,r,a;return ue(this,void 0,void 0,function*(){P(this.element),this.manifestUrlString=Je(this.manifestUrlString,e,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){P(this.element),this.state$.setState(Ge.RUNNING),this.subscription.add(V(...nd.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ba(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ue(this,void 0,void 0,function*(){const i={[Ae.VIDEO]:this.videoBufferManager,[Ae.AUDIO]:this.audioBufferManager,[Ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Ba(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ge.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(),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}updateLive(){var e;return ue(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class zy{constructor(e,t){this.fov=e,this.orientation=t}}class Wy{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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Qy=`#define GLSLIFY 1
|
|
29
|
+
`}),U}return d==null||d.recordSwitch(G),G};var Ie=s=>new URL(s).hostname;const KS=300,Bs=(s,e=KS)=>new Hs(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Pl(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),k(u)&&k(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class ir{constructor(){this.onDroopedVideoFramesLimit$=new x,this.subscription=new ae,this.playing=!1,this.tracks=[],this.forceChecker$=new x,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&&!Oi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=i-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&&Ii(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,i)}}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(B(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Cs(this.droppedFramesChecker.checkTime).pipe(re(()=>this.playing),re(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(je(this.droppedFramesChecker.checkTime)),i=V(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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,i;const r=(i=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>ws(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||i===void 0?void 0:i[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}}const wi={};var Q;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const ye=(s,e)=>new Hs(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class qo{constructor(e){this.subscription=new ae,this.videoState=new ce(Q.DOWNLOADING_LIB),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.videoTracks$=new S([]),this.frameRatesByFrameHeight={},this.isLive$=new S(void 0),this.maxSeekBackTime$=new S(1/0),this.availableFrom$=new S(void 0),this.elementSize$=new S(void 0),this.liveOffset=new tr,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&t!==Q.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:H(t)}break}case p.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:H(t)}break}case p.PLAYING:{switch(t){case Q.PLAYING:break;case Q.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Q.READY:this.play();break;case Q.STOPPED:this.prepare();break;default:H(t)}break}case p.PAUSED:{switch(t){case Q.PLAYING:this.pause(),this.liveOffset.pause();break;case Q.PAUSED:break;case Q.READY:this.videoState.setState(Q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED);break;case Q.STOPPED:this.prepare();break;default:H(t)}break}default:H(i)}},this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:L.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);er(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(wi.MediaPlayer=r.MediaPlayer,wi.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){P(wi.MediaPlayer,"dashjs not loaded"),P(wi.Debug,"dashjs not loaded"),this.player=wi.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?hn(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&kS(this.player),AS(this.player),this.params.tuning.requestQuick&&wS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,b)=>this.subscription.add(m.subscribe(b,i));r(Bs(this.video),this.elementSize$),r(ye(this.player,"error").pipe(w(m=>{const b=typeof m.error=="object"?m.error.code:m.error,$=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${b}`,message:$}})),e.error$),r(ye(this.player,"playbackError").pipe(w(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=ye(this.player,"qualityChangeRendered").pipe(re(({mediaType:m})=>m==="video"),w(({newQuality:m})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m))===null||b===void 0?void 0:b.track}));a.pipe(re(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(re(({to:m})=>m===Q.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(Xe(t.videoTrack,()=>{var m,b;const $=this.player.getQualityFor("video");return(b=(m=this.videoTracks$.getValue().find(({bitrateInfo:R})=>R.qualityIndex===$))===null||m===void 0?void 0:m.track)===null||b===void 0?void 0:b.id},m=>{var b;if(ie(m))return;const $=(b=this.videoTracks$.getValue().find(({track:R})=>R.id===m))===null||b===void 0?void 0:b.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a.pipe(w(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Xe(t.autoVideoTrackSwitching,()=>{var m,b,$;return($=(b=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||$===void 0?void 0:$.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(ye(this.player,"bufferStateChanged").pipe(re(({mediaType:m})=>m==="video"),w(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(ye(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:b}})=>{var $,R;const j=this.player.getDashMetrics(),X=j.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),F=($=j.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&$!==void 0?$:Mi.HTTP1,Y=(R={1:!0,0:!1}[X])!==null&&R!==void 0?R:void 0;this.params.output.httpConnectionType$.next(F),this.params.output.httpConnectionReused$.next(Y),e.hostname$.next(Ie(b))}),r(ye(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:b,availableFrom:$}}})=>{this.isLive$.next(b),this.availableFrom$.next($.getTime()),b||e.duration$.next(m);const R=[],j=this.player.getQualityFor("video");let X;for(const F of this.player.getBitrateInfoListFor("video")){const Y=F.qualityIndex.toString(10),K=Vt(F),O=F.bitrate/1e3,G={width:F.width,height:F.height},ne=this.frameRatesByFrameHeight[F.height];if(K){const U={id:Y,quality:K,bitrate:O,size:G,fps:ne};R.push({track:U,bitrateInfo:F}),F.qualityIndex===j&&(X=U)}}this.videoTracks$.next(R),e.availableVideoTracks$.next(R.map(({track:F})=>F)),X&&e.currentVideoTrack$.next(X),this.videoState.setState(Q.STREAM_INITIALIZED),this.videoState.startTransitionTo(Q.READY)}),r(ye(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const b=m.requestEndDate.getTime()-m.firstByteDate.getTime(),$=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,b)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=gi(this.videoTracks$.getValue().map(({track:j})=>j),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const R=this.videoTracks$.getValue().find(({track:j})=>j===b);R!=null&&R.bitrateInfo&&this.player.setQualityFor("video",R==null?void 0:R.bitrateInfo.qualityIndex,!1)}),r(Ne({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(re(k))}).pipe(re(({isLive:m})=>m),w(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=ye(this.player,"playbackTimeUpdated").pipe(w(({time:m})=>m!=null?m:0));r(Ne({availableFrom:this.availableFrom$.pipe(re(k)),currentTime:n}),({availableFrom:m,currentTime:b})=>this.params.output.liveTime$.next(m+b*1e3)),r(n.pipe(re(()=>this.isLive$.getValue()===!1)),e.position$),r(ye(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(ye(this.player,"playbackEnded"),e.endedEvent$),r(ye(this.player,"playbackProgress").pipe(w(()=>Fu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(ye(this.player,"playbackPlaying"),()=>{this.videoState.setState(Q.PLAYING),D(t.playbackState,p.PLAYING)}),r(ye(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Q.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(ye(this.player,"playbackPaused"),()=>{this.videoState.setState(Q.PAUSED),D(t.playbackState,p.PAUSED)}),r(ye(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===Q.READY&&this.videoState.setState(Q.READY)}),r(this.isLive$,e.isLive$),r(Bs(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=_S(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(ye(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ne({isLive:this.isLive$,isShort:e.duration$.pipe(w(m=>m<60))}),({isLive:m,isShort:b})=>{const $=!m&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(re(m=>m>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(ye(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(ye(this.player,"playbackPlaying").pipe(ge(),ui(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(ye(this.player,"manifestLoaded"),m=>{var b,$,R,j,X,F,Y;if(!(($=(b=m.data)===null||b===void 0?void 0:b.Period)===null||$===void 0)&&$.AdaptationSet){const K=[];for(const O of(j=(R=m.data)===null||R===void 0?void 0:R.Period)===null||j===void 0?void 0:j.AdaptationSet)if(O.contentType==="text"){const G=(X=O.Representation)===null||X===void 0?void 0:X.id,ne=new URL((F=O.Representation)===null||F===void 0?void 0:F.BaseURL,(Y=m.data)===null||Y===void 0?void 0:Y.baseUri).toString(),U="internal",I=O.lang;K.push({id:G,url:ne,type:U,language:I})}t.internalTextTracks.startTransitionTo(K)}}),this.subscription.add(jt(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:g,inFullscreen$:T,pause$:A,playing$:E}=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:E,pause$:A,tracks$:this.videoTracks$.pipe(w(m=>m.map(({track:b})=>b)))}),this.subscription.add(gt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Dt(this.video,t.playbackRate,v,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(T.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Q.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Q.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=Je(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Te.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Q.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}bt(this.video),this.params.output.element$.next(void 0)}}var Qi=s=>{switch(s){case"mobile":return He.Q_144P;case"lowest":return He.Q_240P;case"low":return He.Q_360P;case"sd":case"medium":return He.Q_480P;case"hd":case"high":return He.Q_720P;case"fullhd":case"full":return He.Q_1080P;case"quadhd":case"quad":return He.Q_1440P;case"ultrahd":case"ultra":return He.Q_2160P}};const zo=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var It=s=>ue(void 0,void 0,void 0,function*(){const e=s.muted;try{yield s.play()}catch(t){if(!zo(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{yield s.play()}catch(i){return zo(i)&&(s.muted=!1,console.warn(i)),!1}}return!0});function ke(){return me()}function Uu(s){return ke()-s}function Wo(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function JS(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ds(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,g=2e3,T=()=>{if(u)return;P(l);const O=Uu(l);let G;if(O<g){G=g-O,setTimeout(T,G);return}g*=2,g>v&&(g=v),n&&n.abort(),n=new r,R()};const A=O=>(a=O,K),E=O=>(c=O,K),m=()=>(f="json",K),b=()=>{if(!u){if(--d>=0){T(),i&&i();return}u=!0,c&&c(),t&&t()}},$=O=>(h=O,K),R=()=>{l=ke(),n=new r,n.open("get",s);let O=0,G,ne=0;const U=()=>(P(l),Math.max(l,Math.max(G||0,ne||0)));if(a&&n.addEventListener("progress",I=>{const N=ke();a.updateChunk&&I.loaded>O&&(a.updateChunk(U(),I.loaded-O),O=I.loaded,G=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>b())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const N=n.response.byteLength-O;N&&a.updateChunk&&a.updateChunk(U(),N)}c&&c(),n&&e(n.response)}else b()}),n.addEventListener("error",()=>{b()}),h){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ne=ke(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),K},K={withBitrateReporting:A,withParallel:$,withJSONResponse:m,withRetryCount:O=>(d=O,K),withRetryInterval:(O,G)=>(k(O)&&(g=O),k(G)&&(v=G),K),withTimeout:O=>(o=O,K),withFinally:E,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return K}const XS=100,ZS=2e3,eb=500;let tb=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,i){return{start:e,end:t,bytes:i}}_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-eb;if(t-e>ZS){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=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;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>XS&&(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 ib{constructor(e,t,i,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=i,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 i=ke(),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=ke()-i,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=Ds(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=ke()}_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=ke();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(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=i,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 gs=1e4,Ss=3,sb=300,rb=2e3,ab=6e4,nb=10,ob=1,db=500;class ub{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 tb(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 i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,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):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}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:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{JS(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 ib(Ss,gs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const b=a&&(!l||l===this.rep);return b||t("Not running!"),b},h=(b,$,R)=>{u&&u.abort(),u=Ds(this.urlResolver.resolve(b,!1),$,R,()=>this._retryCallback()).withTimeout(gs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ss).withFinally(()=>{u=null}).send()},f=(b,$,R)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),$,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=b=>{const $=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${$}=>${b}`),i.playbackRate=b)},g=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const R=ke()-1e4;let j=0;for(let F=0;F<this.bufferStates.length;F++){const Y=this.bufferStates[F];b=Math.min(b,Y.buf),Y.ts<R&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${b} drop=${j} jitter=${this.sourceJitter}`);let X=b-ob;this.sourceJitter>=0?X-=this.sourceJitter/2:this.sourceJitter-=1,X>3?v(1.15):X>1?v(1.1):X>.3?v(1.05):v(1)}},A=b=>{let $;const R=()=>$&&$.start?$.start.length:0,j=I=>$.start[I]/1e3,X=I=>$.dur[I]/1e3,F=I=>$.fragIndex+I,Y=(I,N)=>({chunkIdx:F(I),startTS:j(I),dur:X(I),discontinuity:N}),K=()=>{let I=0;if($&&$.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=N;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let Se=$.dur.length-1;for(;Se>=0&&(pe-=$.dur[Se],!(pe<=0));--Se);I=Math.min(Se,$.dur.length-1-Z),I=Math.max(I,0)}return Y(I,!0)},O=I=>{const N=R();if(!(N<=0)){if(k(I)){for(let Z=0;Z<N;Z++)if(j(Z)>I)return Y(Z)}return K()}},G=I=>{const N=R(),Z=I?I.chunkIdx+1:0,pe=Z-$.fragIndex;if(!(N<=0)){if(!I||pe<0||pe-N>nb)return t(`Resync: offset=${pe} bChunks=${N} chunk=`+JSON.stringify(I)),K();if(!(pe>=N))return Y(Z-$.fragIndex,!1)}},ne=(I,N,Z)=>{d&&d.abort(),d=Ds(this.urlResolver.resolve(I,!0,this.lowLatency),N,Z,()=>this._retryCallback()).withTimeout(gs).withRetryCount(Ss).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,N)=>{ne(b,Z=>{if(!c())return;$=Z;const pe=!!$.lowLatency;pe!==this.lowLatency&&g(pe);let Se=0;for(let Ce=0;Ce<$.dur.length;++Ce)Se+=$.dur[Ce];Se>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,I(O(N))},()=>this._handleNetworkError())},nextChunk:G}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:b=>{const{videoElement:$,logger:R}=this.params;let j=A(e.jidxUrl),X,F,Y,K,O=0,G,ne,U;const I=()=>{G&&(clearTimeout(G),G=void 0);const ee=Math.max(db,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Re=O+ee,Ue=ke(),xe=Math.min(1e4,Re-Ue);O=Ue;const Ve=()=>{d||c()&&j.seek(()=>{c()&&(O=ke(),N(),I())})};xe>0?G=window.setTimeout(()=>{this.paused?I():Ve()},xe):Ve()},N=()=>{let ee;for(;ee=j.nextChunk(K);)K=ee,et(ee);const Re=j.nextChunk(Y);if(Re){if(Y&&Re.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?I():(E(),this._initPlayerWith(e));return}Ce(Re)}else I()},Z=(ee,Re)=>{if(!c()||!this.sourceBuffer)return;let Ue,xe,Ve;const qt=Ct=>{window.setTimeout(()=>{c()&&Z(ee,Re)},Ct)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),qt(100);else{const Ct=ke(),zt=$.currentTime;!this.paused&&$.buffered.length>1&&ne===zt&&Ct-U>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ne!==zt&&(ne=zt,U=Ct);const Wt=this._getBufferSizeSec();if(Wt>30)R(`Buffered ${Wt} seconds; delaying appendBuffer`),qt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Ct,buf:Wt}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Re&&Re()}catch(Ji){if(Ji.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Ue=this.sourceBuffer.buffered.start(0),xe=zt,xe-Ue>4&&this.sourceBuffer.remove(Ue,xe-3)),qt(1e3);else throw Ji}}},pe=()=>{F&&X&&(R([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Y)]),Z(F,function(){F=null,N()}))},Se=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ce=ee=>{c()&&f(Se(ee),(Re,Ue)=>{if(c()){if(Ue/=1e3,F=Re,Y=ee,n=ee.startTS,Ue){const xe=Math.min(10,ee.dur/Ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}pe()}},()=>this._handleNetworkError())},et=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(ee),!1)))},Tt=ee=>{c()&&(e.cachedHeader=ee,Z(ee,()=>{X=!0,pe()}))};a=!0,j.seek(ee=>{if(c()){if(O=ke(),!ee){I();return}K=ee,!ie(b)||ee.startTS>b?Ce(ee):(Y=ee,N())}},b),e.cachedHeader?Tt(e.cachedHeader):h(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=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,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=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=ke();if(this.chunkRateEstimator.addInterval(h,v,f)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:T}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Uu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=ke();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ds(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(gs).withRetryCount(Ss).withRetryInterval(sb,rb).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;It(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},ab))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const lb=[z.PAUSED,z.PLAYING,z.READY],cb=[z.PAUSED,z.PLAYING,z.READY];class hb{constructor(e){this.subscription=new ae,this.videoState=new ce(z.STOPPED),this.representations$=new S([]),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.maxSeekBackTime$=new S(1/0),this.zeroTime$=new S(void 0),this.liveOffset=new tr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Qi(c.name))!==null&&n!==void 0?n:Vt(c.video),v=c.bitrate/1e3,g=Object.assign({},c.video);if(!f)continue;const T={id:h,quality:f,bitrate:v,size:g};l.push({track:T,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.MANIFEST_READY&&this.videoState.setState(z.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),k(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||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!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(cb.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===W.Requested&&lb.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(Je(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(n===p.PAUSED)this.videoState.setState(z.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(z.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(z.PAUSED)})}return;case z.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(z.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(z.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(Je(this.params.source.url,c))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(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=St(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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===W.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ne({zeroTime:this.zeroTime$.pipe(re(k)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(jt(this.video,this.params.desiredState.isLooped,t)).add(gt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Dt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&$l(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case z.MANIFEST_READY:case z.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 z.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case z.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,De(["init"])).pipe(je(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),bt(this.video)}createLiveDashPlayer(){const e=new ub({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&k(u)?u:(a=gi(o.map(({track:v})=>v),{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}))===null||a===void 0?void 0:a.id,c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((c&&l||l!==h)&&this.setVideoTrack(l),f&&this.setAutoQuality(d),c||f||l!==h){const v=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(v,"Representations missing"),this.dash.startPlay(v,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===z.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Je(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Vu=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?Mi.HTTP1:(e=i)!==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}},wt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const fb=s=>{const e=document.createElement("a");return e.href=s,e.origin},pb=s=>{const e=document.createElement("a");return e.href=s,e.host};class Hu{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=li(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(pb(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ns{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=g=>{r(Ns._str2ua(g.substr(u))),u=g.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=ci(v)),this._lastXhr=new Hu(v,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const T=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:T,speed:8*g.length/(T/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-u>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const T=Date.now()-c;h>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:h,duration:T,speed:8*h/(T/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,T,A)=>this._params.onError(g,T,A))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ns._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class vb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ci(i)),new Hu(i,t,r=>{this.attachManifest(r,t,fb(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,v,g,T,A,E,m,b,$,R,j,X,F,Y,K,O;const G=d.getElementsByTagName("SegmentBase")[0],ne=G&&n(G,"indexRange").split("-"),U=G&&G.getElementsByTagName("Initialization")[0],I=U&&n(U,"range").split("-");if(!I||!ne){const et=d.parentElement;if((et==null?void 0:et.getAttribute("contentType"))==="text"){const Tt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),Re=(g=et.getAttribute("lang"))!==null&&g!==void 0?g:void 0;ee&&u.push({id:Tt,url:ee,language:Re})}return}const N=.1,Z=Number((T=d.attributes.getNamedItem("bandwidth"))===null||T===void 0?void 0:T.value),pe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Se;const Ce=(E=(A=d.attributes.getNamedItem("frameRate"))===null||A===void 0?void 0:A.value)!==null&&E!==void 0?E:void 0;Se=Ce?hn(Ce):void 0,o.push({width:Number((m=d.attributes.getNamedItem("width"))===null||m===void 0?void 0:m.value),height:Number((b=d.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:Z,baseURL:pe,failoverHosts:t,indexFrom:Number(ne[0]),indexTo:Number(ne[1]),initFrom:Number(I[0]),initTo:Number(I[1]),codecs:(R=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&R!==void 0?R:void 0,mimeType:(X=(j=d.attributes.getNamedItem("mimeType"))===null||j===void 0?void 0:j.value)!==null&&X!==void 0?X:void 0,fps:Se,bufferSize:N*Z/8,bufferLength:N,name:(Y=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Y!==void 0?Y:void 0,id:(O=(K=d.attributes.getNamedItem("id"))===null||K===void 0?void 0:K.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,u=v}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ns({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||ie(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var J;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const mb=[J.PAUSED,J.PLAYING];class gb{constructor(e){this.videoState=new ce(J.STOPPED),this.subscription=new ae,this.representations$=new S([]),this.currentRepresentation$=new S(void 0),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.elementSize$=new S(void 0),this.dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&Qi(u.name))!==null&&n!==void 0?n:Vt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const v={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:v,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(J.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===W.Requested&&mb.includes(t)&&this.seek(n.position,n.forcePrecise),t){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_LOADED),this.prepare();return;case J.MANIFEST_LOADED:this.videoState.startTransitionTo(J.INITIAL_REPRESENTATION_SELECTED);return;case J.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(J.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case J.METADATA_LOADED:this.videoState.startTransitionTo(J.READY),this.dash.updateRefsForCurrentTime();return;case J.READY:r===p.READY?D(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case J.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new xS(this.video),this.dash=new vb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:L.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=yt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{ie(this.params.desiredState.seekState.getState().state!==W.Applying)&&(this.videoState.getState()===J.PLAYING||this.videoState.getState()===J.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(w(o=>o.map(({track:u})=>u)))}),n(Bs(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===J.READY&&this.videoState.setState(J.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(J.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(V(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).pipe(w(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),T=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let A;if(!T&&k(f))A=f;else{const E=wt(this.video.buffered,this.video.currentTime*1e3),m=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(E/m,1);A=(u=gi(c.map(({track:R})=>R),{container:g,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:R})=>R===l))===null||o===void 0?void 0:o.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const $=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to)}return k(A)?(d=c.find(({track:E})=>E.id===A))===null||d===void 0?void 0:d.representation:void 0}),ve()).subscribe(this.currentRepresentation$,i)).add(Ne({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(re(o=>o.to===J.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(re(k))}).pipe(ge()).subscribe(()=>this.videoState.setState(J.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(re(k),ve((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=wt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ie(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=Vu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),ui(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(re(k)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return H(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}}var Ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ae||(Ae={}));var Fs;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Fs||(Fs={}));var Ye;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Ye||(Ye={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var hi;(function(s){s.MP4="mp4",s.WEBM="webm"})(hi||(hi={}));var Us;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Us||(Us={}));var he;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(he||(he={}));class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[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 Gu 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 Yu=class{constructor(){Object.defineProperty(this,"signal",{value:new Gu,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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Yu.prototype[Symbol.toStringTag]="AbortController",Gu.prototype[Symbol.toStringTag]="AbortSignal");function ju(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Sb(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!ju({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const sr=ju({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qu=sr?Sb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Fi=sr?qu.fetch:window.fetch;sr?qu.Request:window.Request;const di=sr?Yu:window.AbortController;var Ba=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const bb=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},yb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=yb?bb:window.requestIdleCallback;var Kr,Jr;let zu=!1;try{zu=Ua().browser===yd.Safari&&parseInt((Jr=(Kr=navigator.userAgent.match(/Version\/(\d+)/))===null||Kr===void 0?void 0:Kr[1])!==null&&Jr!==void 0?Jr:"",10)<16}catch(s){console.error(s)}class Tb{constructor(e){this.bufferFull$=new x,this.error$=new x,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return ue(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ue(this,void 0,void 0,function*(){return new Promise(t=>{let i;zu&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:L.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:H(t)}}}var Jo=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class ut{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 Wu extends ut{}class Eb extends ut{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class $b extends ut{parseChildrenBoxes(){return Si(this.content)}}class Ab extends ut{constructor(e){super(e),this.data=this.content}}class Ki extends ut{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _b extends Ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class wb extends ut{parseChildrenBoxes(){return Si(this.content)}}class kb extends ut{parseChildrenBoxes(){return Si(this.content)}}var Ft;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ft||(Ft={}));class Pb extends Ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ft.MONOSCOPIC;break;case 1:this.stereoMode=Ft.TOP_BOTTOM;break;case 2:this.stereoMode=Ft.LEFT_RIGHT;break;case 3:this.stereoMode=Ft.STEREO_CUSTOM;break;case 4:this.stereoMode=Ft.RIGHT_LEFT;break}this.cursor+=1}}class Rb extends Ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Db extends Ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ib extends ut{parseChildrenBoxes(){return Si(this.content)}}class Cb extends Ki{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 xb extends ut{parseChildrenBoxes(){return Si(this.content)}}class Lb extends ut{parseChildrenBoxes(){return Si(this.content)}}const Ob={ftyp:Eb,moov:$b,mdat:Ab,sidx:_b,trak:wb,mdia:Ib,tkhd:Cb,minf:xb,sv3d:kb,st3d:Pb,prhd:Rb,proj:Lb,equi:Db,unknown:Wu};class Mb{createBox(e,t){const i=Ob[e];return i?new i(t):new Wu(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return rr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const rr=new Mb;function Di(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const a=t.decode(new DataView(s.buffer,i,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+o>s.byteLength?null:rr.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Bb(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Di(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function Si(s){const e=[];let t=0;for(;t<s.byteLength;){const i=rr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Nb=new TextDecoder("ascii"),Fb=s=>Nb.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Ub=s=>{const e=rr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Vb=s=>{const e=Bb(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},Hb=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Di(s,"sv3d")){e.is3dVideo=!0;const i=Di(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Di(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Di(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Gb={validateData:Fb,parseInit:Hb,getIndexRange:()=>{},parseSegments:Ub,parseFeedableSegmentChunk:Vb};var _;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(_||(_={}));var C;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(C||(C={}));const Xo={[_.EBML]:{type:C.Master},[_.EBMLVersion]:{type:C.UnsignedInteger},[_.EBMLReadVersion]:{type:C.UnsignedInteger},[_.EBMLMaxIDLength]:{type:C.UnsignedInteger},[_.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[_.DocType]:{type:C.String},[_.DocTypeVersion]:{type:C.UnsignedInteger},[_.DocTypeReadVersion]:{type:C.UnsignedInteger},[_.Void]:{type:C.Binary},[_.Segment]:{type:C.Master},[_.SeekHead]:{type:C.Master},[_.Seek]:{type:C.Master},[_.SeekID]:{type:C.Binary},[_.SeekPosition]:{type:C.UnsignedInteger},[_.Info]:{type:C.Master},[_.TimestampScale]:{type:C.UnsignedInteger},[_.Duration]:{type:C.Float},[_.Tracks]:{type:C.Master},[_.TrackEntry]:{type:C.Master},[_.Video]:{type:C.Master},[_.Projection]:{type:C.Master},[_.ProjectionType]:{type:C.UnsignedInteger},[_.ProjectionPrivate]:{type:C.Master},[_.Chapters]:{type:C.Master},[_.Cluster]:{type:C.Master},[_.Timestamp]:{type:C.UnsignedInteger},[_.SilentTracks]:{type:C.Master},[_.SilentTrackNumber]:{type:C.UnsignedInteger},[_.Position]:{type:C.UnsignedInteger},[_.PrevSize]:{type:C.UnsignedInteger},[_.SimpleBlock]:{type:C.Binary},[_.BlockGroup]:{type:C.Master},[_.EncryptedBlock]:{type:C.Binary},[_.Attachments]:{type:C.Master},[_.Tags]:{type:C.Master},[_.Cues]:{type:C.Master},[_.CuePoint]:{type:C.Master},[_.CueTime]:{type:C.UnsignedInteger},[_.CueTrackPositions]:{type:C.Master},[_.CueTrack]:{type:C.UnsignedInteger},[_.CueClusterPosition]:{type:C.UnsignedInteger},[_.CueRelativePosition]:{type:C.UnsignedInteger},[_.CueDuration]:{type:C.UnsignedInteger},[_.CueBlockNumber]:{type:C.UnsignedInteger},[_.CueCodecState]:{type:C.UnsignedInteger},[_.CueReference]:{type:C.Master},[_.CueRefTime]:{type:C.UnsignedInteger}},Qu=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Vs(s,t),r=i in Xo,a=r?Xo[i].type:C.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=Vs(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Vs=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},at=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return Vs(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:H(e)}},fi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Qu(i);if(!e(r))return;r.type===C.Master&&fi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Yb=s=>{if(s.getUint32(0)!==_.EBML)return!1;let e,t,i;const r=Qu(s);return fi(r.value,({tag:a,type:n,value:o})=>(a===_.EBMLReadVersion?e=at(o,n):a===_.DocType?t=at(o,n):a===_.DocTypeReadVersion&&(i=at(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ku=[_.Info,_.SeekHead,_.Tracks,_.TrackEntry,_.Video,_.Projection,_.ProjectionType,_.ProjectionPrivate,_.Chapters,_.Cluster,_.Cues,_.Attachments,_.Tags],jb=[_.Timestamp,_.SilentTracks,_.SilentTrackNumber,_.Position,_.PrevSize,_.SimpleBlock,_.BlockGroup,_.EncryptedBlock],qb=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return fi(s,({tag:h,type:f,value:v,valueSize:g})=>{if(h===_.SeekID){const T=at(v,f);d=Vs(T)}else h!==_.SeekPosition&&(d=void 0);return h===_.Segment?(e=v.byteOffset,t=v.byteOffset+g):h===_.Info?a=!0:h===_.SeekHead?n=!0:h===_.TimestampScale?i=at(v,f):h===_.Duration?r=at(v,f):h===_.SeekPosition&&d===_.Cues?u=at(v,f):h===_.Tracks?fi(v,({tag:T,type:A,value:E})=>T===_.ProjectionType?(l=at(E,A)===1,!1):!0):a&&n&&Ku.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zb=s=>{if(ie(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wb=(s,e)=>{let t=!1,i=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return fi(s,({tag:o,type:u,value:d})=>{switch(o){case _.Cues:t=!0;break;case _.CuePoint:n&&r(n)&&a.push(n),n={};break;case _.CueTime:n&&(n.time=at(d,u));break;case _.CueTrackPositions:break;case _.CueClusterPosition:n&&(n.position=at(d,u));break;default:t&&Ku.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Qb=s=>{let e=0,t=!1;try{fi(s,i=>i.tag===_.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):jb.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[_.SimpleBlock,_.BlockGroup,_.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Kb={validateData:Yb,parseInit:qb,getIndexRange:zb,parseSegments:Wb,parseFeedableSegmentChunk:Qb},Ju=1e4,Jb=3e4,Xb=5e3,Zb=Ju,ey=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Qi(a):void 0)!==null&&n!==void 0?n:Vt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},ty=({id:s,bitrate:e})=>({id:s,bitrate:e}),iy=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=st(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:st(s,-1)},sy=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),bs=s=>{const e=[];let t=0,i=s.length-1;for(;t<Ju&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Zo{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new S(!1),this.fullyBuffered$=new S(!1),this.playingRepresentation$=new S(void 0),this.playingRepresentationInit$=new S(void 0),this.error$=new x,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ae,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new di,this.destroyAbortController=new di,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){const c=this.representations.get(l);P(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Tb(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const T=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=T,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id),v=this.parsedInitData.get(c.id);if(P(h,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield M(void 0);this.searchGaps(f,c),yield yield M(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v)})}.bind(this)),this.switchTo=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=l;const c=this.representations.get(l);P(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(ie(f)||ie(h)?yield yield M(this.loadInit(c,"high",!1)):f instanceof Promise&&(yield yield M(f)),h=this.segments.get(l),P(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal));const v=this.getCurrentPosition();k(v)&&(this.searchGaps(h,c),this.maintain(v))})}.bind(this)),this.seekLive=Oe(this.destroyAbortController.signal,function(l){return Me(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield M(void 0);for(const T of this.representations.keys()){const A=l.find(b=>b.id===T);A&&this.representations.set(T,A);const E=this.representations.get(T);if(!E)return yield M(void 0);const m=bs(E.segmentReference.segments);this.segments.set(E.id,m)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=bs(h.segmentReference.segments),v=this.initData.get(h.id);if(P(v,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(v instanceof ArrayBuffer))return yield M(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield M(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(f,h),yield yield M(this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!(d!=null&&d.dynamic),this.container=i,i){case hi.MP4:this.containerParser=Gb;break;case hi.WEBM:this.containerParser=Kb;break;default:H(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),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 di,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=wt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=wt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=st(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&wt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=st(i,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;k(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n)return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=st(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=bs(o);this.segments.set(n.id,[...c])}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const g=h<=i&&f>=i,T=h>i||g||v===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=i+A||f<=i+A;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&T&&E&&this.sourceBuffer&&!Ba(this.sourceBuffer.buffered,i))&&T&&E});if(r===-1)return[];if(t!==Ye.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ye.BYTE_RANGE:{r=t.segmentReference.url,a={from:st(e,0).byte.from,to:st(e,-1).byte.to};break}case Ye.TEMPLATE:{const d=st(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:H(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield Oe(u,function(){return Me(this,arguments,function*(){const d=kn(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)}})})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(i=wt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===te.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=te.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Ye.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const T=f?h.byte.from-i:0,A=f?h.byte.to-i:e.byteLength,E=T<r,m=A<=r;if(h.status===te.DOWNLOADING&&E&&m){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const b=new DataView(e.buffer,e.byteOffset+T,v);this.sourceBufferTaskQueue.append(b,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(v,r-T),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+T+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===v?b:this.containerParser.parseFeedableSegmentChunk(b);$!=null&&$.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(R=>{if(a.aborted)n();else if(R)c.fedBytes+=$.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ko(()=>er(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Oe(this.destroyAbortController.signal,function(){return Me(this,arguments,function*(){const o=kn(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=>ue(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?bs(l):l),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return ue(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||ie(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ie(this.sourceBuffer)||ie(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var ni;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(ni||(ni={}));class ry{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.abortAllController=new di,this.subscription=new ae,this.fetchManifest=Oe(this.abortAllController.signal,function(r){return Me(this,arguments,function*(){let a=r;this.requestQuic&&(a=ci(a));const n=yield yield M(Fi(a,{signal:this.abortAllController.signal}).catch(ki));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Oe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?ni.HEADER:ni.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,v;return Me(this,arguments,function*(){let g=r;const T=new Headers;if(n)switch(a){case ni.HEADER:{T.append("Range",`bytes=${n.from}-${n.to}`);break}case ni.PARAM:{const N=new URL(g,location.href);N.searchParams.append("bytes",`${n.from}-${n.to}`),g=N.toString();break}default:H(a)}this.requestQuic&&(g=ci(g));let A=this.abortAllController.signal,E;if(d){const N=new di;if(E=V(B(this.abortAllController.signal,"abort"),B(d,"abort")).subscribe(()=>{try{N.abort()}catch(Z){ki(Z)}}),this.abortAllController.signal.aborted||d.aborted)try{N.abort()}catch(Z){ki(Z)}A=N.signal}const m=me(),b=yield yield M(Fi(g,{priority:u,headers:T,signal:A}).catch(ki)),$=me();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-m),!b)return E==null||E.unsubscribe(),yield M(null);if(!b.ok||!b.body)return E==null||E.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));this.onHeadersReceived(b.headers);const R=parseInt((h=b.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!R){const N=yield yield M(b.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(N.byteLength,me()-$),o==null||o(new DataView(N),N.byteLength),E==null||E.unsubscribe(),yield M(N)}if(!o&&!l)return E==null||E.unsubscribe(),yield M(b.arrayBuffer());const[j,X]=b.body.tee(),F=j.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(X));let Y=0;const K=new ArrayBuffer(R),O=new Uint8Array(K),G=new DataView(K);let ne=!1;const U=N=>{E==null||E.unsubscribe(),ne=!0,ki(N)},I=Oe(A,function({done:N,value:Z}){return Me(this,arguments,function*(){if(Y===0&&this.lastRequestFirstBytes$.next(me()-m),A.aborted)return E==null||E.unsubscribe(),yield M(void 0);!N&&Z&&(O.set(Z,Y),Y+=Z.byteLength,o==null||o(G,Y),yield yield M(F==null?void 0:F.read().then(I,U)))})}.bind(this));return yield yield M(F==null?void 0:F.read().then(I,U)),E==null||E.unsubscribe(),yield M(ne?null:K)})}.bind(this)),this.fetchByteRangeRepresentation=Oe(this.abortAllController.signal,function(r,a,n){var o;return Me(this,arguments,function*(){if(r.type!==Ye.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(v,d))),l=Math.min(l,0);const g=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!g)return yield M(null);const T=new DataView(g,u-l,d-l+1);if(!a.validateData(T))throw new Error("Invalid media file");const A=a.parseInit(T),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(A);if(!E)throw new ReferenceError("No way to load representation index");let m;if(h)m=new DataView(g,E.from-l,E.to-E.from+1);else{const $=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!$)return yield M(null);m=new DataView($)}const b=a.parseSegments(m,A,E);return yield M({init:A,dataView:new DataView(g),segments:b})})}.bind(this)),this.fetchTemplateRepresentation=Oe(this.abortAllController.signal,function(r,a){return Me(this,arguments,function*(){if(r.type!==Ye.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Vu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ye.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Ye.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:H(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ki=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var ay=vt,ny=Vi,oy=Pe,dy=oy("match"),uy=function(s){var e;return ay(s)&&((e=s[dy])!==void 0?!!e:ny(s)=="RegExp")},ly=qi,cy=String,hy=function(s){if(ly(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return cy(s)},fy=mt,py=function(){var s=fy(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},vy=Fe,my=ot,gy=js,Sy=py,ed=RegExp.prototype,by=function(s){var e=s.flags;return e===void 0&&!("flags"in ed)&&!my(s,"flags")&&gy(ed,s)?vy(Sy,s):e},pn=ze,yy=Qs,Ty=Math.floor,Xr=pn("".charAt),Ey=pn("".replace),Zr=pn("".slice),$y=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ay=/\$([$&'`]|\d{1,2})/g,_y=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Ay;return r!==void 0&&(r=yy(r),u=$y),Ey(a,u,function(d,l){var c;switch(Xr(l,0)){case"$":return"$";case"&":return s;case"`":return Zr(e,0,t);case"'":return Zr(e,n);case"<":c=r[Zr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ty(h/10);return f===0?d:f<=o?i[f-1]===void 0?Xr(l,1):i[f-1]+Xr(l,1):d}c=i[h-1]}return c===void 0?"":c})},wy=Ze,ky=Fe,vn=ze,td=Va,Py=Ee,Ry=Hi,Dy=uy,ti=hy,Iy=Ws,Cy=by,xy=_y,Ly=Pe,Oy=Ly("replace"),My=TypeError,Xu=vn("".indexOf),By=vn("".replace),id=vn("".slice),Ny=Math.max,sd=function(s,e,t){return t>s.length?-1:e===""?t:Xu(s,e,t)};wy({target:"String",proto:!0},{replaceAll:function(e,t){var i=td(this),r,a,n,o,u,d,l,c,h,f=0,v=0,g="";if(!Ry(e)){if(r=Dy(e),r&&(a=ti(td(Cy(e))),!~Xu(a,"g")))throw My("`.replaceAll` does not allow non-global regexes");if(n=Iy(e,Oy),n)return ky(n,e,i,t);if(r)return By(ti(i),e,t)}for(o=ti(i),u=ti(e),d=Py(t),d||(t=ti(t)),l=u.length,c=Ny(1,l),f=sd(o,u,0);f!==-1;)h=d?ti(t(u,f,o)):xy(u,o,f,[],void 0,t),g+=id(o,v,f)+h,v=f+l,f=sd(o,u,f+c);return v<o.length&&(g+=id(o,v)),g}});var Fy=ln,Uy=Fy("String","replaceAll"),Vy=Uy,Hy=Vy,Gy=Hy,Yy=Gy,rd=Gs(Yy);const ad=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ea=(s,e)=>{let t=s;t=rd(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=rd(t,n,(o,u)=>ie(a)?o:ie(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jy=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,v,g,T,A,E,m,b,$,R,j,X,F,Y,K,O,G,ne,U,I,N,Z,pe,Se,Ce,et,Tt,ee;const Ue=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Ve=Ue.children[0],qt=Ve.getElementsByTagName("Period")[0],Ct=qt.children,zt=Ve.getAttribute("type")==="dynamic",Wt=Ve.getAttribute("availabilityStartTime"),Ji=Wt?new Date(Wt).getTime():void 0;let xt;const mn=Ve.getAttribute("mediaPresentationDuration"),gn=qt.getAttribute("duration"),ar=Ve.getElementsByTagName("vk:Attrs")[0],Sn=ar==null?void 0:ar.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(mn)xt=ad(mn);else if(gn){const We=ad(gn);k(We)&&(xt=We)}else Sn&&(xt=parseInt(Sn,10));let nl=0;const nr=(i=(t=Ve.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],ol=nr.includes(Fs.WEBM_AS_IN_FFMPEG)||nr.includes(Fs.WEBM_AS_IN_SPEC)?hi.WEBM:hi.MP4;for(const We of Ct){const Xi=We.getAttribute("mimeType"),dl=We.getAttribute("codecs"),bn=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:Xi==null?void 0:Xi.split("/")[0],ul=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],yn=We.querySelectorAll("Representation"),ll=We.querySelector("SegmentTemplate");if(bn===Ae.TEXT){for(const be of yn){const Et=be.getAttribute("id")||"",Zi=We.getAttribute("lang"),Qt=(d=(u=(o=be.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",or=new URL(Qt,e).toString(),dr=Et.includes("_auto");xe[Ae.TEXT].push({id:Et,lang:Zi,isAuto:dr,kind:Ae.TEXT,url:or})}continue}for(const be of yn){const Et=(l=be.getAttribute("mimeType"))!==null&&l!==void 0?l:Xi,Zi=(h=(c=be.getAttribute("codecs"))!==null&&c!==void 0?c:dl)!==null&&h!==void 0?h:"",Qt=(v=(f=be.getAttribute("contentType"))!==null&&f!==void 0?f:Et==null?void 0:Et.split("/")[0])!==null&&v!==void 0?v:bn,or=(T=(g=We.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&T!==void 0?T:[],dr=parseInt((A=be.getAttribute("width"))!==null&&A!==void 0?A:"",10),Tn=parseInt((E=be.getAttribute("height"))!==null&&E!==void 0?E:"",10),En=parseInt((m=be.getAttribute("bandwidth"))!==null&&m!==void 0?m:"",10)/1e3,$n=(b=be.getAttribute("frameRate"))!==null&&b!==void 0?b:"",cl=($=be.getAttribute("quality"))!==null&&$!==void 0?$:void 0,hl=$n?hn($n):void 0,fl=(R=be.getAttribute("id"))!==null&&R!==void 0?R:(nl++).toString(10),pl=Qt==="video"?`${Tn}p`:Qt==="audio"?`${En}Kbps`:Zi,vl=`${fl}@${pl}`,ml=(F=(X=(j=be.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||X===void 0?void 0:X.trim())!==null&&F!==void 0?F:"",An=new URL(ml,e).toString(),gl=[...nr,...ul,...or];let ur;const Sl=be.querySelector("SegmentBase"),Lt=(Y=be.querySelector("SegmentTemplate"))!==null&&Y!==void 0?Y:ll;if(Sl){const bi=(O=(K=be.querySelector("SegmentBase Initialization"))===null||K===void 0?void 0:K.getAttribute("range"))!==null&&O!==void 0?O:"",[yi,cr]=bi.split("-").map(Kt=>parseInt(Kt,10)),Ti={from:yi,to:cr},Ei=(G=be.querySelector("SegmentBase"))===null||G===void 0?void 0:G.getAttribute("indexRange"),[hr,es]=Ei?Ei.split("-").map(Kt=>parseInt(Kt,10)):[],$i=Ei?{from:hr,to:es}:void 0;ur={type:Ye.BYTE_RANGE,url:An,initRange:Ti,indexRange:$i}}else if(Lt){const bi={representationId:(ne=be.getAttribute("id"))!==null&&ne!==void 0?ne:void 0,bandwidth:(U=be.getAttribute("bandwidth"))!==null&&U!==void 0?U:void 0},yi=parseInt((I=Lt.getAttribute("timescale"))!==null&&I!==void 0?I:"",10),cr=(N=Lt.getAttribute("initialization"))!==null&&N!==void 0?N:"",Ti=Lt.getAttribute("media"),Ei=(pe=parseInt((Z=Lt.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&pe!==void 0?pe:1,hr=ea(cr,bi);if(!Ti)throw new ReferenceError("No media attribute in SegmentTemplate");const es=(Se=Lt.querySelectorAll("SegmentTimeline S"))!==null&&Se!==void 0?Se:[],$i=[];let Kt=0;if(es.length){let fr=Ei,lt=0;for(const Ai of es){const $t=parseInt((Ce=Ai.getAttribute("d"))!==null&&Ce!==void 0?Ce:"",10),Ot=parseInt((et=Ai.getAttribute("r"))!==null&&et!==void 0?et:"",10)||0,ts=parseInt((Tt=Ai.getAttribute("t"))!==null&&Tt!==void 0?Tt:"",10);lt=Number.isFinite(ts)?ts:lt;const pr=$t/yi*1e3,_n=lt/yi*1e3;for(let is=0;is<Ot+1;is++){const bl=ea(Ti,Object.assign(Object.assign({},bi),{segmentNumber:fr.toString(10),segmentTime:(lt+is*$t).toString(10)})),wn=(_n||0)+is*pr,yl=wn+pr;fr++,$i.push({time:{from:wn,to:yl},url:bl})}lt+=(Ot+1)*$t,Kt+=(Ot+1)*pr}}else if(k(xt)){const lt=parseInt((ee=Lt.getAttribute("duration"))!==null&&ee!==void 0?ee:"",10)/yi*1e3,Ai=Math.ceil(xt/lt);let $t=0;for(let Ot=1;Ot<Ai;Ot++){const ts=ea(Ti,Object.assign(Object.assign({},bi),{segmentNumber:Ot.toString(10),segmentTime:$t.toString(10)}));$i.push({time:{from:$t,to:$t+lt},url:ts}),$t+=lt}}ur={type:Ye.TEMPLATE,baseUrl:An,initUrl:hr,totalSegmentsDurationMs:Kt,segments:$i}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!Et)continue;const lr={video:Ae.VIDEO,audio:Ae.AUDIO,text:Ae.TEXT}[Qt];lr&&xe[lr].push({id:vl,kind:lr,segmentReference:ur,profiles:gl,duration:xt,bitrate:En,mime:Et,codecs:Zi,width:dr,height:Tn,fps:hl,quality:cl})}}return{dynamic:zt,liveAvailabilityStartTime:Ji,duration:xt,container:ol,representations:xe}},Na=1e3,nd=["timeupdate","progress","play","seeked","stalled","waiting"];var Ge;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ge||(Ge={}));let qy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ae,this.representationSubscription=new ae,this.state$=new ce(Ge.NONE),this.currentVideoRepresentation$=new S(void 0),this.currentVideoRepresentationInit$=new S(void 0),this.error$=new x,this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.isLive$=new S(!1),this.liveDuration$=new S(0),this.liveAvailabilityStartTime$=new S(void 0),this.bufferLength$=new S(0),this.liveLoadBufferLength$=new S(0),this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new di,this.initManifest=Oe(this.destroyController.signal,function(t,i,r){var a;return Me(this,arguments,function*(){this.element=t,this.manifestUrlString=Je(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ge.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Ge.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Oe(this.destroyController.signal,function(){var t;return Me(this,arguments,function*(){const i=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!i)return yield M(this.manifest);let r;try{r=jy(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Ae.TEXT)};return 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:li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Oe(this.destroyController.signal,function(t,i){return Me(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ge.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Zo(Ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(i)&&(this.audioBufferManager=new Zo(Ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Cs(Na).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Go(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=Je(this.manifestUrlString,d+1e3,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(V(...nd.map(o=>B(this.element,o))).pipe(Al(Na),w(o=>this.element?wt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(v=>{var g,T;return(T=(g=v.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&T!==void 0?T:0}))-h}this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(u=>ue(this,void 0,void 0,function*(){P(this.element);const d=this.element.playbackRate,l=Go(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),c=Jb*d,h=Zb*d,f=Xb*d;o=u>o?u:o;const v=l===0&&u<f,g=l!==0&&u<c+f&&u>=c,T=l!==0&&u<c;if(T||g){const A=o-(c+h),E=Math.trunc(l+A/d);let m;u?E>0?m=E:m=0:m=l,this.manifestUrlString=Je(this.manifestUrlString,m,Te.DASH_CMAF_OFFSET_P)}(v||T||g)&&(yield this.updateLive(),o=0)})))}const a=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(V(this.forceEnded$,Ne({allBuffersFull:a,someBufferEnded:n}).pipe(re(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(V(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield M(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),k(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&k(i)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Ge.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Cs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ry({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,i,r,a;return ue(this,void 0,void 0,function*(){P(this.element),this.manifestUrlString=Je(this.manifestUrlString,e,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){P(this.element),this.state$.setState(Ge.RUNNING),this.subscription.add(V(...nd.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ba(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ue(this,void 0,void 0,function*(){const i={[Ae.VIDEO]:this.videoBufferManager,[Ae.AUDIO]:this.audioBufferManager,[Ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Ba(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ge.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(),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}updateLive(){var e;return ue(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class zy{constructor(e,t){this.fov=e,this.orientation=t}}class Wy{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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Qy=`#define GLSLIFY 1
|
|
30
30
|
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;}`,Ky=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|