@vkontakte/videoplayer-core 2.0.92 → 2.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.92
3
- * Thu, 16 Nov 2023 17:30:22 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-92/doc/
2
+ * @vkontakte/videoplayer-core v2.0.93
3
+ * Fri, 17 Nov 2023 13:52:44 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-93/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 Fa,CurrentClientBrowser as bd,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 fa,isLowerOrEqual as yd,Observable as Hs,interval as Cs,VideoQuality as He,videoQualityToHeight as $l,abortable as Oe,getExponentialDelay as wn,throttle as Al,CurrentClientDevice as _l,safeStorage as pr,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.92";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 $t;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})($t||($t={}));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 vr=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")}),Td=Ys,Ed=Function.prototype,pa=Ed.call,Ll=Td&&Ed.bind.bind(pa,pa),ze=Td?Ll:function(s){return function(){return pa.apply(s,arguments)}},$d=ze,Ol=$d({}.toString),Ml=$d("".slice),Vi=function(s){return Ml(Ol(s),8,-1)},Bl=ze,Nl=qe,Fl=Vi,mr=Object,Ul=Bl("".split),Vl=Nl(function(){return!mr("z").propertyIsEnumerable(0)})?function(s){return Fl(s)=="String"?Ul(s,""):mr(s)}:mr,Hi=function(s){return s==null},Hl=Hi,Gl=TypeError,Ua=function(s){if(Hl(s))throw Gl("Can't call method on "+s);return s},Yl=Vl,jl=Ua,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 vr=="object"&&vr)||function(){return this}()||vr||Function("return this")(),va=typeof document=="object"&&document.all,ql=typeof va=="undefined"&&va!==void 0,Ad={all:va,IS_HTMLDDA:ql},_d=Ad,zl=_d.all,Ee=_d.IS_HTMLDDA?function(s){return typeof s=="function"||s===zl}:function(s){return typeof s=="function"},Wl=_e,Ql=Ee,kn=Wl.WeakMap,Kl=Ql(kn)&&/native code/.test(String(kn)),Pn=Ee,wd=Ad,Jl=wd.all,vt=wd.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Pn(s)||s===Jl}:function(s){return typeof s=="object"?s!==null:Pn(s)},Xl=qe,Pt=!Xl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ht={},Zl=_e,Rn=vt,ma=Zl.document,ec=Rn(ma)&&Rn(ma.createElement),Va=function(s){return ec?ma.createElement(s):{}},tc=Pt,ic=qe,sc=Va,kd=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Pt,ac=qe,Pd=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)},Ha={},gr=Ha,Sr=_e,lc=Ee,Dn=function(s){return lc(s)?s:void 0},Gt=function(s,e){return arguments.length<2?Dn(gr[s])||Dn(Sr[s]):gr[s]&&gr[s][e]||Sr[s]&&Sr[s][e]},cc=ze,js=cc({}.isPrototypeOf),qs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Rd=_e,br=qs,In=Rd.process,Cn=Rd.Deno,xn=In&&In.versions||Cn&&Cn.version,Ln=xn&&xn.v8,Ke,xs;Ln&&(Ke=Ln.split("."),xs=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!xs&&br&&(Ke=br.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=br.match(/Chrome\/(\d+)/),Ke&&(xs=+Ke[1])));var Dd=xs,On=Dd,hc=qe,fc=_e,pc=fc.String,Id=!!Object.getOwnPropertySymbols&&!hc(function(){var s=Symbol();return!pc(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&On&&On<41}),vc=Id,Cd=vc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",mc=Gt,gc=Ee,Sc=js,bc=Cd,yc=Object,xd=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)},yr=Fe,Tr=Ee,Er=vt,kc=TypeError,Pc=function(s,e){var t,i;if(e==="string"&&Tr(t=s.toString)&&!Er(i=yr(t,s))||Tr(t=s.valueOf)&&!Er(i=yr(t,s))||e!=="string"&&Tr(t=s.toString)&&!Er(i=yr(t,s)))return i;throw kc("Can't convert object to primitive value")},Ld={exports:{}},Rc=!0,Mn=_e,Dc=Object.defineProperty,Ic=function(s,e){try{Dc(Mn,s,{value:e,configurable:!0,writable:!0})}catch(t){Mn[s]=e}return e},Cc=_e,xc=Ic,Bn="__core-js_shared__",Lc=Cc[Bn]||xc(Bn,{}),Ga=Lc,Nn=Ga;(Ld.exports=function(s,e){return Nn[s]||(Nn[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 Od=Ld.exports,Oc=Ua,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),Md=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Gc(++Vc+Hc,36)},Yc=_e,jc=Od,Fn=ot,qc=Md,zc=Id,Wc=Cd,si=Yc.Symbol,$r=jc("wks"),Qc=Wc?si.for||si:si&&si.withoutSetter||qc,Pe=function(s){return Fn($r,s)||($r[s]=zc&&Fn(si,s)?si[s]:Qc("Symbol."+s)),$r[s]},Kc=Fe,Un=vt,Vn=xd,Jc=Ws,Xc=Pc,Zc=Pe,eh=TypeError,th=Zc("toPrimitive"),ih=function(s,e){if(!Un(s)||Vn(s))return s;var t=Jc(s,th),i;if(t){if(e===void 0&&(e="default"),i=Kc(t,s,e),!Un(i)||Vn(i))return i;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(s,e)},sh=ih,rh=xd,Ya=function(s){var e=sh(s,"string");return rh(e)?e:e+""},ah=Pt,nh=kd,oh=Pd,as=mt,Hn=Ya,dh=TypeError,Ar=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,_r="enumerable",wr="configurable",kr="writable";Ht.f=ah?oh?function(e,t,i){if(as(e),t=Hn(t),as(i),typeof e=="function"&&t==="prototype"&&"value"in i&&kr in i&&!i[kr]){var r=uh(e,t);r&&r[kr]&&(e[t]=i.value,i={configurable:wr in i?i[wr]:r[wr],enumerable:_r in i?i[_r]:r[_r],writable:!1})}return Ar(e,t,i)}:Ar:function(e,t,i){if(as(e),t=Hn(t),as(i),nh)try{return Ar(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=Pt,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=Od,ph=Md,Gn=fh("keys"),ja=function(s){return Gn[s]||(Gn[s]=ph(s))},qa={},vh=Kl,Bd=_e,mh=vt,gh=Yi,Pr=ot,Rr=Ga,Sh=ja,bh=qa,Yn="Object already initialized",ga=Bd.TypeError,yh=Bd.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 ga("Incompatible receiver, "+s+" required");return t}};if(vh||Rr.state){var et=Rr.state||(Rr.state=new yh);et.get=et.get,et.has=et.has,et.set=et.set,Ls=function(s,e){if(et.has(s))throw ga(Yn);return e.facade=s,et.set(s,e),e},Bi=function(s){return et.get(s)||{}},Os=function(s){return et.has(s)}}else{var Jt=Sh("state");bh[Jt]=!0,Ls=function(s,e){if(Pr(s,Jt))throw ga(Yn);return e.facade=s,gh(s,Jt,e),e},Bi=function(s){return Pr(s,Jt)?s[Jt]:{}},Os=function(s){return Pr(s,Jt)}}var Nd={set:Ls,get:Bi,has:Os,enforce:Th,getterFor:Eh},$h=Ys,Fd=Function.prototype,jn=Fd.apply,qn=Fd.call,Ud=typeof Reflect=="object"&&Reflect.apply||($h?qn.bind(jn):function(){return qn.apply(jn,arguments)}),Ah=Vi,_h=ze,Vd=function(s){if(Ah(s)==="Function")return _h(s)},za={},Hd={},Gd={}.propertyIsEnumerable,Yd=Object.getOwnPropertyDescriptor,wh=Yd&&!Gd.call({1:2},1);Hd.f=wh?function(e){var t=Yd(this,e);return!!t&&t.enumerable}:Gd;var kh=Pt,Ph=Fe,Rh=Hd,Dh=Ks,Ih=Gi,Ch=Ya,xh=ot,Lh=kd,zn=Object.getOwnPropertyDescriptor;za.f=kh?zn:function(e,t){if(e=Ih(e),t=Ch(t),Lh)try{return zn(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",jd=ji,Wn=Vd,Hh=Yt,Gh=Ys,Yh=Wn(Wn.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=Ud,qh=Vd,zh=Ee,Wh=za.f,Qh=jd,Xt=Ha,Kh=Js,Zt=Yi,Qn=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},Xe=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&&Qn(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",Qn(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],h,f),s.real&&u&&(d||!u[h])&&Zt(u,h,f)))},Sa=Pt,Xh=ot,qd=Function.prototype,Zh=Sa&&Object.getOwnPropertyDescriptor,Wa=Xh(qd,"name"),ef=Wa&&function(){}.name==="something",tf=Wa&&(!Sa||Sa&&Zh(qd,"name").configurable),sf={EXISTS:Wa,PROPER:ef,CONFIGURABLE:tf},zd={},rf=Math.ceil,af=Math.floor,nf=Math.trunc||function(e){var t=+e;return(t>0?af:rf)(t)},of=nf,Qa=function(s){var e=+s;return e!==e||e===0?0:of(e)},df=Qa,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=Qa,ff=Math.min,pf=function(s){return s>0?ff(hf(s),9007199254740991):0},vf=pf,Ka=function(s){return vf(s.length)},mf=Gi,gf=cf,Sf=Ka,Kn=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:Kn(!0),indexOf:Kn(!1)},yf=ze,Dr=ot,Tf=Gi,Ef=bf.indexOf,$f=qa,Jn=yf([].push),Af=function(s,e){var t=Tf(s),i=0,r=[],a;for(a in t)!Dr($f,a)&&Dr(t,a)&&Jn(r,a);for(;e.length>i;)Dr(t,a=e[i++])&&(~Ef(r,a)||Jn(r,a));return r},Wd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_f=Af,wf=Wd,kf=Object.keys||function(e){return _f(e,wf)},Pf=Pt,Rf=Pd,Df=Ht,If=mt,Cf=Gi,xf=kf;zd.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,Qd=Lf("document","documentElement"),Of=mt,Mf=zd,Xn=Wd,Bf=qa,Nf=Qd,Ff=Va,Uf=ja,Zn=">",eo="<",ba="prototype",ya="script",Kd=Uf("IE_PROTO"),Ir=function(){},Jd=function(s){return eo+ya+Zn+s+eo+"/"+ya+Zn},to=function(s){s.write(Jd("")),s.close();var e=s.parentWindow.Object;return s=null,e},Vf=function(){var s=Ff("iframe"),e="java"+ya+":",t;return s.style.display="none",Nf.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Jd("document.F=Object")),t.close(),t.F},os,ks=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&os?to(os):Vf():to(os);for(var s=Xn.length;s--;)delete ks[ba][Xn[s]];return ks()};Bf[Kd]=!0;var Xd=Object.create||function(e,t){var i;return e!==null?(Ir[ba]=Of(e),i=new Ir,Ir[ba]=null,i[Kd]=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=ja,Wf=Gf,io=zf("IE_PROTO"),Ta=Object,Qf=Ta.prototype,Zd=Wf?Ta.getPrototypeOf:function(s){var e=qf(s);if(Yf(e,io))return e[io];var t=e.constructor;return jf(t)&&e instanceof t?t.prototype:e instanceof Ta?Qf:null},Kf=Yi,Ja=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Kf(s,e,t),s},Jf=qe,Xf=Ee,Zf=vt,ep=Xd,so=Zd,tp=Ja,ip=Pe,Ea=ip("iterator"),eu=!1,ht,Cr,xr;[].keys&&(xr=[].keys(),"next"in xr?(Cr=so(so(xr)),Cr!==Object.prototype&&(ht=Cr)):eu=!0);var sp=!Zf(ht)||Jf(function(){var s={};return ht[Ea].call(s)!==s});sp?ht={}:ht=ep(ht);Xf(ht[Ea])||tp(ht,Ea,function(){return this});var tu={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:eu},rp=Pe,ap=rp("toStringTag"),iu={};iu[ap]="z";var Xa=String(iu)==="[object z]",np=Xa,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=Xa,pp=qi,vp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},mp=Xa,gp=Ht.f,Sp=Yi,bp=ot,yp=vp,Tp=Pe,ro=Tp("toStringTag"),Za=function(s,e,t,i){if(s){var r=t?s:s.prototype;bp(r,ro)||gp(r,ro,{configurable:!0,value:e}),i&&!mp&&Sp(r,"toString",yp)}},Ep=tu.IteratorPrototype,$p=Xd,Ap=Ks,_p=Za,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=Xe,Dp=Fe,su=sf,Ip=Pp,Cp=Zd,xp=Za,ao=Ja,Lp=Pe,no=pi,ru=tu,Op=su.PROPER;su.CONFIGURABLE;ru.IteratorPrototype;var ds=ru.BUGGY_SAFARI_ITERATORS,Lr=Lp("iterator"),oo="keys",us="values",uo="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 oo:return function(){return new t(this,A)};case us:return function(){return new t(this,A)};case uo:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Lr]||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),no[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(oo),entries:o(uo)},n)for(T in g)(ds||d||!(T in l))&&ao(l,T,g[T]);else Rp({target:e,proto:!0,forced:ds||d},g);return n&&l[Lr]!==h&&ao(l,Lr,h,{name:r}),no[e]=h,g},Np=function(s,e){return{value:s,done:e}},Fp=Gi,lo=pi,au=Nd;Ht.f;var Up=Bp,ls=Np,nu="Array Iterator",Vp=au.set,Hp=au.getterFor(nu);Up(Array,"Array",function(s,e){Vp(this,{type:nu,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");lo.Arguments=lo.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,co=Ws,Qp=Hi,Kp=pi,Jp=Pe,Xp=Jp("iterator"),ou=function(s){if(!Qp(s))return co(s,Xp)||co(s,"@@iterator")||Kp[Wp(s)]},Zp=Fe,ev=Yt,tv=mt,iv=zs,sv=ou,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,ho=mt,ov=Ws,dv=function(s,e,t){var i,r;ho(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 ho(i),t},uv=Js,lv=Fe,cv=mt,hv=zs,fv=zp,pv=Ka,fo=js,vv=av,mv=ou,po=dv,gv=TypeError,Rs=function(s,e){this.stopped=s,this.result=e},vo=Rs.prototype,en=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&&po(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&&fo(vo,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){po(d,"throw",E)}if(typeof f=="object"&&f&&fo(vo,f))return f}return new Rs(!1)},Sv=Ya,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=Xe,$v=en,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=Ha,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,mo=pi,Cv=Pe,go=Cv("toStringTag");for(var Or in Pv){var So=Rv[Or],Mr=So&&So.prototype;Mr&&Dv(Mr)!==go&&Iv(Mr,go,Or),mo[Or]=mo.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=Pt,bo=Hv("species"),Yv=function(s){var e=Uv(s);Gv&&e&&!e[bo]&&Vv(e,bo,{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,$a=Ga,Kv=Wv(Function.toString);Qv($a.inspectSource)||($a.inspectSource=function(s){return Kv(s)});var du=$a.inspectSource,Jv=ze,Xv=qe,uu=Ee,Zv=qi,em=Gt,tm=du,lu=function(){},im=[],cu=em("Reflect","construct"),tn=/^\s*(?:class|function)\b/,sm=Jv(tn.exec),rm=!tn.exec(lu),_i=function(e){if(!uu(e))return!1;try{return cu(lu,im,e),!0}catch(t){return!1}},hu=function(e){if(!uu(e))return!1;switch(Zv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rm||!!sm(tn,tm(e))}catch(t){return!0}};hu.sham=!0;var am=!cu||Xv(function(){var s;return _i(_i.call)||!_i(Object)||!_i(function(){s=!0})||s})?hu:_i,nm=am,om=zs,dm=TypeError,um=function(s){if(nm(s))return s;throw dm(om(s)+" is not a constructor")},yo=mt,lm=um,cm=Hi,hm=Pe,fm=hm("species"),fu=function(s,e){var t=yo(s).constructor,i;return t===void 0||cm(i=yo(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,pu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sm),Be=_e,bm=Ud,ym=Js,To=Ee,Tm=ot,vu=qe,Eo=Qd,Em=vm,$o=Va,$m=gm,Am=pu,_m=Xs,Aa=Be.setImmediate,_a=Be.clearImmediate,wm=Be.process,Br=Be.Dispatch,km=Be.Function,Ao=Be.MessageChannel,Pm=Be.String,Nr=0,Ci={},_o="onreadystatechange",Ni,Mt,Fr,Ur;vu(function(){Ni=Be.location});var sn=function(s){if(Tm(Ci,s)){var e=Ci[s];delete Ci[s],e()}},Vr=function(s){return function(){sn(s)}},wo=function(s){sn(s.data)},ko=function(s){Be.postMessage(Pm(s),Ni.protocol+"//"+Ni.host)};(!Aa||!_a)&&(Aa=function(e){$m(arguments.length,1);var t=To(e)?e:km(e),i=Em(arguments,1);return Ci[++Nr]=function(){bm(t,void 0,i)},Mt(Nr),Nr},_a=function(e){delete Ci[e]},_m?Mt=function(s){wm.nextTick(Vr(s))}:Br&&Br.now?Mt=function(s){Br.now(Vr(s))}:Ao&&!Am?(Fr=new Ao,Ur=Fr.port2,Fr.port1.onmessage=wo,Mt=ym(Ur.postMessage,Ur)):Be.addEventListener&&To(Be.postMessage)&&!Be.importScripts&&Ni&&Ni.protocol!=="file:"&&!vu(ko)?(Mt=ko,Be.addEventListener("message",wo,!1)):_o in $o("script")?Mt=function(s){Eo.appendChild($o("script"))[_o]=function(){Eo.removeChild(this),sn(s)}}:Mt=function(s){setTimeout(Vr(s),0)});var mu={set:Aa,clear:_a},gu=function(){this.head=null,this.tail=null};gu.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 Su=gu,Rm=qs,Dm=/ipad|iphone|ipod/i.test(Rm)&&typeof Pebble!="undefined",Im=qs,Cm=/web0s(?!.*chrome)/i.test(Im),Ut=_e,Po=Js,xm=za.f,Hr=mu.set,Lm=Su,Om=pu,Mm=Dm,Bm=Cm,Gr=Xs,Ro=Ut.MutationObserver||Ut.WebKitMutationObserver,Do=Ut.document,Io=Ut.process,cs=Ut.Promise,Co=xm(Ut,"queueMicrotask"),wa=Co&&Co.value,ei,Yr,jr,hs,xo;if(!wa){var fs=new Lm,ps=function(){var s,e;for(Gr&&(s=Io.domain)&&s.exit();e=fs.get();)try{e()}catch(t){throw fs.head&&ei(),t}s&&s.enter()};!Om&&!Gr&&!Bm&&Ro&&Do?(Yr=!0,jr=Do.createTextNode(""),new Ro(ps).observe(jr,{characterData:!0}),ei=function(){jr.data=Yr=!Yr}):!Mm&&cs&&cs.resolve?(hs=cs.resolve(void 0),hs.constructor=cs,xo=Po(hs.then,hs),ei=function(){xo(ps)}):Gr?ei=function(){Io.nextTick(ps)}:(Hr=Po(Hr,Ut),ei=function(){Hr(ps)}),wa=function(s){fs.head||ei(),fs.add(s)}}var Nm=wa,Fm=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},rn=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Um=_e,vi=Um.Promise,bu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vm=bu,Hm=Xs,Gm=!Vm&&!Hm&&typeof window=="object"&&typeof document=="object",Ym=_e,xi=vi,jm=Ee,qm=jd,zm=du,Wm=Pe,Qm=Gm,Km=bu,qr=Dd,Lo=xi&&xi.prototype,Jm=Wm("species"),ka=!1,yu=jm(Ym.PromiseRejectionEvent),Xm=qm("Promise",function(){var s=zm(xi),e=s!==String(xi);if(!e&&qr===66||!(Lo.catch&&Lo.finally))return!0;if(!qr||qr<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,ka=t.then(function(){})instanceof i,!ka)return!0}return!e&&(Qm||Km)&&!yu}),zi={CONSTRUCTOR:Xm,REJECTION_EVENT:yu,SUBCLASSING:ka},mi={},Oo=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=Oo(e),this.reject=Oo(t)};mi.f=function(s){return new eg(s)};var tg=Xe,Ms=Xs,kt=_e,Wi=Fe,ig=Ja,sg=Za,rg=Yv,ag=Yt,Pa=Ee,ng=vt,og=zv,dg=fu,Tu=mu.set,an=Nm,ug=Fm,lg=rn,cg=Su,Eu=Nd,Ra=vi,nn=zi,$u=mi,Zs="Promise",Au=nn.CONSTRUCTOR,hg=nn.REJECTION_EVENT;nn.SUBCLASSING;var zr=Eu.getterFor(Zs),fg=Eu.set,pg=Ra&&Ra.prototype,ri=Ra,Wr=pg,_u=kt.TypeError,Da=kt.document,on=kt.process,Ia=$u.f,vg=Ia,mg=!!(Da&&Da.createEvent&&kt.dispatchEvent),wu="unhandledrejection",gg="rejectionhandled",Mo=0,ku=1,Sg=2,dn=1,Pu=2,vs,Bo,bg,Ru=function(s){var e;return ng(s)&&Pa(e=s.then)?e:!1},Du=function(s,e){var t=e.value,i=e.state==ku,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Pu&&Tg(e),e.rejection=dn),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(_u("Promise-chain cycle")):(d=Ru(u))?Wi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Iu=function(s,e){s.notified||(s.notified=!0,an(function(){for(var t=s.reactions,i;i=t.get();)Du(i,s);s.notified=!1,e&&!s.rejection&&yg(s)}))},Cu=function(s,e,t){var i,r;mg?(i=Da.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),kt.dispatchEvent(i)):i={promise:e,reason:t},!hg&&(r=kt["on"+s])?r(i):s===wu&&ug("Unhandled promise rejection",t)},yg=function(s){Wi(Tu,kt,function(){var e=s.facade,t=s.value,i=No(s),r;if(i&&(r=lg(function(){Ms?on.emit("unhandledRejection",t,e):Cu(wu,e,t)}),s.rejection=Ms||No(s)?Pu:dn,r.error))throw r.value})},No=function(s){return s.rejection!==dn&&!s.parent},Tg=function(s){Wi(Tu,kt,function(){var e=s.facade;Ms?on.emit("rejectionHandled",e):Cu(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,Iu(s,!0))},Ca=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw _u("Promise can't be resolved itself");var i=Ru(e);i?an(function(){var r={done:!1};try{Wi(i,e,ai(Ca,r,s),ai(oi,r,s))}catch(a){oi(r,a,s)}}):(s.value=e,s.state=ku,Iu(s,!1))}catch(r){oi({done:!1},r,s)}}};Au&&(ri=function(e){og(this,Wr),ag(e),Wi(vs,this);var t=zr(this);try{e(ai(Ca,t),ai(oi,t))}catch(i){oi(t,i)}},Wr=ri.prototype,vs=function(e){fg(this,{type:Zs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:Mo,value:void 0})},vs.prototype=ig(Wr,"then",function(e,t){var i=zr(this),r=Ia(dg(this,ri));return i.parent=!0,r.ok=Pa(e)?e:!0,r.fail=Pa(t)&&t,r.domain=Ms?on.domain:void 0,i.state==Mo?i.reactions.add(r):an(function(){Du(r,i)}),r.promise}),Bo=function(){var s=new vs,e=zr(s);this.promise=s,this.resolve=ai(Ca,e),this.reject=ai(oi,e)},$u.f=Ia=function(s){return s===ri||s===bg?new Bo(s):vg(s)});tg({global:!0,constructor:!0,wrap:!0,forced:Au},{Promise:ri});sg(ri,Zs,!1,!0);rg(Zs);var Eg=Pe,xu=Eg("iterator"),Lu=!1;try{var $g=0,Fo={next:function(){return{done:!!$g++}},return:function(){Lu=!0}};Fo[xu]=function(){return this},Array.from(Fo,function(){throw 2})}catch(s){}var Ag=function(s,e){if(!e&&!Lu)return!1;var t=!1;try{var i={};i[xu]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},_g=vi,wg=Ag,kg=zi.CONSTRUCTOR,Ou=kg||!wg(function(s){_g.all(s).then(void 0,function(){})}),Pg=Xe,Rg=Fe,Dg=Yt,Ig=mi,Cg=rn,xg=en,Lg=Ou;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=Xe,Mg=zi.CONSTRUCTOR,Uo=vi;Uo&&Uo.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(s){return this.then(void 0,s)}});var Bg=Xe,Ng=Fe,Fg=Yt,Ug=mi,Vg=rn,Hg=en,Gg=Ou;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=Xe,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,Mu=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=Xe,Xg=Gt,Zg=Rc,eS=vi,tS=zi.CONSTRUCTOR,iS=Mu,sS=Xg("Promise"),rS=!tS;Jg({target:"Promise",stat:!0,forced:Zg},{resolve:function(e){return iS(rS&&this===sS?eS:this,e)}});var aS=Xe,xa=vi,nS=qe,oS=Gt,dS=Ee,uS=fu,Vo=Mu,lS=xa&&xa.prototype,cS=!!xa&&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 Vo(e,s()).then(function(){return i})}:s,t?function(i){return Vo(e,s()).then(function(){throw i})}:s)}});var hS=Gt,un=hS,fS=un,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 nt=(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 Ho=(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,Go=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=nt(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(Go).subscribe(()=>a(`timeout(${Go})`)))});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 Je=(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)=>Je(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),gt=(s,e,t,i)=>Je(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}),Rt=(s,e,t,i)=>Je(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(Je(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(Je(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(Je(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(Je(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 ln=s=>{s.removeAttribute("src"),s.load()},DS=s=>{try{s.pause(),s.playbackRate=0,ln(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 La=window.WeakMap?new WeakMap:new IS,St=s=>{let e=s.querySelector("video");const t=!!e;return e?ln(e):(e=document.createElement("video"),s.appendChild(e)),La.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=La.get(s);La.delete(s),e?ln(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 Bu=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},Yo=s=>{const e=Bu(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},CS=s=>{const e=Bu(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Oa=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<Oa&&(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||Oa))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 Nu=(s,e,t=Oa)=>{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(()=>Nu(s.buffered,s.currentTime))),n=Fa().browser===bd.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(Yo(s));return B(s,"fullscreenchange").pipe(w(()=>Yo(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}},cn=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var LS=Xe,OS=Qs,MS=Ka,BS=Qa;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=un,FS=NS("Array","at"),US=FS,VS=US,HS=VS,GS=HS,it=Gs(GS);let hn=!1,ct={};const YS=s=>{hn=s},jS=()=>{ct={}},qS=s=>{s(ct)},ms=(s,e)=>{var t;hn&&(ct.meta=(t=ct.meta)!==null&&t!==void 0?t:{},ct.meta[s]=e)};class st{constructor(e){this.name=e}next(e){var t,i;if(!hn)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 st("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=it($,-1))===null||f===void 0?void 0:f.quality,j=(v=it($,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&&fa(U.quality,l)?(Y[U.quality]=Nt.DroppedFramesLimit,!1):X||(ie(r.max)||yd(U.quality,r.max))&&(ie(r.min)||fa(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.93";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 et=Dr.state||(Dr.state=new yh);et.get=et.get,et.has=et.has,et.set=et.set,Ls=function(s,e){if(et.has(s))throw Sa(jn);return e.facade=s,et.set(s,e),e},Bi=function(s){return et.get(s)||{}},Os=function(s){return et.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},Xe=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=Xe,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=Xe,$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=Xe,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=Xe,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=Xe,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=Xe,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=Xe,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=Xe,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=Xe,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 nt=(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=nt(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 Je=(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)=>Je(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),gt=(s,e,t,i)=>Je(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)=>Je(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(Je(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(Je(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(Je(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(Je(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=Xe,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,it=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 st{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 st("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=it($,-1))===null||f===void 0?void 0:f.quality,j=(v=it($,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 jo{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?cn(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(Je(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(Je(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(()=>Nu(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(Rt(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=nt(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 qo=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 Dt=s=>ue(void 0,void 0,void 0,function*(){const e=s.muted;try{yield s.play()}catch(t){if(!qo(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{yield s.play()}catch(i){return qo(i)&&(s.muted=!1,console.warn(i)),!1}}return!0});function ke(){return me()}function Fu(s){return ke()-s}function zo(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=Fu(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=zo(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=zo(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,Ze(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=It=>{window.setTimeout(()=>{c()&&Z(ee,Re)},It)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),qt(100);else{const It=ke(),zt=$.currentTime;!this.paused&&$.buffered.length>1&&ne===zt&&It-U>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ne!==zt&&(ne=zt,U=It);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:It,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())},Ze=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&&Fu(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;Dt(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(nt(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:n===p.PLAYING&&(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)):this.seek(-this.liveOffset.getTotalOffset()));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(Rt(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(nt(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Uu=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}},_t=(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 Vu{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 Vu(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 Vu(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 Ze=d.parentElement;if((Ze==null?void 0:Ze.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=Ze.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?cn(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(Rt(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=_t(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=_t(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}=Uu(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(){Dt(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 Wo{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 Hu extends Wo{constructor(){super(),this.listeners||Wo.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 Gu=class{constructor(){Object.defineProperty(this,"signal",{value:new Hu,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&&(Gu.prototype[Symbol.toStringTag]="AbortController",Hu.prototype[Symbol.toStringTag]="AbortSignal");function Yu(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(!Yu({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=Yu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ju=sr?Sb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Fi=sr?ju.fetch:window.fetch;sr?ju.Request:window.Request;const di=sr?Gu:window.AbortController;var Ma=(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",Qo=yb?bb:window.requestIdleCallback;var Qr,Kr;let qu=!1;try{qu=Fa().browser===bd.Safari&&parseInt((Kr=(Qr=navigator.userAgent.match(/Version\/(\d+)/))===null||Qr===void 0?void 0:Qr[1])!==null&&Kr!==void 0?Kr:"",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;qu&&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 Ko=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 zu 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:zu};class Mb{createBox(e,t){const i=Ob[e];return i?new i(t):new zu(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 Jo={[_.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}},Wu=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 Jo,a=r?Jo[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},rt=(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=Wu(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=Wu(s);return fi(r.value,({tag:a,type:n,value:o})=>(a===_.EBMLReadVersion?e=rt(o,n):a===_.DocType?t=rt(o,n):a===_.DocTypeReadVersion&&(i=rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Qu=[_.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=rt(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=rt(v,f):h===_.Duration?r=rt(v,f):h===_.SeekPosition&&d===_.Cues?u=rt(v,f):h===_.Tracks?fi(v,({tag:T,type:A,value:E})=>T===_.ProjectionType?(l=rt(E,A)===1,!1):!0):a&&n&&Qu.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=rt(d,u));break;case _.CueTrackPositions:break;case _.CueClusterPosition:n&&(n.position=rt(d,u));break;default:t&&Qu.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},Ku=1e4,Jb=3e4,Xb=5e3,Zb=Ku,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=it(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:it(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<Ku&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Xo{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,Ko(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=_t(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)&&Ko(this.sourceBuffer.buffered)>=this.bufferLimit){const d=_t(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=it(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&&_t(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=it(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=it(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&&!Ma(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:it(e,0).byte.from,to:it(e,-1).byte.to};break}case Ye.TEMPLATE:{const d=it(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=wn(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=_t((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=Qo(()=>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=wn(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=Qo(()=>{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}=Uu(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,Zo=RegExp.prototype,by=function(s){var e=s.flags;return e===void 0&&!("flags"in Zo)&&!my(s,"flags")&&gy(Zo,s)?vy(Sy,s):e},fn=ze,yy=Qs,Ty=Math.floor,Jr=fn("".charAt),Ey=fn("".replace),Xr=fn("".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(Jr(l,0)){case"$":return"$";case"&":return s;case"`":return Xr(e,0,t);case"'":return Xr(e,n);case"<":c=r[Xr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ty(h/10);return f===0?d:f<=o?i[f-1]===void 0?Jr(l,1):i[f-1]+Jr(l,1):d}c=i[h-1]}return c===void 0?"":c})},wy=Xe,ky=Fe,pn=ze,ed=Ua,Py=Ee,Ry=Hi,Dy=uy,ti=hy,Iy=Ws,Cy=by,xy=_y,Ly=Pe,Oy=Ly("replace"),My=TypeError,Ju=pn("".indexOf),By=pn("".replace),td=pn("".slice),Ny=Math.max,id=function(s,e,t){return t>s.length?-1:e===""?t:Ju(s,e,t)};wy({target:"String",proto:!0},{replaceAll:function(e,t){var i=ed(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(ed(Cy(e))),!~Ju(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=id(o,u,0);f!==-1;)h=d?ti(t(u,f,o)):xy(u,o,f,[],void 0,t),g+=td(o,v,f)+h,v=f+l,f=id(o,u,f+c);return v<o.length&&(g+=td(o,v)),g}});var Fy=un,Uy=Fy("String","replaceAll"),Vy=Uy,Hy=Vy,Gy=Hy,Yy=Gy,sd=Gs(Yy);const rd=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},Zr=(s,e)=>{let t=s;t=sd(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=sd(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,Ze,Tt,ee;const Ue=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Ve=Ue.children[0],qt=Ve.getElementsByTagName("Period")[0],It=qt.children,zt=Ve.getAttribute("type")==="dynamic",Wt=Ve.getAttribute("availabilityStartTime"),Ji=Wt?new Date(Wt).getTime():void 0;let Ct;const vn=Ve.getAttribute("mediaPresentationDuration"),mn=qt.getAttribute("duration"),ar=Ve.getElementsByTagName("vk:Attrs")[0],gn=ar==null?void 0:ar.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(vn)Ct=rd(vn);else if(mn){const We=rd(mn);k(We)&&(Ct=We)}else gn&&(Ct=parseInt(gn,10));let al=0;const nr=(i=(t=Ve.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],nl=nr.includes(Fs.WEBM_AS_IN_FFMPEG)||nr.includes(Fs.WEBM_AS_IN_SPEC)?hi.WEBM:hi.MP4;for(const We of It){const Xi=We.getAttribute("mimeType"),ol=We.getAttribute("codecs"),Sn=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:Xi==null?void 0:Xi.split("/")[0],dl=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],bn=We.querySelectorAll("Representation"),ul=We.querySelector("SegmentTemplate");if(Sn===Ae.TEXT){for(const be of bn){const xt=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();xe[Ae.TEXT].push({id:xt,lang:Zi,kind:Ae.TEXT,url:or})}continue}for(const be of bn){const xt=(l=be.getAttribute("mimeType"))!==null&&l!==void 0?l:Xi,Zi=(h=(c=be.getAttribute("codecs"))!==null&&c!==void 0?c:ol)!==null&&h!==void 0?h:"",Qt=(v=(f=be.getAttribute("contentType"))!==null&&f!==void 0?f:xt==null?void 0:xt.split("/")[0])!==null&&v!==void 0?v:Sn,or=(T=(g=We.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&T!==void 0?T:[],ll=parseInt((A=be.getAttribute("width"))!==null&&A!==void 0?A:"",10),yn=parseInt((E=be.getAttribute("height"))!==null&&E!==void 0?E:"",10),Tn=parseInt((m=be.getAttribute("bandwidth"))!==null&&m!==void 0?m:"",10)/1e3,En=(b=be.getAttribute("frameRate"))!==null&&b!==void 0?b:"",cl=($=be.getAttribute("quality"))!==null&&$!==void 0?$:void 0,hl=En?cn(En):void 0,fl=(R=be.getAttribute("id"))!==null&&R!==void 0?R:(al++).toString(10),pl=Qt==="video"?`${yn}p`:Qt==="audio"?`${Tn}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:"",$n=new URL(ml,e).toString(),gl=[...nr,...dl,...or];let dr;const Sl=be.querySelector("SegmentBase"),Lt=(Y=be.querySelector("SegmentTemplate"))!==null&&Y!==void 0?Y:ul;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,lr]=bi.split("-").map(Kt=>parseInt(Kt,10)),Ti={from:yi,to:lr},Ei=(G=be.querySelector("SegmentBase"))===null||G===void 0?void 0:G.getAttribute("indexRange"),[cr,es]=Ei?Ei.split("-").map(Kt=>parseInt(Kt,10)):[],$i=Ei?{from:cr,to:es}:void 0;dr={type:Ye.BYTE_RANGE,url:$n,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),lr=(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,cr=Zr(lr,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 hr=Ei,lt=0;for(const Ai of es){const Et=parseInt((Ce=Ai.getAttribute("d"))!==null&&Ce!==void 0?Ce:"",10),Ot=parseInt((Ze=Ai.getAttribute("r"))!==null&&Ze!==void 0?Ze:"",10)||0,ts=parseInt((Tt=Ai.getAttribute("t"))!==null&&Tt!==void 0?Tt:"",10);lt=Number.isFinite(ts)?ts:lt;const fr=Et/yi*1e3,An=lt/yi*1e3;for(let is=0;is<Ot+1;is++){const bl=Zr(Ti,Object.assign(Object.assign({},bi),{segmentNumber:hr.toString(10),segmentTime:(lt+is*Et).toString(10)})),_n=(An||0)+is*fr,yl=_n+fr;hr++,$i.push({time:{from:_n,to:yl},url:bl})}lt+=(Ot+1)*Et,Kt+=(Ot+1)*fr}}else if(k(Ct)){const lt=parseInt((ee=Lt.getAttribute("duration"))!==null&&ee!==void 0?ee:"",10)/yi*1e3,Ai=Math.ceil(Ct/lt);let Et=0;for(let Ot=1;Ot<Ai;Ot++){const ts=Zr(Ti,Object.assign(Object.assign({},bi),{segmentNumber:Ot.toString(10),segmentTime:Et.toString(10)}));$i.push({time:{from:Et,to:Et+lt},url:ts}),Et+=lt}}dr={type:Ye.TEMPLATE,baseUrl:$n,initUrl:cr,totalSegmentsDurationMs:Kt,segments:$i}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!xt)continue;const ur={video:Ae.VIDEO,audio:Ae.AUDIO,text:Ae.TEXT}[Qt];ur&&xe[ur].push({id:vl,kind:ur,segmentReference:dr,profiles:gl,duration:Ct,bitrate:Tn,mime:xt,codecs:Zi,width:ll,height:yn,fps:hl,quality:cl})}}return{dynamic:zt,liveAvailabilityStartTime:Ji,duration:Ct,container:nl,representations:xe}},Ba=1e3,ad=["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=nt(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 Xo(Ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(i)&&(this.audioBufferManager=new Xo(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(Ba).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Ho(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=nt(this.manifestUrlString,d+1e3,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(V(...ad.map(o=>B(this.element,o))).pipe(Al(Ba),w(o=>this.element?_t(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=Ho(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=nt(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=nt(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(...ad.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&&Ma(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),Ma(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(Je(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(Je(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=nt(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,Ze(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())},Ze=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(nt(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:n===p.PLAYING&&(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)):this.seek(-this.liveOffset.getTotalOffset()));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(nt(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 Ze=d.parentElement;if((Ze==null?void 0:Ze.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=Ze.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},rt=(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=rt(o,n):a===_.DocType?t=rt(o,n):a===_.DocTypeReadVersion&&(i=rt(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=rt(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=rt(v,f):h===_.Duration?r=rt(v,f):h===_.SeekPosition&&d===_.Cues?u=rt(v,f):h===_.Tracks?fi(v,({tag:T,type:A,value:E})=>T===_.ProjectionType?(l=rt(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=rt(d,u));break;case _.CueTrackPositions:break;case _.CueClusterPosition:n&&(n.position=rt(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=it(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:it(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=it(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=it(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=it(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:it(e,0).byte.from,to:it(e,-1).byte.to};break}case Ye.TEMPLATE:{const d=it(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=Xe,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,Ze,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((Ze=Ai.getAttribute("r"))!==null&&Ze!==void 0?Ze:"",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=nt(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=nt(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=nt(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=nt(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
@@ -34,5 +34,5 @@ precision highp float;
34
34
  #define GLSLIFY 1
35
35
  #endif
36
36
  #define PI 3.14159265358979323846264
37
- varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Jy{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new zy(this.params.fov,this.params.orientation),this.cameraRotationManager=new Wy(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Qy,this.gl.VERTEX_SHADER),i=this.createShader(Ky,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Xu{constructor(e){this.subscription=new ae,this.videoState=new ce(he.STOPPED),this.elementSize$=new S(void 0),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.videoTracks$=new S([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new QS,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===W.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==he.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:n===p.PAUSED?(this.videoState.setState(he.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&D(this.params.desiredState.playbackState,p.READY);return;case he.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case he.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Jy(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new qy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:L.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(re(k),ge()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Rt(this.video,t.playbackRate,i.playbackRateState$,r)),a(Bs(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),D(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),D(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Ge.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((A,E)=>E.bitrate-A.bitrate),v=Array.from(h.video).sort((A,E)=>E.bitrate-A.bitrate),g=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const A of f){const E=ty(A);E&&this.audioTracks.push({track:E,representation:A})}for(const A of v){const E=ey(A);if(E){c.push({track:E,representation:A});const m=!this.params.tuning.isAudioDisabled&&iy(f,v,A);m&&this.audioRepresentations.set(A.id,m)}}this.videoTracks$.next(c);for(const A of g){const E=sy(A);E&&this.textTracks.push({track:E,representation:A})}this.params.output.availableVideoTracks$.next(c.map(({track:A})=>A)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:A})=>A)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:A})=>A));const T=this.selectVideoRepresentation();P(T),this.player.initRepresentations(T.id,(l=this.audioRepresentations.get(T.id))===null||l===void 0?void 0:l.id)}else d===Ge.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(V(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Ge.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Ae.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ae.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),w(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(w(({to:d})=>d===p.READY),ve());this.subscription.add(V(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(V(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks$.getValue().find(({track:{id:A}})=>A===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=_t(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),g=gi(this.videoTracks$.getValue().map(({track:A})=>A),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=o?g!=null?g:d:d!=null?d:g;return T&&((n=this.videoTracks$.getValue().find(({track:A})=>A===T))===null||n===void 0?void 0:n.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Dt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(he.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class Xy extends Xu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Zy extends Xu{constructor(e){super(e),this.liveOffset=new tr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Ne({interval:Cs(Ba),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===he.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ne({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===he.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const tt={};var se;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));const Pi=(s,e)=>new Hs(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class eT{constructor(e){this.subscription=new ae,this.videoState=new ce(se.INITIALIZING),this.textTracksManager=new dt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==se.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case se.STOPPED:break;case se.READY:case se.PLAYING:case se.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case se.STOPPED:this.prepare();break;case se.READY:case se.PLAYING:case se.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case se.PLAYING:break;case se.STOPPED:this.prepare();break;case se.READY:case se.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case se.PAUSED:break;case se.STOPPED:this.prepare();break;case se.READY:this.videoState.setState(se.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED);break;case se.PLAYING:this.pause();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.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);er(import("hls.js").then(r=>{e||(tt.Hls=r.default,tt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){P(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(se.STOPPED)}subscribe(){P(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=yt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(jt(this.video,e.isLooped,i)),this.subscription.add(gt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Rt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Pi(this.hls,tt.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),D(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),D(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),a(Pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((l,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:g,height:T}=c,A=(f=Qi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Vt({width:g,height:T});if(!A)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,m={id:v.toString(),quality:A,bitrate:c.bitrate/1e3,size:{width:g,height:T},fps:E};return this.trackLevels.set(v,{track:m,level:c}),l.push(m),l},[]))),t.availableVideoTracks$),a(Pi(this.hls,tt.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,g="internal";l.push({id:h,url:f,language:v,type:g})}e.internalTextTracks.startTransitionTo(l)}}),a(Pi(this.hls,tt.Events.LEVEL_LOADING).pipe(w(({url:d})=>Ie(d))),t.hostname$),this.subscription.add(Je(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(re(k)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Je(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(ie(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(w(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(se.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ue(this,void 0,void 0,function*(){this.videoState.startTransitionTo(se.PLAYING),(yield Dt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:t})))||(this.videoState.setState(se.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(se.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(se.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0)}}const nd="X-Playback-Duration";var od=s=>ue(void 0,void 0,void 0,function*(){var e;const t=yield Fi(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(nd)?parseInt(t.headers.get(nd),10):void 0});const tT=s=>{let e=null;if(s.QUALITY&&(e=Qi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Vt({width:t,height:i})}return e!=null?e:null},Zu=(s,e=s)=>ue(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Fi(s)).text()).split(`
38
- `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=li(c[1].split(",").map(b=>b.split("="))),v=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,g=tT(f);let T;f.BANDWIDTH&&(T=parseInt(f.BANDWIDTH,10)/1e3||void 0),!T&&f["AVERAGE-BANDWIDTH"]&&(T=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const A=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let E;if(f.RESOLUTION){const[b,$]=f.RESOLUTION.split("x").map(R=>parseInt(R,10));b&&$&&(E={width:b,height:$})}const m=new URL(n[++d],e).toString();g&&o.push({id:v,quality:g,url:m,bandwidth:T,size:E,fps:A})}if(h){const f=li(h[1].split(",").map(A=>A.split("=")).map(([A,E])=>[A,E.replace(/^"|"$/g,"")])),v=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),g=f.LANGUAGE,T=f.NAME;v&&g&&u.push({type:"internal",id:g,label:T,language:g,url:v,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}});var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class iT{constructor(e){var t;this.subscription=new ae,this.videoState=new ce(oe.STOPPED),this.textTracksManager=new dt,this.manifests$=new S([]),this.liveOffset=new tr,this.manifestStartTime$=new S(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===p.STOPPED){a!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(u||d){const h=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested){this.videoState.startTransitionTo(oe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case oe.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===p.PAUSED&&(D(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case oe.CHANGING_MANIFEST:break;default:return H(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:He.INVARIANT,url:this.params.source.url};Zu(nt(this.params.source.url),this.params.source.url).then(({qualityManifests:r})=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.maxSeekBackTime$=new S((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===W.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ne({startTime:this.manifestStartTime$.pipe(re(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(ie(e))return;const t=this.params.format===y.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,i=nt(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),od(i).then(r=>{var a;if(!ie(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(ie(n)||!isFinite(n))try{Fi(i).then(o=>o.text()).then(o=>{var u;const d=(u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||u===void 0?void 0:u[1];if(d){const l=new URL(d,i).toString();od(l).then(c=>{ie(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(le||(le={}));class sT{constructor(e){this.subscription=new ae,this.videoState=new ce(le.STOPPED),this.textTracksManager=new dt,this.manifests$=new S([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(le.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==p.PAUSED&&l.state===W.Requested&&this.seek(l.position),r){case le.READY:a===p.READY?D(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(le.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;case le.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:He.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),Zu(this.params.source.url).then(({qualityManifests:i,textTracks:r})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===le.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===W.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(V(B(o,"addtrack"),B(o,"removetrack"),B(o,"change"),De(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();ie(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(le.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var fe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(fe||(fe={}));class rT{constructor(e){this.subscription=new ae,this.videoState=new ce(fe.STOPPED),this.trackUrls={},this.textTracksManager=new dt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(fe.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==fe.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested&&this.seek(c.position),a){case fe.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(fe.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case fe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&k(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===fe.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();P(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];P(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ie(t))}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(fe.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(i=Object.values(this.trackUrls).find(d=>yd(d.track.quality,e)))===null||i===void 0?void 0:i.track,o=this.params.desiredState.videoTrack.getState(),u=(r=this.trackUrls[o!=null?o:"0"])===null||r===void 0?void 0:r.track;n&&u&&fa(u.quality,n.quality)&&(a=n)}else if(!e){const n=Object.values(this.trackUrls).map(o=>o.track);a=gi(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.startTransitionTo(a.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const dd=["stun:videostun.mycdn.me:80"],aT=1e3,nT=3,ea=()=>null;class oT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ea,this.externalStopCallback=ea,this.externalErrorCallback=ea,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ue(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:dd}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ue(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ue(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}onPeerConnectionStream(e){return ue(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return ue(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),aT)}normalizeOptions(e={}){const t={stunServerList:dd,maxRetryNumber:nT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));class dT{constructor(e){this.videoState=new ce(de.STOPPED),this.maxSeekBackTime$=new S(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case de.READY:i===p.PAUSED?(this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container),this.liveStreamClient=new oT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=yt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===de.READY&&this.videoState.setState(de.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(gt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case de.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case de.READY:break;case de.PAUSED:t.playbackState.setState(p.PAUSED);break;case de.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:He.INVARIANT}),this.video.srcObject=e,D(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(de.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(de.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}))}prepare(){this.liveStreamClient.connect()}}class ud{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ta,ia,sa,ra,aa,na,ys,oa,Ts,da,Es,ua,$s,la,As,ca,_s,ha;const el=Fa().device===_l.Android,wt=document.createElement("video"),uT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lT='video/mp4; codecs="hev1.1.6.L93.B0"',tl='video/webm; codecs="vp09.00.10.08"',il='video/webm; codecs="av01.0.00M.08"',cT='audio/mp4; codecs="mp4a.40.2"',hT='audio/webm; codecs="opus"',Qe={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((ia=(ta=window.SourceBuffer)===null||ta===void 0?void 0:ta.prototype)===null||ia===void 0)&&ia.appendBuffer)),hls:!!(!((sa=wt.canPlayType)===null||sa===void 0)&&sa.call(wt,"application/x-mpegurl")||!((ra=wt.canPlayType)===null||ra===void 0)&&ra.call(wt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Le={mp4:!!(!((aa=wt.canPlayType)===null||aa===void 0)&&aa.call(wt,"video/mp4")),webm:!!(!((na=wt.canPlayType)===null||na===void 0)&&na.call(wt,"video/webm")),cmaf:!0},at={h264:!!(!((oa=(ys=window.MediaSource)===null||ys===void 0?void 0:ys.isTypeSupported)===null||oa===void 0)&&oa.call(ys,uT)),h265:!!(!((da=(Ts=window.MediaSource)===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||da===void 0)&&da.call(Ts,lT)),vp9:!!(!((ua=(Es=window.MediaSource)===null||Es===void 0?void 0:Es.isTypeSupported)===null||ua===void 0)&&ua.call(Es,tl)),av1:!!(!((la=($s=window.MediaSource)===null||$s===void 0?void 0:$s.isTypeSupported)===null||la===void 0)&&la.call($s,il)),aac:!!(!((ca=(As=window.MediaSource)===null||As===void 0?void 0:As.isTypeSupported)===null||ca===void 0)&&ca.call(As,cT)),opus:!!(!((ha=(_s=window.MediaSource)===null||_s===void 0?void 0:_s.isTypeSupported)===null||ha===void 0)&&ha.call(_s,hT))},ii=(at.h264||at.h265)&&at.aac;var At;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(At||(At={}));var ft;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(ft||(ft={}));let Bt;const fT=()=>ue(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:il})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:tl})}))]);Bt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{fT()}catch(s){console.error(s)}const Ui=Qe.hls&&Le.mp4,pT=()=>Object.keys(at).filter(s=>at[s]),vT=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Qe.mse&&Le.mp4&&ii;case y.DASH_SEP:return Qe.mse&&Le.mp4&&ii;case y.DASH_WEBM:return Qe.mse&&Le.webm&&at.vp9&&at.opus;case y.DASH_WEBM_AV1:return Qe.mse&&Le.webm&&at.av1&&at.opus;case y.DASH_LIVE:return Qe.mse&&Le.mp4&&ii;case y.DASH_LIVE_CMAF:return Qe.mse&&Le.mp4&&ii&&Le.cmaf;case y.DASH_ONDEMAND:return Qe.mse&&Le.mp4&&ii;case y.HLS:case y.HLS_ONDEMAND:return Ui||e&&Qe.mse&&Le.mp4&&ii;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Ui;case y.MPEG:return Le.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Qe.webrtc&&Qe.ws&&at.h264&&(Le.mp4||Le.webm);default:return H(t)}}),Ri=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case At.VP9:return[e,t];case At.AV1:return[t,e];case At.NONE:return[];case At.SMOOTH:return Bt?Bt[t].smooth?[t,e]:Bt[e].smooth?[e,t]:[t,e]:[e,t];case At.POWER_EFFICIENT:return Bt?Bt[t].powerEfficient?[t,e]:Bt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(s)}return[e,t]},mT=({webmCodec:s,androidPreferredFormat:e})=>{if(el)switch(e){case ft.MPEG:return[y.MPEG,...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case ft.HLS:return[y.HLS,y.HLS_ONDEMAND,...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case ft.DASH:return[...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Ui?[...Ri(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},gT=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(el)switch(s){case ft.DASH:{o=a;break}case ft.HLS:case ft.MPEG:{o=n;break}}else Ui?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},ld=s=>s?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var ST=s=>new Hs(e=>{const t=new ae,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new x;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const bT={cacheDuration:12e4},yT={chunkDuration:5e3,maxParallelRequests:5};class TT{constructor(e){this.current$=new S({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new S(0),duration$:new S(1/0),volume$:new S({muted:!1,volume:1}),currentVideoTrack$:new S(void 0),availableVideoTracks$:new S([]),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),autoVideoTrackLimitingAvailable$:new S(!1),autoVideoTrackLimits$:new S(void 0),currentBuffer$:new S(void 0),isBuffering$:new S(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new S(void 0),isLowLatency$:new S(!1),canChangePlaybackSpeed$:new S(!0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),inPiP$:new S(!1),inFullscreen$:new S(!1),element$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=vT([...gT(this.params.tuning),...mT(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>k(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new ud(a);const n=[...ld(!0),...ld(!1)];this.chromecastFormatsIterator=new ud(n.filter(o=>k(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(ie(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==W.None;if(this.params.desiredState.seekState.setState({state:W.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case we.SCREEN:return this.createScreenProvider(t);case we.CHROMECAST:return this.createChromecastProvider(t);default:return H(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new gb(Object.assign(Object.assign({},n),{source:o,config:bT}))}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new jo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new Xy(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new jo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new Zy(Object.assign(Object.assign({},n),{source:o}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ui||!this.params.tuning.useHlsJs?new sT(Object.assign(Object.assign({},n),{source:o})):new eT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new iT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new rT(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new hb(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},yT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new dT({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new $S({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?we.CHROMECAST:we.SCREEN}chooseFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case we.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.next();case we.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case we.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case we.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:i(e.url)})}return li(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,i=0;return e.add(V(this.providerOutput.error$,ST({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:L.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(re(({to:a})=>a===p.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===we.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(we.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===L.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:we.SCREEN)}})),e}}const Na=(s,e,t)=>t*e+(1-t)*s,sl=(s,e)=>s.reduce((t,i)=>t+i,0)/e,ET=(s,e,t,i)=>{let r=0,a=t;const n=sl(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class rl{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new S(e.initial),this.debounced$=new S(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${i}`),this.smoothedSeries$=new st(`smoothed_${i}`),this.reportedSeries$=new st(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(ie(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class $T extends rl{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Na(this.slow,e,this.params.emaAlphaSlow),this.fast=Na(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class AT extends rl{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=sl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Na(this.emaSmoothed,e,this.params.emaAlpha);const i=ET(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class cd{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $T({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new AT({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const _T=5e3,hd="one_video_throughput",fd="one_video_rtt",pt=window.navigator.connection,pd=()=>{const s=pt==null?void 0:pt.downlink;if(k(s)&&s!==10)return s*1e3},vd=()=>{const s=pt==null?void 0:pt.rtt;if(k(s)&&s!==3e3)return s},md=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Li{constructor(e){var t,i;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Li.load(hd)||(e.useBrowserEstimation?pd():void 0)||_T,a=(i=(t=Li.load(fd))!==null&&t!==void 0?t:e.useBrowserEstimation?vd():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new S(r),this.rtt$=new S(a),this.rttAdjustedThroughput$=new S(md(r,a,e.rttPenaltyRequestSize)),this.throughput=cd.getSmoothedValue(r,-1,e),this.rtt=cd.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=pd();u&&this.throughput.next(u);const d=vd();k(d)&&this.rtt.next(d)};pt&&"onchange"in pt&&this.subscription.add(B(pt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{pr.set(hd,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{pr.set(fd,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ne({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>md(n,o,e.rttPenaltyRequestSize)),re(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=me();const r=new ae;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(B(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=me()}));break;case 1:case 0:r.add(B(e,"loadstart").subscribe(()=>{t=0,i=me()}));break}r.add(B(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=me(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=me();let a=0,n=me();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:l})=>ue(this,void 0,void 0,function*(){d?(this.addRawSpeed(i,me()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&me()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,me()-n,this.concurrentDownloads.size),a=0,n=me()),yield t==null?void 0:t.read().then(u,o))});this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(Li.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=pr.get(e);if(k(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const gd={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:He.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:At.VP9,androidPreferredFormat:ft.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},wT=s=>{var e;return Object.assign(Object.assign({},wl(s,gd)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...gd.configName]})};var Sd=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(w(({to:t})=>{var i;return t.state===W.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),re(k)),e.pipe(re(()=>s.getState().state===W.None))),kT=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};class xT{constructor(e={configName:[]}){if(this.subscription=new ae,this.logger=new kl,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ce(p.STOPPED),seekState:new ce({state:W.None}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({}),cameraOrientation:new ce({x:0,y:0})},this.info={playbackState$:new S(p.STOPPED),position$:new S(0),duration$:new S(1/0),muted$:new S(!1),volume$:new S(1),availableQualities$:new S([]),availableQualitiesFps$:new S({}),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),currentQuality$:new S(void 0),isAutoQualityEnabled$:new S(!0),autoQualityLimitingAvailable$:new S(!1),autoQualityLimits$:new S({}),currentPlaybackRate$:new S(1),currentBuffer$:new S({start:0,end:0}),isBuffering$:new S(!0),isStalled$:new S(!1),isEnded$:new S(!1),isLooped$:new S(!1),isLive$:new S(void 0),canChangePlaybackSpeed$:new S(void 0),atLiveEdge$:new S(void 0),atLiveDurationEdge$:new S(void 0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),currentFormat$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),throughputEstimation$:new S(void 0),rttEstimation$:new S(void 0),videoBitrate$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),surface$:new S($t.NONE),chromecastState$:new S($e.NOT_AVAILABLE),chromecastDeviceName$:new S(void 0),intrinsicVideoSize$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new S(void 0),tuningConfigName$:new S([]),enableDebugTelemetry$:new S(!1),dumpTelemetry:qS},this.initLogs(),this.tuning=wT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Il({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=kT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new TT({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?B(document,"visibilitychange").pipe(ge()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:W.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===$e.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===$e.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t,i,r;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(re(a=>a.length>0),ge()).subscribe(a=>{a.find(n=>n.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((r=this.providerContainer)===null||r===void 0)&&r.providerOutput.availableTextTracks$.getValue().find(a=>a.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(ie(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===W.None?void 0:t.position;return k(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(V(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e===p.STOPPED),ge()).subscribe(()=>{this.initedAt=me(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===W.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:W.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===W.Applying&&(this.desiredState.seekState.setState({state:W.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>Oi(o)?1:Oi(u)?-1:Ii(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(w(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ne({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),Is(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Ne({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&Math.abs(u)-Math.abs(o)<this.tuning.live.activeLiveDelay),ve(),Is(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),ve()).subscribe(this.info.volume$)).add(Sd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(ui(!0)),e.providerOutput.seekedEvent$.pipe(ui(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(w(n=>({id:n?`No${n}`:"NoProviders",category:L.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),w(n=>n!=null?n:me()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),w(()=>me()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),w(()=>me()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new S(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new S(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(V(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(V(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===$e.CONNECTED?l=$t.SECOND_SCREEN:u?n?l=$t.PIP:o?l=$t.FULLSCREEN:l=$t.INLINE:l=$t.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ae;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=gi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(V(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),jS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>YS(i)),this.providerContainer.current$.subscribe(({type:i})=>ms("provider",i)),t.duration$.subscribe(i=>ms("duration",i)),t.availableVideoTracks$.pipe(re(i=>!!i.length),ge()).subscribe(i=>ms("tracks",i)),this.events.fatalError$.subscribe(new st("fatalError")),this.events.managedError$.subscribe(new st("managedError")),t.position$.subscribe(new st("position")),t.currentVideoTrack$.pipe(w(i=>i==null?void 0:i.quality)).subscribe(new st("quality")),this.info.currentBuffer$.subscribe(new st("buffer")),t.isBuffering$.subscribe(new st("isBuffering"))].forEach(i=>this.subscription.add(i)),ms("codecs",pT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(r)})})});this.subscription.add(V(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const LT=`@vkontakte/videoplayer-core@${Rl}`;export{$e as ChromecastState,Mi as HttpConnectionType,BT as Observable,p as PlaybackState,xT as Player,LT as SDK_VERSION,NT as Subject,FT as Subscription,$t as Surface,Rl as VERSION,UT as ValueSubject,y as VideoFormat,VT as VideoQuality};
37
+ varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Jy{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new zy(this.params.fov,this.params.orientation),this.cameraRotationManager=new Wy(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Qy,this.gl.VERTEX_SHADER),i=this.createShader(Ky,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Zu{constructor(e){this.subscription=new ae,this.videoState=new ce(he.STOPPED),this.elementSize$=new S(void 0),this.textTracksManager=new dt,this.droppedFramesManager=new ir,this.videoTracks$=new S([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new QS,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===W.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==he.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:n===p.PAUSED?(this.videoState.setState(he.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&D(this.params.desiredState.playbackState,p.READY);return;case he.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case he.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Jy(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new qy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:L.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(re(k),ge()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Dt(this.video,t.playbackRate,i.playbackRateState$,r)),a(Bs(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),D(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),D(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Ge.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((A,E)=>E.bitrate-A.bitrate),v=Array.from(h.video).sort((A,E)=>E.bitrate-A.bitrate),g=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const A of f){const E=ty(A);E&&this.audioTracks.push({track:E,representation:A})}for(const A of v){const E=ey(A);if(E){c.push({track:E,representation:A});const m=!this.params.tuning.isAudioDisabled&&iy(f,v,A);m&&this.audioRepresentations.set(A.id,m)}}this.videoTracks$.next(c);for(const A of g){const E=sy(A);E&&this.textTracks.push({track:E,representation:A})}this.params.output.availableVideoTracks$.next(c.map(({track:A})=>A)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:A})=>A)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:A})=>A));const T=this.selectVideoRepresentation();P(T),this.player.initRepresentations(T.id,(l=this.audioRepresentations.get(T.id))===null||l===void 0?void 0:l.id)}else d===Ge.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(V(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Ge.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Ae.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ae.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),w(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(w(({to:d})=>d===p.READY),ve());this.subscription.add(V(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(V(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks$.getValue().find(({track:{id:A}})=>A===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=wt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),g=gi(this.videoTracks$.getValue().map(({track:A})=>A),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=o?g!=null?g:d:d!=null?d:g;return T&&((n=this.videoTracks$.getValue().find(({track:A})=>A===T))===null||n===void 0?void 0:n.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){It(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(he.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class Xy extends Zu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Zy extends Zu{constructor(e){super(e),this.liveOffset=new tr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Ne({interval:Cs(Na),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===he.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ne({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===he.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const tt={};var se;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));const Pi=(s,e)=>new Hs(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class eT{constructor(e){this.subscription=new ae,this.videoState=new ce(se.INITIALIZING),this.textTracksManager=new dt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==se.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case se.STOPPED:break;case se.READY:case se.PLAYING:case se.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case se.STOPPED:this.prepare();break;case se.READY:case se.PLAYING:case se.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case se.PLAYING:break;case se.STOPPED:this.prepare();break;case se.READY:case se.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case se.PAUSED:break;case se.STOPPED:this.prepare();break;case se.READY:this.videoState.setState(se.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED);break;case se.PLAYING:this.pause();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.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);er(import("hls.js").then(r=>{e||(tt.Hls=r.default,tt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){P(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(se.STOPPED)}subscribe(){P(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=yt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(jt(this.video,e.isLooped,i)),this.subscription.add(gt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Pi(this.hls,tt.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),D(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),D(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),a(Pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((l,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:g,height:T}=c,A=(f=Qi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Vt({width:g,height:T});if(!A)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,m={id:v.toString(),quality:A,bitrate:c.bitrate/1e3,size:{width:g,height:T},fps:E};return this.trackLevels.set(v,{track:m,level:c}),l.push(m),l},[]))),t.availableVideoTracks$),a(Pi(this.hls,tt.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,g="internal";l.push({id:h,url:f,language:v,type:g})}e.internalTextTracks.startTransitionTo(l)}}),a(Pi(this.hls,tt.Events.LEVEL_LOADING).pipe(w(({url:d})=>Ie(d))),t.hostname$),this.subscription.add(Je(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(re(k)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Je(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(ie(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(w(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(se.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ue(this,void 0,void 0,function*(){this.videoState.startTransitionTo(se.PLAYING),(yield It(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:t})))||(this.videoState.setState(se.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(se.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(se.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0)}}const od="X-Playback-Duration";var dd=s=>ue(void 0,void 0,void 0,function*(){var e;const t=yield Fi(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(od)?parseInt(t.headers.get(od),10):void 0});const tT=s=>{let e=null;if(s.QUALITY&&(e=Qi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Vt({width:t,height:i})}return e!=null?e:null},el=(s,e=s)=>ue(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Fi(s)).text()).split(`
38
+ `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=li(c[1].split(",").map(b=>b.split("="))),v=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,g=tT(f);let T;f.BANDWIDTH&&(T=parseInt(f.BANDWIDTH,10)/1e3||void 0),!T&&f["AVERAGE-BANDWIDTH"]&&(T=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const A=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let E;if(f.RESOLUTION){const[b,$]=f.RESOLUTION.split("x").map(R=>parseInt(R,10));b&&$&&(E={width:b,height:$})}const m=new URL(n[++d],e).toString();g&&o.push({id:v,quality:g,url:m,bandwidth:T,size:E,fps:A})}if(h){const f=li(h[1].split(",").map(A=>A.split("=")).map(([A,E])=>[A,E.replace(/^"|"$/g,"")])),v=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),g=f.LANGUAGE,T=f.NAME;v&&g&&u.push({type:"internal",id:g,label:T,language:g,url:v,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}});var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class iT{constructor(e){var t;this.subscription=new ae,this.videoState=new ce(oe.STOPPED),this.textTracksManager=new dt,this.manifests$=new S([]),this.liveOffset=new tr,this.manifestStartTime$=new S(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===p.STOPPED){a!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(u||d){const h=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested){this.videoState.startTransitionTo(oe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case oe.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===p.PAUSED&&(D(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case oe.CHANGING_MANIFEST:break;default:return H(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:He.INVARIANT,url:this.params.source.url};el(nt(this.params.source.url),this.params.source.url).then(({qualityManifests:r})=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.maxSeekBackTime$=new S((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===W.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ne({startTime:this.manifestStartTime$.pipe(re(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(ie(e))return;const t=this.params.format===y.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,i=nt(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),dd(i).then(r=>{var a;if(!ie(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(ie(n)||!isFinite(n))try{Fi(i).then(o=>o.text()).then(o=>{var u;const d=(u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||u===void 0?void 0:u[1];if(d){const l=new URL(d,i).toString();dd(l).then(c=>{ie(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(le||(le={}));class sT{constructor(e){this.subscription=new ae,this.videoState=new ce(le.STOPPED),this.textTracksManager=new dt,this.manifests$=new S([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(le.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==p.PAUSED&&l.state===W.Requested&&this.seek(l.position),r){case le.READY:a===p.READY?D(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(le.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;case le.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:He.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),el(this.params.source.url).then(({qualityManifests:i,textTracks:r})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ie(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===le.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===W.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(V(B(o,"addtrack"),B(o,"removetrack"),B(o,"change"),De(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();ie(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(le.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var fe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(fe||(fe={}));class rT{constructor(e){this.subscription=new ae,this.videoState=new ce(fe.STOPPED),this.trackUrls={},this.textTracksManager=new dt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(fe.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==fe.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===W.None&&this.params.desiredState.seekState.setState({state:W.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested&&this.seek(c.position),a){case fe.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(fe.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case fe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),D(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),D(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&k(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===fe.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();P(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];P(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ie(t))}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(fe.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(i=Object.values(this.trackUrls).find(d=>Td(d.track.quality,e)))===null||i===void 0?void 0:i.track,o=this.params.desiredState.videoTrack.getState(),u=(r=this.trackUrls[o!=null?o:"0"])===null||r===void 0?void 0:r.track;n&&u&&pa(u.quality,n.quality)&&(a=n)}else if(!e){const n=Object.values(this.trackUrls).map(o=>o.track);a=gi(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.startTransitionTo(a.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const ud=["stun:videostun.mycdn.me:80"],aT=1e3,nT=3,ta=()=>null;class oT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ta,this.externalStopCallback=ta,this.externalErrorCallback=ta,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ue(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:ud}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ue(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ue(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}onPeerConnectionStream(e){return ue(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return ue(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),aT)}normalizeOptions(e={}){const t={stunServerList:ud,maxRetryNumber:nT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));class dT{constructor(e){this.videoState=new ce(de.STOPPED),this.maxSeekBackTime$=new S(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case de.READY:i===p.PAUSED?(this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container),this.liveStreamClient=new oT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=yt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===de.READY&&this.videoState.setState(de.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(gt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case de.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case de.READY:break;case de.PAUSED:t.playbackState.setState(p.PAUSED);break;case de.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(je(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:He.INVARIANT}),this.video.srcObject=e,D(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(de.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){It(this.video).then(e=>{e||(this.videoState.setState(de.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}))}prepare(){this.liveStreamClient.connect()}}class ld{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ia,sa,ra,aa,na,oa,ys,da,Ts,ua,Es,la,$s,ca,As,ha,_s,fa;const tl=Ua().device===_l.Android,kt=document.createElement("video"),uT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lT='video/mp4; codecs="hev1.1.6.L93.B0"',il='video/webm; codecs="vp09.00.10.08"',sl='video/webm; codecs="av01.0.00M.08"',cT='audio/mp4; codecs="mp4a.40.2"',hT='audio/webm; codecs="opus"',Qe={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((sa=(ia=window.SourceBuffer)===null||ia===void 0?void 0:ia.prototype)===null||sa===void 0)&&sa.appendBuffer)),hls:!!(!((ra=kt.canPlayType)===null||ra===void 0)&&ra.call(kt,"application/x-mpegurl")||!((aa=kt.canPlayType)===null||aa===void 0)&&aa.call(kt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Le={mp4:!!(!((na=kt.canPlayType)===null||na===void 0)&&na.call(kt,"video/mp4")),webm:!!(!((oa=kt.canPlayType)===null||oa===void 0)&&oa.call(kt,"video/webm")),cmaf:!0},at={h264:!!(!((da=(ys=window.MediaSource)===null||ys===void 0?void 0:ys.isTypeSupported)===null||da===void 0)&&da.call(ys,uT)),h265:!!(!((ua=(Ts=window.MediaSource)===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||ua===void 0)&&ua.call(Ts,lT)),vp9:!!(!((la=(Es=window.MediaSource)===null||Es===void 0?void 0:Es.isTypeSupported)===null||la===void 0)&&la.call(Es,il)),av1:!!(!((ca=($s=window.MediaSource)===null||$s===void 0?void 0:$s.isTypeSupported)===null||ca===void 0)&&ca.call($s,sl)),aac:!!(!((ha=(As=window.MediaSource)===null||As===void 0?void 0:As.isTypeSupported)===null||ha===void 0)&&ha.call(As,cT)),opus:!!(!((fa=(_s=window.MediaSource)===null||_s===void 0?void 0:_s.isTypeSupported)===null||fa===void 0)&&fa.call(_s,hT))},ii=(at.h264||at.h265)&&at.aac;var _t;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(_t||(_t={}));var ft;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(ft||(ft={}));let Bt;const fT=()=>ue(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:sl})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:il})}))]);Bt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{fT()}catch(s){console.error(s)}const Ui=Qe.hls&&Le.mp4,pT=()=>Object.keys(at).filter(s=>at[s]),vT=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Qe.mse&&Le.mp4&&ii;case y.DASH_SEP:return Qe.mse&&Le.mp4&&ii;case y.DASH_WEBM:return Qe.mse&&Le.webm&&at.vp9&&at.opus;case y.DASH_WEBM_AV1:return Qe.mse&&Le.webm&&at.av1&&at.opus;case y.DASH_LIVE:return Qe.mse&&Le.mp4&&ii;case y.DASH_LIVE_CMAF:return Qe.mse&&Le.mp4&&ii&&Le.cmaf;case y.DASH_ONDEMAND:return Qe.mse&&Le.mp4&&ii;case y.HLS:case y.HLS_ONDEMAND:return Ui||e&&Qe.mse&&Le.mp4&&ii;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Ui;case y.MPEG:return Le.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Qe.webrtc&&Qe.ws&&at.h264&&(Le.mp4||Le.webm);default:return H(t)}}),Ri=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case _t.VP9:return[e,t];case _t.AV1:return[t,e];case _t.NONE:return[];case _t.SMOOTH:return Bt?Bt[t].smooth?[t,e]:Bt[e].smooth?[e,t]:[t,e]:[e,t];case _t.POWER_EFFICIENT:return Bt?Bt[t].powerEfficient?[t,e]:Bt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(s)}return[e,t]},mT=({webmCodec:s,androidPreferredFormat:e})=>{if(tl)switch(e){case ft.MPEG:return[y.MPEG,...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case ft.HLS:return[y.HLS,y.HLS_ONDEMAND,...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case ft.DASH:return[...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Ui?[...Ri(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...Ri(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},gT=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(tl)switch(s){case ft.DASH:{o=a;break}case ft.HLS:case ft.MPEG:{o=n;break}}else Ui?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},cd=s=>s?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var ST=s=>new Hs(e=>{const t=new ae,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new x;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const bT={cacheDuration:12e4},yT={chunkDuration:5e3,maxParallelRequests:5};class TT{constructor(e){this.current$=new S({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new S(0),duration$:new S(1/0),volume$:new S({muted:!1,volume:1}),currentVideoTrack$:new S(void 0),availableVideoTracks$:new S([]),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),autoVideoTrackLimitingAvailable$:new S(!1),autoVideoTrackLimits$:new S(void 0),currentBuffer$:new S(void 0),isBuffering$:new S(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new S(void 0),isLowLatency$:new S(!1),canChangePlaybackSpeed$:new S(!0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),inPiP$:new S(!1),inFullscreen$:new S(!1),element$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=vT([...gT(this.params.tuning),...mT(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>k(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new ld(a);const n=[...cd(!0),...cd(!1)];this.chromecastFormatsIterator=new ld(n.filter(o=>k(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(ie(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==W.None;if(this.params.desiredState.seekState.setState({state:W.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case we.SCREEN:return this.createScreenProvider(t);case we.CHROMECAST:return this.createChromecastProvider(t);default:return H(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new gb(Object.assign(Object.assign({},n),{source:o,config:bT}))}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new qo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new Xy(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new qo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new Zy(Object.assign(Object.assign({},n),{source:o}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ui||!this.params.tuning.useHlsJs?new sT(Object.assign(Object.assign({},n),{source:o})):new eT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new iT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new rT(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new hb(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},yT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new dT({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new $S({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?we.CHROMECAST:we.SCREEN}chooseFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case we.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.next();case we.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case we.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case we.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:i(e.url)})}return li(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,i=0;return e.add(V(this.providerOutput.error$,ST({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:L.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(re(({to:a})=>a===p.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===we.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(we.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===L.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:we.SCREEN)}})),e}}const Fa=(s,e,t)=>t*e+(1-t)*s,rl=(s,e)=>s.reduce((t,i)=>t+i,0)/e,ET=(s,e,t,i)=>{let r=0,a=t;const n=rl(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class al{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new S(e.initial),this.debounced$=new S(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${i}`),this.smoothedSeries$=new st(`smoothed_${i}`),this.reportedSeries$=new st(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(ie(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class $T extends al{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Fa(this.slow,e,this.params.emaAlphaSlow),this.fast=Fa(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class AT extends al{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=rl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Fa(this.emaSmoothed,e,this.params.emaAlpha);const i=ET(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class hd{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $T({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new AT({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const _T=5e3,fd="one_video_throughput",pd="one_video_rtt",pt=window.navigator.connection,vd=()=>{const s=pt==null?void 0:pt.downlink;if(k(s)&&s!==10)return s*1e3},md=()=>{const s=pt==null?void 0:pt.rtt;if(k(s)&&s!==3e3)return s},gd=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Li{constructor(e){var t,i;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Li.load(fd)||(e.useBrowserEstimation?vd():void 0)||_T,a=(i=(t=Li.load(pd))!==null&&t!==void 0?t:e.useBrowserEstimation?md():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new S(r),this.rtt$=new S(a),this.rttAdjustedThroughput$=new S(gd(r,a,e.rttPenaltyRequestSize)),this.throughput=hd.getSmoothedValue(r,-1,e),this.rtt=hd.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vd();u&&this.throughput.next(u);const d=md();k(d)&&this.rtt.next(d)};pt&&"onchange"in pt&&this.subscription.add(B(pt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vr.set(fd,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vr.set(pd,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ne({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>gd(n,o,e.rttPenaltyRequestSize)),re(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=me();const r=new ae;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(B(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=me()}));break;case 1:case 0:r.add(B(e,"loadstart").subscribe(()=>{t=0,i=me()}));break}r.add(B(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=me(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=me();let a=0,n=me();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:l})=>ue(this,void 0,void 0,function*(){d?(this.addRawSpeed(i,me()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&me()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,me()-n,this.concurrentDownloads.size),a=0,n=me()),yield t==null?void 0:t.read().then(u,o))});this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(Li.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=vr.get(e);if(k(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Sd={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:He.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:_t.VP9,androidPreferredFormat:ft.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},wT=s=>{var e;return Object.assign(Object.assign({},wl(s,Sd)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Sd.configName]})};var bd=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(w(({to:t})=>{var i;return t.state===W.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),re(k)),e.pipe(re(()=>s.getState().state===W.None))),kT=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};class xT{constructor(e={configName:[]}){if(this.subscription=new ae,this.logger=new kl,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ce(p.STOPPED),seekState:new ce({state:W.None}),volume:new ce({volume:1,muted:!1}),videoTrack:new ce(void 0),autoVideoTrackSwitching:new ce(!0),autoVideoTrackLimits:new ce({}),isLooped:new ce(!1),playbackRate:new ce(1),externalTextTracks:new ce([]),internalTextTracks:new ce([]),currentTextTrack:new ce(void 0),textTrackCuesSettings:new ce({}),cameraOrientation:new ce({x:0,y:0})},this.info={playbackState$:new S(p.STOPPED),position$:new S(0),duration$:new S(1/0),muted$:new S(!1),volume$:new S(1),availableQualities$:new S([]),availableQualitiesFps$:new S({}),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),currentQuality$:new S(void 0),isAutoQualityEnabled$:new S(!0),autoQualityLimitingAvailable$:new S(!1),autoQualityLimits$:new S({}),currentPlaybackRate$:new S(1),currentBuffer$:new S({start:0,end:0}),isBuffering$:new S(!0),isStalled$:new S(!1),isEnded$:new S(!1),isLooped$:new S(!1),isLive$:new S(void 0),canChangePlaybackSpeed$:new S(void 0),atLiveEdge$:new S(void 0),atLiveDurationEdge$:new S(void 0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),currentFormat$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),throughputEstimation$:new S(void 0),rttEstimation$:new S(void 0),videoBitrate$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),surface$:new S(At.NONE),chromecastState$:new S($e.NOT_AVAILABLE),chromecastDeviceName$:new S(void 0),intrinsicVideoSize$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new S(void 0),tuningConfigName$:new S([]),enableDebugTelemetry$:new S(!1),dumpTelemetry:qS},this.initLogs(),this.tuning=wT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Il({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=kT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new TT({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?B(document,"visibilitychange").pipe(ge()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:W.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===$e.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===$e.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t,i,r;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(re(a=>a.length>0),ge()).subscribe(a=>{a.find(n=>n.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((r=this.providerContainer)===null||r===void 0)&&r.providerOutput.availableTextTracks$.getValue().find(a=>a.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(ie(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===W.None?void 0:t.position;return k(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(V(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e===p.STOPPED),ge()).subscribe(()=>{this.initedAt=me(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===W.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:W.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===W.Applying&&(this.desiredState.seekState.setState({state:W.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>Oi(o)?1:Oi(u)?-1:Ii(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(w(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ne({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),Is(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Ne({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&Math.abs(u)-Math.abs(o)<this.tuning.live.activeLiveDelay),ve(),Is(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),ve()).subscribe(this.info.volume$)).add(bd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(ui(!0)),e.providerOutput.seekedEvent$.pipe(ui(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(w(n=>({id:n?`No${n}`:"NoProviders",category:L.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),w(n=>n!=null?n:me()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),w(()=>me()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),w(()=>me()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new S(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new S(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(V(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(V(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===$e.CONNECTED?l=At.SECOND_SCREEN:u?n?l=At.PIP:o?l=At.FULLSCREEN:l=At.INLINE:l=At.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ae;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=gi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(V(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),jS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>YS(i)),this.providerContainer.current$.subscribe(({type:i})=>ms("provider",i)),t.duration$.subscribe(i=>ms("duration",i)),t.availableVideoTracks$.pipe(re(i=>!!i.length),ge()).subscribe(i=>ms("tracks",i)),this.events.fatalError$.subscribe(new st("fatalError")),this.events.managedError$.subscribe(new st("managedError")),t.position$.subscribe(new st("position")),t.currentVideoTrack$.pipe(w(i=>i==null?void 0:i.quality)).subscribe(new st("quality")),this.info.currentBuffer$.subscribe(new st("buffer")),t.isBuffering$.subscribe(new st("isBuffering"))].forEach(i=>this.subscription.add(i)),ms("codecs",pT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(r)})})});this.subscription.add(V(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const LT=`@vkontakte/videoplayer-core@${Rl}`;export{$e as ChromecastState,Mi as HttpConnectionType,BT as Observable,p as PlaybackState,xT as Player,LT as SDK_VERSION,NT as Subject,FT as Subscription,At as Surface,Rl as VERSION,UT as ValueSubject,y as VideoFormat,VT as VideoQuality};