@vkontakte/videoplayer-core 2.0.92-beta.1 → 2.0.92-dev.1c5a344.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +18 -18
- package/es2015.esm.js +16 -16
- package/es2018.cjs.js +16 -16
- package/es2018.esm.js +16 -16
- package/esnext.cjs.js +16 -16
- package/esnext.esm.js +16 -16
- package/evergreen.esm.js +15 -15
- package/index.d.ts +23 -0
- package/package.json +2 -2
package/es2015.esm.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.92-
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.92-dev.1c5a344.0
|
|
3
|
+
* Sun, 12 Nov 2023 20:32:18 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-92/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as S,Subject as x,Subscription as ae,isNonNullable as k,ErrorCategory as L,isNullable as se,fromEvent as U,assertNever as V,merge as G,tap as Is,map as w,observableFrom as Ne,filterChanged as ve,assertNonNullable as P,debounce as Ye,getHighestQuality as Tl,timeout as El,getCurrentBrowser as Fa,CurrentClientBrowser as bd,combine as Be,once as ge,mapTo as ui,filter as re,now as me,videoSizeToQuality as Vt,isInvariantQuality as xi,isHigher as _s,isLower as ws,isHigherOrEqual as fa,isLowerOrEqual as yd,Observable as Hs,interval as Cs,VideoQuality as Qe,videoQualityToHeight as $l,abortable as Le,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-beta.1";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var we;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(we||(we={}));var $e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})($e||($e={}));var Li;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(Li||(Li={}));var W;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(W||(W={}));var $t;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})($t||($t={}));function ue(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function Oe(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(v,g){a.push([h,f,v,g])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(v){c(a[0][3],v)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(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=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class 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 s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=k((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||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 s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();se(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();se(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(U(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(r.sessionState)}})).add(G(U(s,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)),Ne([s.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=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(se(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,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Cl=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return $e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return $e.AVAILABLE;case cast.framework.CastState.CONNECTING:return $e.CONNECTING;case cast.framework.CastState.CONNECTED:return $e.CONNECTED;default:return V(i)}};var vr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Gs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var je=function(i){try{return!!i()}catch(e){return!0}},xl=je,Ys=!xl(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Td=Ys,Ed=Function.prototype,pa=Ed.call,Ll=Td&&Ed.bind.bind(pa,pa),qe=Td?Ll:function(i){return function(){return pa.apply(i,arguments)}},$d=qe,Ol=$d({}.toString),Ml=$d("".slice),Fi=function(i){return Ml(Ol(i),8,-1)},Bl=qe,Nl=je,Fl=Fi,mr=Object,Ul=Bl("".split),Vl=Nl(function(){return!mr("z").propertyIsEnumerable(0)})?function(i){return Fl(i)=="String"?Ul(i,""):mr(i)}:mr,Ui=function(i){return i==null},Hl=Ui,Gl=TypeError,Ua=function(i){if(Hl(i))throw Gl("Can't call method on "+i);return i},Yl=Vl,jl=Ua,Vi=function(i){return Yl(jl(i))},fi={},is=function(i){return i&&i.Math==Math&&i},_e=is(typeof globalThis=="object"&&globalThis)||is(typeof window=="object"&&window)||is(typeof self=="object"&&self)||is(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(i){return typeof i=="function"||i===zl}:function(i){return typeof i=="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(i){return typeof i=="object"?i!==null:Pn(i)||i===Jl}:function(i){return typeof i=="object"?i!==null:Pn(i)},Xl=je,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(i){return ec?ma.createElement(i):{}},tc=Pt,ic=je,sc=Va,kd=!tc&&!ic(function(){return Object.defineProperty(sc("div"),"a",{get:function(){return 7}}).a!=7}),rc=Pt,ac=je,Pd=rc&&ac(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),nc=vt,oc=String,dc=TypeError,mt=function(i){if(nc(i))return i;throw dc(oc(i)+" is not an object")},uc=Ys,ss=Function.prototype.call,Fe=uc?ss.bind(ss):function(){return ss.apply(ss,arguments)},Ha={},gr=Ha,Sr=_e,lc=Ee,Dn=function(i){return lc(i)?i:void 0},Gt=function(i,e){return arguments.length<2?Dn(gr[i])||Dn(Sr[i]):gr[i]&&gr[i][e]||Sr[i]&&Sr[i][e]},cc=qe,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=je,fc=_e,pc=fc.String,Id=!!Object.getOwnPropertySymbols&&!hc(function(){var i=Symbol();return!pc(i)||!(Object(i)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(i){return typeof i=="symbol"}:function(i){var e=mc("Symbol");return gc(e)&&Sc(e.prototype,yc(i))},Tc=String,zs=function(i){try{return Tc(i)}catch(e){return"Object"}},Ec=Ee,$c=zs,Ac=TypeError,Yt=function(i){if(Ec(i))return i;throw Ac($c(i)+" is not a function")},_c=Yt,wc=Ui,Ws=function(i,e){var t=i[e];return wc(t)?void 0:_c(t)},yr=Fe,Tr=Ee,Er=vt,kc=TypeError,Pc=function(i,e){var t,s;if(e==="string"&&Tr(t=i.toString)&&!Er(s=yr(t,i))||Tr(t=i.valueOf)&&!Er(s=yr(t,i))||e!=="string"&&Tr(t=i.toString)&&!Er(s=yr(t,i)))return s;throw kc("Can't convert object to primitive value")},Ld={exports:{}},Rc=!0,Mn=_e,Dc=Object.defineProperty,Ic=function(i,e){try{Dc(Mn,i,{value:e,configurable:!0,writable:!0})}catch(t){Mn[i]=e}return e},Cc=_e,xc=Ic,Bn="__core-js_shared__",Lc=Cc[Bn]||xc(Bn,{}),Ga=Lc,Nn=Ga;(Ld.exports=function(i,e){return Nn[i]||(Nn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Od=Ld.exports,Oc=Ua,Mc=Object,Qs=function(i){return Mc(Oc(i))},Bc=qe,Nc=Qs,Fc=Bc({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return Fc(Nc(e),t)},Uc=qe,Vc=0,Hc=Math.random(),Gc=Uc(1 .toString),Md=function(i){return"Symbol("+(i===void 0?"":i)+")_"+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(i){return Fn($r,i)||($r[i]=zc&&Fn(si,i)?si[i]:Qc("Symbol."+i)),$r[i]},Kc=Fe,Un=vt,Vn=xd,Jc=Ws,Xc=Pc,Zc=Pe,eh=TypeError,th=Zc("toPrimitive"),ih=function(i,e){if(!Un(i)||Vn(i))return i;var t=Jc(i,th),s;if(t){if(e===void 0&&(e="default"),s=Kc(t,i,e),!Un(s)||Vn(s))return s;throw eh("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xc(i,e)},sh=ih,rh=xd,Ya=function(i){var e=sh(i,"string");return rh(e)?e:e+""},ah=Pt,nh=kd,oh=Pd,rs=mt,Hn=Ya,dh=TypeError,Ar=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,_r="enumerable",wr="configurable",kr="writable";Ht.f=ah?oh?function(e,t,s){if(rs(e),t=Hn(t),rs(s),typeof e=="function"&&t==="prototype"&&"value"in s&&kr in s&&!s[kr]){var r=uh(e,t);r&&r[kr]&&(e[t]=s.value,s={configurable:wr in s?s[wr]:r[wr],enumerable:_r in s?s[_r]:r[_r],writable:!1})}return Ar(e,t,s)}:Ar:function(e,t,s){if(rs(e),t=Hn(t),rs(s),nh)try{return Ar(e,t,s)}catch(r){}if("get"in s||"set"in s)throw dh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ks=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},lh=Pt,ch=Ht,hh=Ks,Hi=lh?function(i,e,t){return ch.f(i,e,hh(1,t))}:function(i,e,t){return i[e]=t,i},fh=Od,ph=Md,Gn=fh("keys"),ja=function(i){return Gn[i]||(Gn[i]=ph(i))},qa={},vh=Kl,Bd=_e,mh=vt,gh=Hi,Pr=ot,Rr=Ga,Sh=ja,bh=qa,Yn="Object already initialized",ga=Bd.TypeError,yh=Bd.WeakMap,Ls,Oi,Os,Th=function(i){return Os(i)?Oi(i):Ls(i,{})},Eh=function(i){return function(e){var t;if(!mh(e)||(t=Oi(e)).type!==i)throw ga("Incompatible receiver, "+i+" 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(i,e){if(et.has(i))throw ga(Yn);return e.facade=i,et.set(i,e),e},Oi=function(i){return et.get(i)||{}},Os=function(i){return et.has(i)}}else{var Jt=Sh("state");bh[Jt]=!0,Ls=function(i,e){if(Pr(i,Jt))throw ga(Yn);return e.facade=i,gh(i,Jt,e),e},Oi=function(i){return Pr(i,Jt)?i[Jt]:{}},Os=function(i){return Pr(i,Jt)}}var Nd={set:Ls,get:Oi,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=Fi,_h=qe,Vd=function(i){if(Ah(i)==="Function")return _h(i)},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=Vi,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(s){}if(xh(e,t))return Dh(!Ph(Rh.f,e,t),e[t])};var Oh=je,Mh=Ee,Bh=/#|\.prototype\./,Gi=function(i,e){var t=Fh[Nh(i)];return t==Vh?!0:t==Uh?!1:Mh(e)?Oh(e):!!e},Nh=Gi.normalize=function(i){return String(i).replace(Bh,".").toLowerCase()},Fh=Gi.data={},Uh=Gi.NATIVE="N",Vh=Gi.POLYFILL="P",jd=Gi,Wn=Vd,Hh=Yt,Gh=Ys,Yh=Wn(Wn.bind),Js=function(i,e){return Hh(i),e===void 0?i:Gh?Yh(i,e):function(){return i.apply(e,arguments)}},as=_e,jh=Ud,qh=Vd,zh=Ee,Wh=za.f,Qh=jd,Xt=Ha,Kh=Js,Zt=Hi,Qn=ot,Jh=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return jh(i,this,arguments)};return e.prototype=i.prototype,e},Xe=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?as:r?as[t]:(as[t]||{}).prototype,o=s?Xt:Xt[t]||Zt(Xt,t,{})[t],u=o.prototype,d,l,c,h,f,v,g,E,$;for(h in e)d=Qh(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Qn(n,h),v=o[h],l&&(i.dontCallGetSet?($=Wh(n,h),g=$&&$.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof v==typeof f)&&(i.bind&&l?E=Kh(f,as):i.wrap&&l?E=Jh(f):a&&zh(f)?E=qh(f):E=f,(i.sham||f&&f.sham||v&&v.sham)&&Zt(E,"sham",!0),Zt(o,h,E),a&&(c=t+"Prototype",Qn(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],h,f),i.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(i){var e=+i;return e!==e||e===0?0:of(e)},df=Qa,uf=Math.max,lf=Math.min,cf=function(i,e){var t=df(i);return t<0?uf(t+e,0):lf(t,e)},hf=Qa,ff=Math.min,pf=function(i){return i>0?ff(hf(i),9007199254740991):0},vf=pf,Ka=function(i){return vf(i.length)},mf=Vi,gf=cf,Sf=Ka,Kn=function(i){return function(e,t,s){var r=mf(e),a=Sf(r),n=gf(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},bf={includes:Kn(!0),indexOf:Kn(!1)},yf=qe,Dr=ot,Tf=Vi,Ef=bf.indexOf,$f=qa,Jn=yf([].push),Af=function(i,e){var t=Tf(i),s=0,r=[],a;for(a in t)!Dr($f,a)&&Dr(t,a)&&Jn(r,a);for(;e.length>s;)Dr(t,a=e[s++])&&(~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=Vi,xf=kf;zd.f=Pf&&!Rf?Object.defineProperties:function(e,t){If(e);for(var s=Cf(t),r=xf(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],s[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(i){return eo+ya+Zn+i+eo+"/"+ya+Zn},to=function(i){i.write(Jd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Vf=function(){var i=Ff("iframe"),e="java"+ya+":",t;return i.style.display="none",Nf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Jd("document.F=Object")),t.close(),t.F},ns,ks=function(){try{ns=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&ns?to(ns):Vf():to(ns);for(var i=Xn.length;i--;)delete ks[ba][Xn[i]];return ks()};Bf[Kd]=!0;var Xd=Object.create||function(e,t){var s;return e!==null?(Ir[ba]=Of(e),s=new Ir,Ir[ba]=null,s[Kd]=e):s=ks(),t===void 0?s:Mf.f(s,t)},Hf=je,Gf=!Hf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.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(i){var e=qf(i);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=Hi,Ja=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Kf(i,e,t),i},Jf=je,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 i={};return ht[Ea].call(i)!==i});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=Fi,dp=Pe,up=dp("toStringTag"),lp=Object,cp=Ps(function(){return arguments}())=="Arguments",hp=function(i,e){try{return i[e]}catch(t){}},Yi=np?Ps:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=hp(e=lp(i),up))=="string"?t:cp?Ps(e):(s=Ps(e))=="Object"&&op(e.callee)?"Arguments":s},fp=Xa,pp=Yi,vp=fp?{}.toString:function(){return"[object "+pp(this)+"]"},mp=Xa,gp=Ht.f,Sp=Hi,bp=ot,yp=vp,Tp=Pe,ro=Tp("toStringTag"),Za=function(i,e,t,s){if(i){var r=t?i:i.prototype;bp(r,ro)||gp(r,ro,{configurable:!0,value:e}),s&&!mp&&Sp(r,"toString",yp)}},Ep=tu.IteratorPrototype,$p=Xd,Ap=Ks,_p=Za,wp=fi,kp=function(){return this},Pp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=$p(Ep,{next:Ap(+!s,t)}),_p(i,r,!1,!0),wp[r]=kp,i},Rp=Xe,Dp=Fe,su=sf,Ip=Pp,Cp=Zd,xp=Za,ao=Ja,Lp=Pe,no=fi,ru=tu,Op=su.PROPER;su.CONFIGURABLE;ru.IteratorPrototype;var os=ru.BUGGY_SAFARI_ITERATORS,Lr=Lp("iterator"),oo="keys",ds="values",uo="entries",Mp=function(){return this},Bp=function(i,e,t,s,r,a,n){Ip(t,e,s);var o=function($){if($===r&&h)return h;if(!os&&$ in l)return l[$];switch($){case oo:return function(){return new t(this,$)};case ds:return function(){return new t(this,$)};case uo:return function(){return new t(this,$)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[Lr]||l["@@iterator"]||r&&l[r],h=!os&&c||o(r),f=e=="Array"&&l.entries||c,v,g,E;if(f&&(v=Cp(f.call(new i)),v!==Object.prototype&&v.next&&(xp(v,u,!0,!0),no[u]=Mp)),Op&&r==ds&&c&&c.name!==ds&&(d=!0,h=function(){return Dp(c,this)}),r)if(g={values:o(ds),keys:a?h:o(oo),entries:o(uo)},n)for(E in g)(os||d||!(E in l))&&ao(l,E,g[E]);else Rp({target:e,proto:!0,forced:os||d},g);return n&&l[Lr]!==h&&ao(l,Lr,h,{name:r}),no[e]=h,g},Np=function(i,e){return{value:i,done:e}},Fp=Vi,lo=fi,au=Nd;Ht.f;var Up=Bp,us=Np,nu="Array Iterator",Vp=au.set,Hp=au.getterFor(nu);Up(Array,"Array",function(i,e){Vp(this,{type:nu,target:Fp(i),index:0,kind:e})},function(){var i=Hp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,us(void 0,!0)):t=="keys"?us(s,!1):t=="values"?us(e[s],!1):us([s,e[s]],!1)},"values");lo.Arguments=lo.Array;var Gp=Pe,Yp=fi,jp=Gp("iterator"),qp=Array.prototype,zp=function(i){return i!==void 0&&(Yp.Array===i||qp[jp]===i)},Wp=Yi,co=Ws,Qp=Ui,Kp=fi,Jp=Pe,Xp=Jp("iterator"),ou=function(i){if(!Qp(i))return co(i,Xp)||co(i,"@@iterator")||Kp[Wp(i)]},Zp=Fe,ev=Yt,tv=mt,iv=zs,sv=ou,rv=TypeError,av=function(i,e){var t=arguments.length<2?sv(i):e;if(ev(t))return tv(Zp(t,i));throw rv(iv(i)+" is not iterable")},nv=Fe,ho=mt,ov=Ws,dv=function(i,e,t){var s,r;ho(i);try{if(s=ov(i,"return"),!s){if(e==="throw")throw t;return t}s=nv(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return ho(s),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(i,e){this.stopped=i,this.result=e},vo=Rs.prototype,en=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=uv(e,s),d,l,c,h,f,v,g,E=function(T){return d&&po(d,"normal",T),new Rs(!0,T)},$=function(T){return r?(cv(T),o?u(T[0],T[1],E):u(T[0],T[1])):o?u(T,E):u(T)};if(a)d=i.iterator;else if(n)d=i;else{if(l=mv(i),!l)throw gv(hv(i)+" is not iterable");if(fv(l)){for(c=0,h=pv(i);h>c;c++)if(f=$(i[c]),f&&fo(vo,f))return f;return new Rs(!1)}d=vv(i,l)}for(v=a?i.next:d.next;!(g=lv(v,d)).done;){try{f=$(g.value)}catch(T){po(d,"throw",T)}if(typeof f=="object"&&f&&fo(vo,f))return f}return new Rs(!1)},Sv=Ya,bv=Ht,yv=Ks,Tv=function(i,e,t){var s=Sv(e);s in i?bv.f(i,s,yv(0,t)):i[s]=t},Ev=Xe,$v=en,Av=Tv;Ev({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $v(e,function(s,r){Av(t,s,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=Yi,Iv=Hi,mo=fi,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,ji=Gs(Mv),Bv=Fi,Xs=typeof process!="undefined"&&Bv(process)=="process",Nv=Ht,Fv=function(i,e,t){return Nv.f(i,e,t)},Uv=Gt,Vv=Fv,Hv=Pe,Gv=Pt,bo=Hv("species"),Yv=function(i){var e=Uv(i);Gv&&e&&!e[bo]&&Vv(e,bo,{configurable:!0,get:function(){return this}})},jv=js,qv=TypeError,zv=function(i,e){if(jv(e,i))return i;throw qv("Incorrect invocation")},Wv=qe,Qv=Ee,$a=Ga,Kv=Wv(Function.toString);Qv($a.inspectSource)||($a.inspectSource=function(i){return Kv(i)});var du=$a.inspectSource,Jv=qe,Xv=je,uu=Ee,Zv=Yi,em=Gt,tm=du,lu=function(){},im=[],cu=em("Reflect","construct"),tn=/^\s*(?:class|function)\b/,sm=Jv(tn.exec),rm=!tn.exec(lu),Ai=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 i;return Ai(Ai.call)||!Ai(Object)||!Ai(function(){i=!0})||i})?hu:Ai,nm=am,om=zs,dm=TypeError,um=function(i){if(nm(i))return i;throw dm(om(i)+" is not a constructor")},yo=mt,lm=um,cm=Ui,hm=Pe,fm=hm("species"),fu=function(i,e){var t=yo(i).constructor,s;return t===void 0||cm(s=yo(t)[fm])?e:lm(s)},pm=qe,vm=pm([].slice),mm=TypeError,gm=function(i,e){if(i<e)throw mm("Not enough arguments");return i},Sm=qs,pu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sm),Me=_e,bm=Ud,ym=Js,To=Ee,Tm=ot,vu=je,Eo=Qd,Em=vm,$o=Va,$m=gm,Am=pu,_m=Xs,Aa=Me.setImmediate,_a=Me.clearImmediate,wm=Me.process,Br=Me.Dispatch,km=Me.Function,Ao=Me.MessageChannel,Pm=Me.String,Nr=0,Di={},_o="onreadystatechange",Mi,Mt,Fr,Ur;vu(function(){Mi=Me.location});var sn=function(i){if(Tm(Di,i)){var e=Di[i];delete Di[i],e()}},Vr=function(i){return function(){sn(i)}},wo=function(i){sn(i.data)},ko=function(i){Me.postMessage(Pm(i),Mi.protocol+"//"+Mi.host)};(!Aa||!_a)&&(Aa=function(e){$m(arguments.length,1);var t=To(e)?e:km(e),s=Em(arguments,1);return Di[++Nr]=function(){bm(t,void 0,s)},Mt(Nr),Nr},_a=function(e){delete Di[e]},_m?Mt=function(i){wm.nextTick(Vr(i))}:Br&&Br.now?Mt=function(i){Br.now(Vr(i))}:Ao&&!Am?(Fr=new Ao,Ur=Fr.port2,Fr.port1.onmessage=wo,Mt=ym(Ur.postMessage,Ur)):Me.addEventListener&&To(Me.postMessage)&&!Me.importScripts&&Mi&&Mi.protocol!=="file:"&&!vu(ko)?(Mt=ko,Me.addEventListener("message",wo,!1)):_o in $o("script")?Mt=function(i){Eo.appendChild($o("script"))[_o]=function(){Eo.removeChild(this),sn(i)}}:Mt=function(i){setTimeout(Vr(i),0)});var mu={set:Aa,clear:_a},gu=function(){this.head=null,this.tail=null};gu.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Su=gu,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,ls=Ut.Promise,Co=xm(Ut,"queueMicrotask"),wa=Co&&Co.value,ei,Yr,jr,cs,xo;if(!wa){var hs=new Lm,fs=function(){var i,e;for(Gr&&(i=Io.domain)&&i.exit();e=hs.get();)try{e()}catch(t){throw hs.head&&ei(),t}i&&i.enter()};!Om&&!Gr&&!Bm&&Ro&&Do?(Yr=!0,jr=Do.createTextNode(""),new Ro(fs).observe(jr,{characterData:!0}),ei=function(){jr.data=Yr=!Yr}):!Mm&&ls&&ls.resolve?(cs=ls.resolve(void 0),cs.constructor=ls,xo=Po(cs.then,cs),ei=function(){xo(fs)}):Gr?ei=function(){Io.nextTick(fs)}:(Hr=Po(Hr,Ut),ei=function(){Hr(fs)}),wa=function(i){hs.head||ei(),hs.add(i)}}var Nm=wa,Fm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},rn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Um=_e,pi=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,Ii=pi,jm=Ee,qm=jd,zm=du,Wm=Pe,Qm=Gm,Km=bu,qr=Dd,Lo=Ii&&Ii.prototype,Jm=Wm("species"),ka=!1,yu=jm(Ym.PromiseRejectionEvent),Xm=qm("Promise",function(){var i=zm(Ii),e=i!==String(Ii);if(!e&&qr===66||!(Lo.catch&&Lo.finally))return!0;if(!qr||qr<51||!/native code/.test(i)){var t=new Ii(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jm]=s,ka=t.then(function(){})instanceof s,!ka)return!0}return!e&&(Qm||Km)&&!yu}),qi={CONSTRUCTOR:Xm,REJECTION_EVENT:yu,SUBCLASSING:ka},vi={},Oo=Yt,Zm=TypeError,eg=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw Zm("Bad Promise constructor");e=s,t=r}),this.resolve=Oo(e),this.reject=Oo(t)};vi.f=function(i){return new eg(i)};var tg=Xe,Ms=Xs,kt=_e,zi=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=pi,nn=qi,$u=vi,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,ps,Bo,bg,Ru=function(i){var e;return ng(i)&&Pa(e=i.then)?e:!1},Du=function(i,e){var t=e.value,s=e.state==ku,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===Pu&&Tg(e),e.rejection=dn),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(_u("Promise-chain cycle")):(d=Ru(u))?zi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Iu=function(i,e){i.notified||(i.notified=!0,an(function(){for(var t=i.reactions,s;s=t.get();)Du(s,i);i.notified=!1,e&&!i.rejection&&yg(i)}))},Cu=function(i,e,t){var s,r;mg?(s=Da.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),kt.dispatchEvent(s)):s={promise:e,reason:t},!hg&&(r=kt["on"+i])?r(s):i===wu&&ug("Unhandled promise rejection",t)},yg=function(i){zi(Tu,kt,function(){var e=i.facade,t=i.value,s=No(i),r;if(s&&(r=lg(function(){Ms?on.emit("unhandledRejection",t,e):Cu(wu,e,t)}),i.rejection=Ms||No(i)?Pu:dn,r.error))throw r.value})},No=function(i){return i.rejection!==dn&&!i.parent},Tg=function(i){zi(Tu,kt,function(){var e=i.facade;Ms?on.emit("rejectionHandled",e):Cu(gg,e,i.value)})},ai=function(i,e,t){return function(s){i(e,s,t)}},oi=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Sg,Iu(i,!0))},Ca=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw _u("Promise can't be resolved itself");var s=Ru(e);s?an(function(){var r={done:!1};try{zi(s,e,ai(Ca,r,i),ai(oi,r,i))}catch(a){oi(r,a,i)}}):(i.value=e,i.state=ku,Iu(i,!1))}catch(r){oi({done:!1},r,i)}}};Au&&(ri=function(e){og(this,Wr),ag(e),zi(ps,this);var t=zr(this);try{e(ai(Ca,t),ai(oi,t))}catch(s){oi(t,s)}},Wr=ri.prototype,ps=function(e){fg(this,{type:Zs,done:!1,notified:!1,parent:!1,reactions:new cg,rejection:!1,state:Mo,value:void 0})},ps.prototype=ig(Wr,"then",function(e,t){var s=zr(this),r=Ia(dg(this,ri));return s.parent=!0,r.ok=Pa(e)?e:!0,r.fail=Pa(t)&&t,r.domain=Ms?on.domain:void 0,s.state==Mo?s.reactions.add(r):an(function(){Du(r,s)}),r.promise}),Bo=function(){var i=new ps,e=zr(i);this.promise=i,this.resolve=ai(Ca,e),this.reject=ai(oi,e)},$u.f=Ia=function(i){return i===ri||i===bg?new Bo(i):vg(i)});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(i){}var Ag=function(i,e){if(!e&&!Lu)return!1;var t=!1;try{var s={};s[xu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},_g=pi,wg=Ag,kg=qi.CONSTRUCTOR,Ou=kg||!wg(function(i){_g.all(i).then(void 0,function(){})}),Pg=Xe,Rg=Fe,Dg=Yt,Ig=vi,Cg=rn,xg=en,Lg=Ou;Pg({target:"Promise",stat:!0,forced:Lg},{all:function(e){var t=this,s=Ig.f(t),r=s.resolve,a=s.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),s.promise}});var Og=Xe,Mg=qi.CONSTRUCTOR,Uo=pi;Uo&&Uo.prototype;Og({target:"Promise",proto:!0,forced:Mg,real:!0},{catch:function(i){return this.then(void 0,i)}});var Bg=Xe,Ng=Fe,Fg=Yt,Ug=vi,Vg=rn,Hg=en,Gg=Ou;Bg({target:"Promise",stat:!0,forced:Gg},{race:function(e){var t=this,s=Ug.f(t),r=s.reject,a=Vg(function(){var n=Fg(t.resolve);Hg(e,function(o){Ng(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Yg=Xe,jg=Fe,qg=vi,zg=qi.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=vi,Mu=function(i,e){if(Wg(i),Qg(e)&&e.constructor===i)return e;var t=Kg.f(i),s=t.resolve;return s(e),t.promise},Jg=Xe,Xg=Gt,Zg=Rc,eS=pi,tS=qi.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=pi,nS=je,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(i){var e=uS(this,oS("Promise")),t=dS(i);return this.then(t?function(s){return Vo(e,i()).then(function(){return s})}:i,t?function(s){return Vo(e,i()).then(function(){throw s})}:i)}});var hS=Gt,un=hS,fS=un,pS=fS("Promise","finally"),vS=pS,mS=vS,gS=mS,SS=gS,er=Gs(SS),Te;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var nt=(i,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Te.DASH_CMAF_OFFSET_P:{if(e===0)return i;const s=new URL(i);return s.searchParams.set("offset_p",e.toFixed(0)),s.toString()}default:V(t)}return i};const Ho=(i,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:V(e)}};var R=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ce{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=G(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=G(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||k(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const bS=i=>{switch(i){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return V(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.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 s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===W.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(s)}break}case p.PLAYING:{switch(s){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(s)}break}case p.PAUSED:{switch(s){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(s)}break}default:V(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(G(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(Ye(ES)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(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(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(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(),R(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:V(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=G(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:W.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(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),R(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&&R(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const l=s[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 b.HLS:case b.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=s[e];P(l),r=nt(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.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 b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(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 s=this.params.desiredState.seekState.getState();return s.state===W.Applying||s.state===W.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(El(Go).subscribe(()=>a(`timeout(${Go})`)))});er(Promise.race([t,s]).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=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},_S=i=>{const e=new S(1/0),t=new x,s=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 E=ji(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(m=>m.split(": ")));if("x-playback-duration"in E||"x-playback-duration-millis"in E){const m=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),y=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=y!=null?y:m*1e3)!==null&&f!==void 0?f:NaN;k(A)&&!isNaN(A)&&e.next(A)}const $=(v=E["x-delivery-type"])!==null&&v!==void 0?v:Li.HTTP1,T=(g={1:!0,0:!1}[E["x-reused"]])!==null&&g!==void 0?g:void 0;s.next($),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,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$:s}},li=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},wS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:li}),!0),kS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Je=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=se(r),d=new ae;return r&&d.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},jt=(i,e,t)=>Je(e,()=>i.loop,s=>{k(s)&&(i.loop=s)},{onError:t}),gt=(i,e,t,s)=>Je(e,()=>({muted:i.muted,volume:i.volume}),r=>{k(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),Rt=(i,e,t,s)=>Je(e,()=>i.playbackRate,r=>{k(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),PS=i=>["__",i.language,i.label].join("|"),RS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.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,s){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(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.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(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(G(U(e,"addtrack"),U(e,"removetrack"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ve((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(G(U(e,"change"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),w(s=>s&&this.htmlTextTrackToITextTrack(s).id),ve()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.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=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(dt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;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:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t)))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))k(e)&&RS(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){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"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const ln=i=>{i.removeAttribute("src"),i.load()},DS=i=>{try{i.pause(),i.playbackRate=0,ln(i),i.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=i=>{let e=i.querySelector("video");const t=!!e;return e?ln(e):(e=document.createElement("video"),i.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=i=>{const e=La.get(i);La.delete(i),e?ln(i):DS(i)};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=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Yo=i=>{const e=Bu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},CS=i=>{const e=Bu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Oa=3;class xS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Oa&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||Oa))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var Nu=(i,e,t=Oa)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const yt=i=>{const e=m=>U(i,m).pipe(ui(void 0)),s=G(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>U(i,m))).pipe(w(m=>m.type==="ended"?i.readyState<2:i.readyState<3),ve()),r=G(U(i,"progress"),U(i,"timeupdate")).pipe(w(()=>Nu(i.buffered,i.currentTime))),n=Fa().browser===bd.Safari?Be({play:e("play").pipe(ge()),playing:e("playing")}).pipe(ui(void 0)):e("playing"),o=U(i,"volumechange").pipe(w(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe(w(()=>i.playbackRate)),d=U(i,"error").pipe(re(()=>!!(i.error||i.played.length)),w(()=>{var m;const y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),l=U(i,"timeupdate").pipe(w(()=>i.currentTime)),c=new x,h=.3;let f;l.subscribe(m=>{i.loop&&k(f)&&k(m)&&f>=i.duration-h&&m<=h&&c.next(f),f=m});const v=U(i,"enterpictureinpicture"),g=U(i,"leavepictureinpicture"),E=new S(CS(i));v.subscribe(()=>E.next(!0)),g.subscribe(()=>E.next(!1));const $=new S(Yo(i));return U(i,"fullscreenchange").pipe(w(()=>Yo(i))).subscribe($),{playing$:n,pause$:e("pause").pipe(re(()=>!i.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$:U(i,"durationchange").pipe(w(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:E,inFullscreen$:$}},cn=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var LS=Xe,OS=Qs,MS=Ka,BS=Qa;LS({target:"Array",proto:!0},{at:function(e){var t=OS(this),s=MS(t),r=BS(e),a=r>=0?r:s+r;return a<0||a>=s?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=i=>{hn=i},jS=()=>{ct={}},qS=i=>{i(ct)},vs=(i,e)=>{var t;hn&&(ct.meta=(t=ct.meta)!==null&&t!==void 0?t:{},ct.meta[i]=e)};class st{constructor(e){this.name=e}next(e){var t,s;if(!hn)return;ct.series=(t=ct.series)!==null&&t!==void 0?t:{};const r=(s=ct.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ct.series[this.name]=r}}var Nt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(Nt||(Nt={}));const zS=new st("best_bitrate"),WS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+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 mi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,v,g,E;const $=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,T=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*$*s.containerSizeFactor,height:e.height*$*s.containerSizeFactor},m=T&&Vt(T),y=s.considerPlaybackRate&&k(o)?o:1,A=i.filter(F=>!xi(F.quality)).sort((F,I)=>_s(F.quality,I.quality)?-1:1),D=(f=it(A,-1))===null||f===void 0?void 0:f.quality,j=(v=it(A,0))===null||v===void 0?void 0:v.quality,X=se(r)||k(r.min)&&k(r.max)&&ws(r.max,r.min)||k(r.min)&&j&&_s(r.min,j)||k(r.max)&&D&&ws(r.max,D),N=y*WS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y={},O=A.filter(F=>(m?ws(F.quality,m):!0)?(k(t)&&isFinite(t)&&k(F.bitrate)?t-a>=F.bitrate*N:!0)?s.lazyQualitySwitch&&k(s.minBufferToSwitchUp)&&u&&!xi(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&_s(F.quality,u.quality)?(Y[F.quality]=Nt.Buffer,!1):!!l&&fa(F.quality,l)?(Y[F.quality]=Nt.DroppedFramesLimit,!1):X||(se(r.max)||yd(F.quality,r.max))&&(se(r.min)||fa(F.quality,r.min))?!0:(Y[F.quality]=Nt.FitsQualityLimits,!1):(Y[F.quality]=Nt.FitsThroughput,!1):(Y[F.quality]=Nt.FitsContainer,!1))[0];O&&O.bitrate&&zS.next(O.bitrate);const H=(g=O!=null?O:A[Math.ceil((A.length-1)/2)])!==null&&g!==void 0?g:i[0];H.quality!==((E=d==null?void 0:d.last)===null||E===void 0?void 0:E.quality)&&c({message:`
|
|
7
|
-
[available tracks] ${i.map(
|
|
6
|
+
import{ValueSubject as S,Subject as L,Subscription as ne,isNonNullable as k,ErrorCategory as O,isNullable as re,fromEvent as U,assertNever as G,merge as H,tap as xs,map as w,observableFrom as Ne,filterChanged as me,assertNonNullable as P,debounce as Ye,getHighestQuality as kl,timeout as Pl,getCurrentBrowser as za,CurrentClientBrowser as _d,combine as Ce,once as ge,mapTo as Si,filter as ee,now as le,videoSizeToQuality as zt,isInvariantQuality as Mi,isHigher as Ps,isLower as Ds,isHigherOrEqual as ba,isLowerOrEqual as kd,Observable as qs,interval as Os,VideoQuality as Je,videoQualityToHeight as Dl,abortable as Re,getExponentialDelay as yr,CurrentClientDevice as Rl,safeStorage as Tr,fillWithDefault as Il,Logger as Cl}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as zT,Subject as WT,Subscription as QT,ValueSubject as KT,VideoQuality as JT}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Ll from"lodash/debounce.js";const xl="2.0.92-dev.1c5a344.0";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var y;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var _e;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(_e||(_e={}));var $e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})($e||($e={}));var Ni;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(Ni||(Ni={}));var W;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(W||(W={}));var _t;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(_t||(_t={}));function ae(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function N(i){return this instanceof N?(this.v=i,this):new N(i)}function Ie(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,b){a.push([h,f,m,b])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(m){c(a[0][3],m)}}function u(h){h.value instanceof N?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 Ol=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Bl{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S($e.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new S($e.NOT_AVAILABLE),this.subscription=new ne,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=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||Ol("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:O.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();re(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();re(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(U(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return G(r.sessionState)}})).add(H(U(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(xs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),Ne([s.getCastState()])).pipe(me(),w(Ml),xs(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=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(re(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,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:O.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Ml=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return $e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return $e.AVAILABLE;case cast.framework.CastState.CONNECTING:return $e.CONNECTING;case cast.framework.CastState.CONNECTED:return $e.CONNECTED;default:return G(i)}};var Er=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function zs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var je=function(i){try{return!!i()}catch(e){return!0}},Nl=je,Ws=!Nl(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Pd=Ws,Dd=Function.prototype,ya=Dd.call,Fl=Pd&&Dd.bind.bind(ya,ya),qe=Pd?Fl:function(i){return function(){return ya.apply(i,arguments)}},Rd=qe,Ul=Rd({}.toString),Vl=Rd("".slice),Gi=function(i){return Vl(Ul(i),8,-1)},Hl=qe,Gl=je,Yl=Gi,$r=Object,jl=Hl("".split),ql=Gl(function(){return!$r("z").propertyIsEnumerable(0)})?function(i){return Yl(i)=="String"?jl(i,""):$r(i)}:$r,Yi=function(i){return i==null},zl=Yi,Wl=TypeError,Wa=function(i){if(zl(i))throw Wl("Can't call method on "+i);return i},Ql=ql,Kl=Wa,ji=function(i){return Ql(Kl(i))},Ei={},ns=function(i){return i&&i.Math==Math&&i},we=ns(typeof globalThis=="object"&&globalThis)||ns(typeof window=="object"&&window)||ns(typeof self=="object"&&self)||ns(typeof Er=="object"&&Er)||function(){return this}()||Er||Function("return this")(),Ta=typeof document=="object"&&document.all,Jl=typeof Ta=="undefined"&&Ta!==void 0,Id={all:Ta,IS_HTMLDDA:Jl},Cd=Id,Xl=Cd.all,Ee=Cd.IS_HTMLDDA?function(i){return typeof i=="function"||i===Xl}:function(i){return typeof i=="function"},Zl=we,ec=Ee,xn=Zl.WeakMap,tc=ec(xn)&&/native code/.test(String(xn)),On=Ee,Ld=Id,ic=Ld.all,gt=Ld.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:On(i)||i===ic}:function(i){return typeof i=="object"?i!==null:On(i)},sc=je,It=!sc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Wt={},rc=we,Bn=gt,Ea=rc.document,ac=Bn(Ea)&&Bn(Ea.createElement),Qa=function(i){return ac?Ea.createElement(i):{}},nc=It,oc=je,dc=Qa,xd=!nc&&!oc(function(){return Object.defineProperty(dc("div"),"a",{get:function(){return 7}}).a!=7}),uc=It,lc=je,Od=uc&&lc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),cc=gt,hc=String,fc=TypeError,St=function(i){if(cc(i))return i;throw fc(hc(i)+" is not an object")},pc=Ws,os=Function.prototype.call,Fe=pc?os.bind(os):function(){return os.apply(os,arguments)},Ka={},Ar=Ka,wr=we,mc=Ee,Mn=function(i){return mc(i)?i:void 0},Qt=function(i,e){return arguments.length<2?Mn(Ar[i])||Mn(wr[i]):Ar[i]&&Ar[i][e]||wr[i]&&wr[i][e]},vc=qe,Qs=vc({}.isPrototypeOf),Ks=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Bd=we,_r=Ks,Nn=Bd.process,Fn=Bd.Deno,Un=Nn&&Nn.versions||Fn&&Fn.version,Vn=Un&&Un.v8,Xe,Bs;Vn&&(Xe=Vn.split("."),Bs=Xe[0]>0&&Xe[0]<4?1:+(Xe[0]+Xe[1]));!Bs&&_r&&(Xe=_r.match(/Edge\/(\d+)/),(!Xe||Xe[1]>=74)&&(Xe=_r.match(/Chrome\/(\d+)/),Xe&&(Bs=+Xe[1])));var Md=Bs,Hn=Md,gc=je,Sc=we,bc=Sc.String,Nd=!!Object.getOwnPropertySymbols&&!gc(function(){var i=Symbol();return!bc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Hn&&Hn<41}),yc=Nd,Fd=yc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Tc=Qt,Ec=Ee,$c=Qs,Ac=Fd,wc=Object,Ud=Ac?function(i){return typeof i=="symbol"}:function(i){var e=Tc("Symbol");return Ec(e)&&$c(e.prototype,wc(i))},_c=String,Js=function(i){try{return _c(i)}catch(e){return"Object"}},kc=Ee,Pc=Js,Dc=TypeError,Kt=function(i){if(kc(i))return i;throw Dc(Pc(i)+" is not a function")},Rc=Kt,Ic=Yi,Xs=function(i,e){var t=i[e];return Ic(t)?void 0:Rc(t)},kr=Fe,Pr=Ee,Dr=gt,Cc=TypeError,Lc=function(i,e){var t,s;if(e==="string"&&Pr(t=i.toString)&&!Dr(s=kr(t,i))||Pr(t=i.valueOf)&&!Dr(s=kr(t,i))||e!=="string"&&Pr(t=i.toString)&&!Dr(s=kr(t,i)))return s;throw Cc("Can't convert object to primitive value")},Vd={exports:{}},xc=!0,Gn=we,Oc=Object.defineProperty,Bc=function(i,e){try{Oc(Gn,i,{value:e,configurable:!0,writable:!0})}catch(t){Gn[i]=e}return e},Mc=we,Nc=Bc,Yn="__core-js_shared__",Fc=Mc[Yn]||Nc(Yn,{}),Ja=Fc,jn=Ja;(Vd.exports=function(i,e){return jn[i]||(jn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Hd=Vd.exports,Uc=Wa,Vc=Object,Zs=function(i){return Vc(Uc(i))},Hc=qe,Gc=Zs,Yc=Hc({}.hasOwnProperty),lt=Object.hasOwn||function(e,t){return Yc(Gc(e),t)},jc=qe,qc=0,zc=Math.random(),Wc=jc(1 .toString),Gd=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Wc(++qc+zc,36)},Qc=we,Kc=Hd,qn=lt,Jc=Gd,Xc=Nd,Zc=Fd,hi=Qc.Symbol,Rr=Kc("wks"),eh=Zc?hi.for||hi:hi&&hi.withoutSetter||Jc,Pe=function(i){return qn(Rr,i)||(Rr[i]=Xc&&qn(hi,i)?hi[i]:eh("Symbol."+i)),Rr[i]},th=Fe,zn=gt,Wn=Ud,ih=Xs,sh=Lc,rh=Pe,ah=TypeError,nh=rh("toPrimitive"),oh=function(i,e){if(!zn(i)||Wn(i))return i;var t=ih(i,nh),s;if(t){if(e===void 0&&(e="default"),s=th(t,i,e),!zn(s)||Wn(s))return s;throw ah("Can't convert object to primitive value")}return e===void 0&&(e="number"),sh(i,e)},dh=oh,uh=Ud,Xa=function(i){var e=dh(i,"string");return uh(e)?e:e+""},lh=It,ch=xd,hh=Od,ds=St,Qn=Xa,fh=TypeError,Ir=Object.defineProperty,ph=Object.getOwnPropertyDescriptor,Cr="enumerable",Lr="configurable",xr="writable";Wt.f=lh?hh?function(e,t,s){if(ds(e),t=Qn(t),ds(s),typeof e=="function"&&t==="prototype"&&"value"in s&&xr in s&&!s[xr]){var r=ph(e,t);r&&r[xr]&&(e[t]=s.value,s={configurable:Lr in s?s[Lr]:r[Lr],enumerable:Cr in s?s[Cr]:r[Cr],writable:!1})}return Ir(e,t,s)}:Ir:function(e,t,s){if(ds(e),t=Qn(t),ds(s),ch)try{return Ir(e,t,s)}catch(r){}if("get"in s||"set"in s)throw fh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var er=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},mh=It,vh=Wt,gh=er,qi=mh?function(i,e,t){return vh.f(i,e,gh(1,t))}:function(i,e,t){return i[e]=t,i},Sh=Hd,bh=Gd,Kn=Sh("keys"),Za=function(i){return Kn[i]||(Kn[i]=bh(i))},en={},yh=tc,Yd=we,Th=gt,Eh=qi,Or=lt,Br=Ja,$h=Za,Ah=en,Jn="Object already initialized",$a=Yd.TypeError,wh=Yd.WeakMap,Ms,Fi,Ns,_h=function(i){return Ns(i)?Fi(i):Ms(i,{})},kh=function(i){return function(e){var t;if(!Th(e)||(t=Fi(e)).type!==i)throw $a("Incompatible receiver, "+i+" required");return t}};if(yh||Br.state){var st=Br.state||(Br.state=new wh);st.get=st.get,st.has=st.has,st.set=st.set,Ms=function(i,e){if(st.has(i))throw $a(Jn);return e.facade=i,st.set(i,e),e},Fi=function(i){return st.get(i)||{}},Ns=function(i){return st.has(i)}}else{var ri=$h("state");Ah[ri]=!0,Ms=function(i,e){if(Or(i,ri))throw $a(Jn);return e.facade=i,Eh(i,ri,e),e},Fi=function(i){return Or(i,ri)?i[ri]:{}},Ns=function(i){return Or(i,ri)}}var jd={set:Ms,get:Fi,has:Ns,enforce:_h,getterFor:kh},Ph=Ws,qd=Function.prototype,Xn=qd.apply,Zn=qd.call,zd=typeof Reflect=="object"&&Reflect.apply||(Ph?Zn.bind(Xn):function(){return Zn.apply(Xn,arguments)}),Dh=Gi,Rh=qe,Wd=function(i){if(Dh(i)==="Function")return Rh(i)},tn={},Qd={},Kd={}.propertyIsEnumerable,Jd=Object.getOwnPropertyDescriptor,Ih=Jd&&!Kd.call({1:2},1);Qd.f=Ih?function(e){var t=Jd(this,e);return!!t&&t.enumerable}:Kd;var Ch=It,Lh=Fe,xh=Qd,Oh=er,Bh=ji,Mh=Xa,Nh=lt,Fh=xd,eo=Object.getOwnPropertyDescriptor;tn.f=Ch?eo:function(e,t){if(e=Bh(e),t=Mh(t),Fh)try{return eo(e,t)}catch(s){}if(Nh(e,t))return Oh(!Lh(xh.f,e,t),e[t])};var Uh=je,Vh=Ee,Hh=/#|\.prototype\./,zi=function(i,e){var t=Yh[Gh(i)];return t==qh?!0:t==jh?!1:Vh(e)?Uh(e):!!e},Gh=zi.normalize=function(i){return String(i).replace(Hh,".").toLowerCase()},Yh=zi.data={},jh=zi.NATIVE="N",qh=zi.POLYFILL="P",Xd=zi,to=Wd,zh=Kt,Wh=Ws,Qh=to(to.bind),tr=function(i,e){return zh(i),e===void 0?i:Wh?Qh(i,e):function(){return i.apply(e,arguments)}},us=we,Kh=zd,Jh=Wd,Xh=Ee,Zh=tn.f,ef=Xd,ai=Ka,tf=tr,ni=qi,io=lt,sf=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Kh(i,this,arguments)};return e.prototype=i.prototype,e},et=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?us:r?us[t]:(us[t]||{}).prototype,o=s?ai:ai[t]||ni(ai,t,{})[t],u=o.prototype,d,l,c,h,f,m,b,E,g;for(h in e)d=ef(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&io(n,h),m=o[h],l&&(i.dontCallGetSet?(g=Zh(n,h),b=g&&g.value):b=n[h]),f=l&&b?b:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?E=tf(f,us):i.wrap&&l?E=sf(f):a&&Xh(f)?E=Jh(f):E=f,(i.sham||f&&f.sham||m&&m.sham)&&ni(E,"sham",!0),ni(o,h,E),a&&(c=t+"Prototype",io(ai,c)||ni(ai,c,{}),ni(ai[c],h,f),i.real&&u&&(d||!u[h])&&ni(u,h,f)))},Aa=It,rf=lt,Zd=Function.prototype,af=Aa&&Object.getOwnPropertyDescriptor,sn=rf(Zd,"name"),nf=sn&&function(){}.name==="something",of=sn&&(!Aa||Aa&&af(Zd,"name").configurable),df={EXISTS:sn,PROPER:nf,CONFIGURABLE:of},eu={},uf=Math.ceil,lf=Math.floor,cf=Math.trunc||function(e){var t=+e;return(t>0?lf:uf)(t)},hf=cf,rn=function(i){var e=+i;return e!==e||e===0?0:hf(e)},ff=rn,pf=Math.max,mf=Math.min,vf=function(i,e){var t=ff(i);return t<0?pf(t+e,0):mf(t,e)},gf=rn,Sf=Math.min,bf=function(i){return i>0?Sf(gf(i),9007199254740991):0},yf=bf,an=function(i){return yf(i.length)},Tf=ji,Ef=vf,$f=an,so=function(i){return function(e,t,s){var r=Tf(e),a=$f(r),n=Ef(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},Af={includes:so(!0),indexOf:so(!1)},wf=qe,Mr=lt,_f=ji,kf=Af.indexOf,Pf=en,ro=wf([].push),Df=function(i,e){var t=_f(i),s=0,r=[],a;for(a in t)!Mr(Pf,a)&&Mr(t,a)&&ro(r,a);for(;e.length>s;)Mr(t,a=e[s++])&&(~kf(r,a)||ro(r,a));return r},tu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rf=Df,If=tu,Cf=Object.keys||function(e){return Rf(e,If)},Lf=It,xf=Od,Of=Wt,Bf=St,Mf=ji,Nf=Cf;eu.f=Lf&&!xf?Object.defineProperties:function(e,t){Bf(e);for(var s=Mf(t),r=Nf(t),a=r.length,n=0,o;a>n;)Of.f(e,o=r[n++],s[o]);return e};var Ff=Qt,iu=Ff("document","documentElement"),Uf=St,Vf=eu,ao=tu,Hf=en,Gf=iu,Yf=Qa,jf=Za,no=">",oo="<",wa="prototype",_a="script",su=jf("IE_PROTO"),Nr=function(){},ru=function(i){return oo+_a+no+i+oo+"/"+_a+no},uo=function(i){i.write(ru("")),i.close();var e=i.parentWindow.Object;return i=null,e},qf=function(){var i=Yf("iframe"),e="java"+_a+":",t;return i.style.display="none",Gf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(ru("document.F=Object")),t.close(),t.F},ls,Rs=function(){try{ls=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&ls?uo(ls):qf():uo(ls);for(var i=ao.length;i--;)delete Rs[wa][ao[i]];return Rs()};Hf[su]=!0;var au=Object.create||function(e,t){var s;return e!==null?(Nr[wa]=Uf(e),s=new Nr,Nr[wa]=null,s[su]=e):s=Rs(),t===void 0?s:Vf.f(s,t)},zf=je,Wf=!zf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Qf=lt,Kf=Ee,Jf=Zs,Xf=Za,Zf=Wf,lo=Xf("IE_PROTO"),ka=Object,ep=ka.prototype,nu=Zf?ka.getPrototypeOf:function(i){var e=Jf(i);if(Qf(e,lo))return e[lo];var t=e.constructor;return Kf(t)&&e instanceof t?t.prototype:e instanceof ka?ep:null},tp=qi,nn=function(i,e,t,s){return s&&s.enumerable?i[e]=t:tp(i,e,t),i},ip=je,sp=Ee,rp=gt,ap=au,co=nu,np=nn,op=Pe,Pa=op("iterator"),ou=!1,pt,Fr,Ur;[].keys&&(Ur=[].keys(),"next"in Ur?(Fr=co(co(Ur)),Fr!==Object.prototype&&(pt=Fr)):ou=!0);var dp=!rp(pt)||ip(function(){var i={};return pt[Pa].call(i)!==i});dp?pt={}:pt=ap(pt);sp(pt[Pa])||np(pt,Pa,function(){return this});var du={IteratorPrototype:pt,BUGGY_SAFARI_ITERATORS:ou},up=Pe,lp=up("toStringTag"),uu={};uu[lp]="z";var on=String(uu)==="[object z]",cp=on,hp=Ee,Is=Gi,fp=Pe,pp=fp("toStringTag"),mp=Object,vp=Is(function(){return arguments}())=="Arguments",gp=function(i,e){try{return i[e]}catch(t){}},Wi=cp?Is:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=gp(e=mp(i),pp))=="string"?t:vp?Is(e):(s=Is(e))=="Object"&&hp(e.callee)?"Arguments":s},Sp=on,bp=Wi,yp=Sp?{}.toString:function(){return"[object "+bp(this)+"]"},Tp=on,Ep=Wt.f,$p=qi,Ap=lt,wp=yp,_p=Pe,ho=_p("toStringTag"),dn=function(i,e,t,s){if(i){var r=t?i:i.prototype;Ap(r,ho)||Ep(r,ho,{configurable:!0,value:e}),s&&!Tp&&$p(r,"toString",wp)}},kp=du.IteratorPrototype,Pp=au,Dp=er,Rp=dn,Ip=Ei,Cp=function(){return this},Lp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Pp(kp,{next:Dp(+!s,t)}),Rp(i,r,!1,!0),Ip[r]=Cp,i},xp=et,Op=Fe,lu=df,Bp=Lp,Mp=nu,Np=dn,fo=nn,Fp=Pe,po=Ei,cu=du,Up=lu.PROPER;lu.CONFIGURABLE;cu.IteratorPrototype;var cs=cu.BUGGY_SAFARI_ITERATORS,Vr=Fp("iterator"),mo="keys",hs="values",vo="entries",Vp=function(){return this},Hp=function(i,e,t,s,r,a,n){Bp(t,e,s);var o=function(g){if(g===r&&h)return h;if(!cs&&g in l)return l[g];switch(g){case mo:return function(){return new t(this,g)};case hs:return function(){return new t(this,g)};case vo:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[Vr]||l["@@iterator"]||r&&l[r],h=!cs&&c||o(r),f=e=="Array"&&l.entries||c,m,b,E;if(f&&(m=Mp(f.call(new i)),m!==Object.prototype&&m.next&&(Np(m,u,!0,!0),po[u]=Vp)),Up&&r==hs&&c&&c.name!==hs&&(d=!0,h=function(){return Op(c,this)}),r)if(b={values:o(hs),keys:a?h:o(mo),entries:o(vo)},n)for(E in b)(cs||d||!(E in l))&&fo(l,E,b[E]);else xp({target:e,proto:!0,forced:cs||d},b);return n&&l[Vr]!==h&&fo(l,Vr,h,{name:r}),po[e]=h,b},Gp=function(i,e){return{value:i,done:e}},Yp=ji,go=Ei,hu=jd;Wt.f;var jp=Hp,fs=Gp,fu="Array Iterator",qp=hu.set,zp=hu.getterFor(fu);jp(Array,"Array",function(i,e){qp(this,{type:fu,target:Yp(i),index:0,kind:e})},function(){var i=zp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,fs(void 0,!0)):t=="keys"?fs(s,!1):t=="values"?fs(e[s],!1):fs([s,e[s]],!1)},"values");go.Arguments=go.Array;var Wp=Pe,Qp=Ei,Kp=Wp("iterator"),Jp=Array.prototype,Xp=function(i){return i!==void 0&&(Qp.Array===i||Jp[Kp]===i)},Zp=Wi,So=Xs,em=Yi,tm=Ei,im=Pe,sm=im("iterator"),pu=function(i){if(!em(i))return So(i,sm)||So(i,"@@iterator")||tm[Zp(i)]},rm=Fe,am=Kt,nm=St,om=Js,dm=pu,um=TypeError,lm=function(i,e){var t=arguments.length<2?dm(i):e;if(am(t))return nm(rm(t,i));throw um(om(i)+" is not iterable")},cm=Fe,bo=St,hm=Xs,fm=function(i,e,t){var s,r;bo(i);try{if(s=hm(i,"return"),!s){if(e==="throw")throw t;return t}s=cm(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return bo(s),t},pm=tr,mm=Fe,vm=St,gm=Js,Sm=Xp,bm=an,yo=Qs,ym=lm,Tm=pu,To=fm,Em=TypeError,Cs=function(i,e){this.stopped=i,this.result=e},Eo=Cs.prototype,un=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=pm(e,s),d,l,c,h,f,m,b,E=function(_){return d&&To(d,"normal",_),new Cs(!0,_)},g=function(_){return r?(vm(_),o?u(_[0],_[1],E):u(_[0],_[1])):o?u(_,E):u(_)};if(a)d=i.iterator;else if(n)d=i;else{if(l=Tm(i),!l)throw Em(gm(i)+" is not iterable");if(Sm(l)){for(c=0,h=bm(i);h>c;c++)if(f=g(i[c]),f&&yo(Eo,f))return f;return new Cs(!1)}d=ym(i,l)}for(m=a?i.next:d.next;!(b=mm(m,d)).done;){try{f=g(b.value)}catch(_){To(d,"throw",_)}if(typeof f=="object"&&f&&yo(Eo,f))return f}return new Cs(!1)},$m=Xa,Am=Wt,wm=er,_m=function(i,e,t){var s=$m(e);s in i?Am.f(i,s,wm(0,t)):i[s]=t},km=et,Pm=un,Dm=_m;km({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Pm(e,function(s,r){Dm(t,s,r)},{AS_ENTRIES:!0}),t}});var Rm=Ka,Im=Rm.Object.fromEntries,Cm={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},Lm=Cm,xm=we,Om=Wi,Bm=qi,$o=Ei,Mm=Pe,Ao=Mm("toStringTag");for(var Hr in Lm){var wo=xm[Hr],Gr=wo&&wo.prototype;Gr&&Om(Gr)!==Ao&&Bm(Gr,Ao,Hr),$o[Hr]=$o.Array}var Nm=Im,Fm=Nm,Um=Fm,Vm=Um,Qi=zs(Vm),Hm=Gi,ir=typeof process!="undefined"&&Hm(process)=="process",Gm=Wt,Ym=function(i,e,t){return Gm.f(i,e,t)},jm=Qt,qm=Ym,zm=Pe,Wm=It,_o=zm("species"),Qm=function(i){var e=jm(i);Wm&&e&&!e[_o]&&qm(e,_o,{configurable:!0,get:function(){return this}})},Km=Qs,Jm=TypeError,Xm=function(i,e){if(Km(e,i))return i;throw Jm("Incorrect invocation")},Zm=qe,ev=Ee,Da=Ja,tv=Zm(Function.toString);ev(Da.inspectSource)||(Da.inspectSource=function(i){return tv(i)});var mu=Da.inspectSource,iv=qe,sv=je,vu=Ee,rv=Wi,av=Qt,nv=mu,gu=function(){},ov=[],Su=av("Reflect","construct"),ln=/^\s*(?:class|function)\b/,dv=iv(ln.exec),uv=!ln.exec(gu),Pi=function(e){if(!vu(e))return!1;try{return Su(gu,ov,e),!0}catch(t){return!1}},bu=function(e){if(!vu(e))return!1;switch(rv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return uv||!!dv(ln,nv(e))}catch(t){return!0}};bu.sham=!0;var lv=!Su||sv(function(){var i;return Pi(Pi.call)||!Pi(Object)||!Pi(function(){i=!0})||i})?bu:Pi,cv=lv,hv=Js,fv=TypeError,pv=function(i){if(cv(i))return i;throw fv(hv(i)+" is not a constructor")},ko=St,mv=pv,vv=Yi,gv=Pe,Sv=gv("species"),yu=function(i,e){var t=ko(i).constructor,s;return t===void 0||vv(s=ko(t)[Sv])?e:mv(s)},bv=qe,yv=bv([].slice),Tv=TypeError,Ev=function(i,e){if(i<e)throw Tv("Not enough arguments");return i},$v=Ks,Tu=/(?:ipad|iphone|ipod).*applewebkit/i.test($v),Me=we,Av=zd,wv=tr,Po=Ee,_v=lt,Eu=je,Do=iu,kv=yv,Ro=Qa,Pv=Ev,Dv=Tu,Rv=ir,Ra=Me.setImmediate,Ia=Me.clearImmediate,Iv=Me.process,Yr=Me.Dispatch,Cv=Me.Function,Io=Me.MessageChannel,Lv=Me.String,jr=0,xi={},Co="onreadystatechange",Ui,Ht,qr,zr;Eu(function(){Ui=Me.location});var cn=function(i){if(_v(xi,i)){var e=xi[i];delete xi[i],e()}},Wr=function(i){return function(){cn(i)}},Lo=function(i){cn(i.data)},xo=function(i){Me.postMessage(Lv(i),Ui.protocol+"//"+Ui.host)};(!Ra||!Ia)&&(Ra=function(e){Pv(arguments.length,1);var t=Po(e)?e:Cv(e),s=kv(arguments,1);return xi[++jr]=function(){Av(t,void 0,s)},Ht(jr),jr},Ia=function(e){delete xi[e]},Rv?Ht=function(i){Iv.nextTick(Wr(i))}:Yr&&Yr.now?Ht=function(i){Yr.now(Wr(i))}:Io&&!Dv?(qr=new Io,zr=qr.port2,qr.port1.onmessage=Lo,Ht=wv(zr.postMessage,zr)):Me.addEventListener&&Po(Me.postMessage)&&!Me.importScripts&&Ui&&Ui.protocol!=="file:"&&!Eu(xo)?(Ht=xo,Me.addEventListener("message",Lo,!1)):Co in Ro("script")?Ht=function(i){Do.appendChild(Ro("script"))[Co]=function(){Do.removeChild(this),cn(i)}}:Ht=function(i){setTimeout(Wr(i),0)});var $u={set:Ra,clear:Ia},Au=function(){this.head=null,this.tail=null};Au.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var wu=Au,xv=Ks,Ov=/ipad|iphone|ipod/i.test(xv)&&typeof Pebble!="undefined",Bv=Ks,Mv=/web0s(?!.*chrome)/i.test(Bv),qt=we,Oo=tr,Nv=tn.f,Qr=$u.set,Fv=wu,Uv=Tu,Vv=Ov,Hv=Mv,Kr=ir,Bo=qt.MutationObserver||qt.WebKitMutationObserver,Mo=qt.document,No=qt.process,ps=qt.Promise,Fo=Nv(qt,"queueMicrotask"),Ca=Fo&&Fo.value,oi,Jr,Xr,ms,Uo;if(!Ca){var vs=new Fv,gs=function(){var i,e;for(Kr&&(i=No.domain)&&i.exit();e=vs.get();)try{e()}catch(t){throw vs.head&&oi(),t}i&&i.enter()};!Uv&&!Kr&&!Hv&&Bo&&Mo?(Jr=!0,Xr=Mo.createTextNode(""),new Bo(gs).observe(Xr,{characterData:!0}),oi=function(){Xr.data=Jr=!Jr}):!Vv&&ps&&ps.resolve?(ms=ps.resolve(void 0),ms.constructor=ps,Uo=Oo(ms.then,ms),oi=function(){Uo(gs)}):Kr?oi=function(){No.nextTick(gs)}:(Qr=Oo(Qr,qt),oi=function(){Qr(gs)}),Ca=function(i){vs.head||oi(),vs.add(i)}}var Gv=Ca,Yv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},hn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},jv=we,$i=jv.Promise,_u=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",qv=_u,zv=ir,Wv=!qv&&!zv&&typeof window=="object"&&typeof document=="object",Qv=we,Oi=$i,Kv=Ee,Jv=Xd,Xv=mu,Zv=Pe,eg=Wv,tg=_u,Zr=Md,Vo=Oi&&Oi.prototype,ig=Zv("species"),La=!1,ku=Kv(Qv.PromiseRejectionEvent),sg=Jv("Promise",function(){var i=Xv(Oi),e=i!==String(Oi);if(!e&&Zr===66||!(Vo.catch&&Vo.finally))return!0;if(!Zr||Zr<51||!/native code/.test(i)){var t=new Oi(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[ig]=s,La=t.then(function(){})instanceof s,!La)return!0}return!e&&(eg||tg)&&!ku}),Ki={CONSTRUCTOR:sg,REJECTION_EVENT:ku,SUBCLASSING:La},Ai={},Ho=Kt,rg=TypeError,ag=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw rg("Bad Promise constructor");e=s,t=r}),this.resolve=Ho(e),this.reject=Ho(t)};Ai.f=function(i){return new ag(i)};var ng=et,Fs=ir,Rt=we,Ji=Fe,og=nn,dg=dn,ug=Qm,lg=Kt,xa=Ee,cg=gt,hg=Xm,fg=yu,Pu=$u.set,fn=Gv,pg=Yv,mg=hn,vg=wu,Du=jd,Oa=$i,pn=Ki,Ru=Ai,sr="Promise",Iu=pn.CONSTRUCTOR,gg=pn.REJECTION_EVENT;pn.SUBCLASSING;var ea=Du.getterFor(sr),Sg=Du.set,bg=Oa&&Oa.prototype,fi=Oa,ta=bg,Cu=Rt.TypeError,Ba=Rt.document,mn=Rt.process,Ma=Ru.f,yg=Ma,Tg=!!(Ba&&Ba.createEvent&&Rt.dispatchEvent),Lu="unhandledrejection",Eg="rejectionhandled",Go=0,xu=1,$g=2,vn=1,Ou=2,Ss,Yo,Ag,Bu=function(i){var e;return cg(i)&&xa(e=i.then)?e:!1},Mu=function(i,e){var t=e.value,s=e.state==xu,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===Ou&&_g(e),e.rejection=vn),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(Cu("Promise-chain cycle")):(d=Bu(u))?Ji(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Nu=function(i,e){i.notified||(i.notified=!0,fn(function(){for(var t=i.reactions,s;s=t.get();)Mu(s,i);i.notified=!1,e&&!i.rejection&&wg(i)}))},Fu=function(i,e,t){var s,r;Tg?(s=Ba.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Rt.dispatchEvent(s)):s={promise:e,reason:t},!gg&&(r=Rt["on"+i])?r(s):i===Lu&&pg("Unhandled promise rejection",t)},wg=function(i){Ji(Pu,Rt,function(){var e=i.facade,t=i.value,s=jo(i),r;if(s&&(r=mg(function(){Fs?mn.emit("unhandledRejection",t,e):Fu(Lu,e,t)}),i.rejection=Fs||jo(i)?Ou:vn,r.error))throw r.value})},jo=function(i){return i.rejection!==vn&&!i.parent},_g=function(i){Ji(Pu,Rt,function(){var e=i.facade;Fs?mn.emit("rejectionHandled",e):Fu(Eg,e,i.value)})},pi=function(i,e,t){return function(s){i(e,s,t)}},vi=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=$g,Nu(i,!0))},Na=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Cu("Promise can't be resolved itself");var s=Bu(e);s?fn(function(){var r={done:!1};try{Ji(s,e,pi(Na,r,i),pi(vi,r,i))}catch(a){vi(r,a,i)}}):(i.value=e,i.state=xu,Nu(i,!1))}catch(r){vi({done:!1},r,i)}}};Iu&&(fi=function(e){hg(this,ta),lg(e),Ji(Ss,this);var t=ea(this);try{e(pi(Na,t),pi(vi,t))}catch(s){vi(t,s)}},ta=fi.prototype,Ss=function(e){Sg(this,{type:sr,done:!1,notified:!1,parent:!1,reactions:new vg,rejection:!1,state:Go,value:void 0})},Ss.prototype=og(ta,"then",function(e,t){var s=ea(this),r=Ma(fg(this,fi));return s.parent=!0,r.ok=xa(e)?e:!0,r.fail=xa(t)&&t,r.domain=Fs?mn.domain:void 0,s.state==Go?s.reactions.add(r):fn(function(){Mu(r,s)}),r.promise}),Yo=function(){var i=new Ss,e=ea(i);this.promise=i,this.resolve=pi(Na,e),this.reject=pi(vi,e)},Ru.f=Ma=function(i){return i===fi||i===Ag?new Yo(i):yg(i)});ng({global:!0,constructor:!0,wrap:!0,forced:Iu},{Promise:fi});dg(fi,sr,!1,!0);ug(sr);var kg=Pe,Uu=kg("iterator"),Vu=!1;try{var Pg=0,qo={next:function(){return{done:!!Pg++}},return:function(){Vu=!0}};qo[Uu]=function(){return this},Array.from(qo,function(){throw 2})}catch(i){}var Dg=function(i,e){if(!e&&!Vu)return!1;var t=!1;try{var s={};s[Uu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Rg=$i,Ig=Dg,Cg=Ki.CONSTRUCTOR,Hu=Cg||!Ig(function(i){Rg.all(i).then(void 0,function(){})}),Lg=et,xg=Fe,Og=Kt,Bg=Ai,Mg=hn,Ng=un,Fg=Hu;Lg({target:"Promise",stat:!0,forced:Fg},{all:function(e){var t=this,s=Bg.f(t),r=s.resolve,a=s.reject,n=Mg(function(){var o=Og(t.resolve),u=[],d=0,l=1;Ng(e,function(c){var h=d++,f=!1;l++,xg(o,t,c).then(function(m){f||(f=!0,u[h]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),s.promise}});var Ug=et,Vg=Ki.CONSTRUCTOR,zo=$i;zo&&zo.prototype;Ug({target:"Promise",proto:!0,forced:Vg,real:!0},{catch:function(i){return this.then(void 0,i)}});var Hg=et,Gg=Fe,Yg=Kt,jg=Ai,qg=hn,zg=un,Wg=Hu;Hg({target:"Promise",stat:!0,forced:Wg},{race:function(e){var t=this,s=jg.f(t),r=s.reject,a=qg(function(){var n=Yg(t.resolve);zg(e,function(o){Gg(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var Qg=et,Kg=Fe,Jg=Ai,Xg=Ki.CONSTRUCTOR;Qg({target:"Promise",stat:!0,forced:Xg},{reject:function(e){var t=Jg.f(this);return Kg(t.reject,void 0,e),t.promise}});var Zg=St,eS=gt,tS=Ai,Gu=function(i,e){if(Zg(i),eS(e)&&e.constructor===i)return e;var t=tS.f(i),s=t.resolve;return s(e),t.promise},iS=et,sS=Qt,rS=xc,aS=$i,nS=Ki.CONSTRUCTOR,oS=Gu,dS=sS("Promise"),uS=!nS;iS({target:"Promise",stat:!0,forced:rS},{resolve:function(e){return oS(uS&&this===dS?aS:this,e)}});var lS=et,Fa=$i,cS=je,hS=Qt,fS=Ee,pS=yu,Wo=Gu,mS=Fa&&Fa.prototype,vS=!!Fa&&cS(function(){mS.finally.call({then:function(){}},function(){})});lS({target:"Promise",proto:!0,real:!0,forced:vS},{finally:function(i){var e=pS(this,hS("Promise")),t=fS(i);return this.then(t?function(s){return Wo(e,i()).then(function(){return s})}:i,t?function(s){return Wo(e,i()).then(function(){throw s})}:i)}});var gS=Qt,gn=gS,SS=gn,bS=SS("Promise","finally"),yS=bS,TS=yS,ES=TS,$S=ES,rr=zs($S),Te;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Te||(Te={}));var ut=(i,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Te.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:G(t)}return i};const Qo=(i,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Te.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:G(e)}};var D=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class he{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||k(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const AS=i=>{switch(i){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return G(i)}};var j;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const wS=5,_S=5,kS=500,Ko=7e3;class PS{constructor(e){this.subscription=new ne,this.loadMediaTimeoutSubscription=new ne,this.videoState=new he(j.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===W.Requested&&s!==j.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case j.PLAYING:case j.PAUSED:case j.READY:break;case j.STOPPED:this.videoState.startTransitionTo(j.READY),this.prepare();break;default:G(s)}break}case p.PLAYING:{switch(s){case j.PLAYING:break;case j.PAUSED:this.videoState.startTransitionTo(j.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case j.READY:this.videoState.startTransitionTo(j.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case j.STOPPED:this.videoState.startTransitionTo(j.READY),this.prepare();break;default:G(s)}break}case p.PAUSED:{switch(s){case j.PLAYING:this.videoState.startTransitionTo(j.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case j.PAUSED:break;case j.READY:this.videoState.startTransitionTo(j.PAUSED),this.videoState.setState(j.PAUSED);break;case j.STOPPED:this.videoState.startTransitionTo(j.READY),this.prepare();break;default:G(s)}break}default:G(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(AS(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ne;this.subscription.add(e),this.subscription.add(H(this.videoState.stateChangeStarted$.pipe(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 L;e.add(r.pipe(Ye(kS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(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)>wS)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(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<_S&&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:G(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(j.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(j.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:W.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===j.PAUSED||e===j.PLAYING)&&(this.videoState.setState(j.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===j.PLAYING||e===j.PAUSED)&&(this.videoState.setState(j.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===j.READY&&this.videoState.setState(j.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()!==j.STOPPED&&this.videoState.setState(j.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=s[e];P(l);const c=kl(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=s[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=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=s[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=s[e];P(l),r=ut(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:O.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return G(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle: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 s=this.params.desiredState.seekState.getState();return s.state===W.Applying||s.state===W.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Pl(Ko).subscribe(()=>a(`timeout(${Ko})`)))});rr(Promise.race([t,s]).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:O.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var DS=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},RS=i=>{const e=new S(1/0),t=new L,s=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,m,b;const E=Qi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in E||"x-playback-duration-millis"in E){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),T=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=T!=null?T:v*1e3)!==null&&f!==void 0?f:NaN;k($)&&!isNaN($)&&e.next($)}const g=(m=E["x-delivery-type"])!==null&&m!==void 0?m:Ni.HTTP1,_=(b={1:!0,0:!1}[E["x-reused"]])!==null&&b!==void 0?b:void 0;s.next(g),r.next(_)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...b){return u(this),f(...b)},h.progress=function(...b){return d(this),m(...b)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},bi=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},IS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:bi}),!0),CS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Ze=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=re(r),d=new ne;return r&&d.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},Jt=(i,e,t)=>Ze(e,()=>i.loop,s=>{k(s)&&(i.loop=s)},{onError:t}),bt=(i,e,t,s)=>Ze(e,()=>({muted:i.muted,volume:i.volume}),r=>{k(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),Ct=(i,e,t,s)=>Ze(e,()=>i.playbackRate,r=>{k(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),LS=i=>["__",i.language,i.label].join("|"),xS=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class ct{constructor(){this.available$=new L,this.current$=new S(void 0),this.error$=new L,this.subscription=new ne,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:O.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ze(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(Ze(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(Ze(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(Ze(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(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(H(U(e,"addtrack"),U(e,"removetrack"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),me((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(U(e,"change"),Ne(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),w(s=>s&&this.htmlTextTrackToITextTrack(s).id),me()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.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=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ct.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:LS(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t)))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))k(e)&&xS(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){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"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Sn=i=>{i.removeAttribute("src"),i.load()},OS=i=>{try{i.pause(),i.playbackRate=0,Sn(i),i.remove()}catch(e){console.error(e)}};class BS{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 Ua=window.WeakMap?new WeakMap:new BS,yt=i=>{let e=i.querySelector("video");const t=!!e;return e?Sn(e):(e=document.createElement("video"),i.appendChild(e)),Ua.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Tt=i=>{const e=Ua.get(i);Ua.delete(i),e?Sn(i):OS(i)};class ar{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 Yu=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Jo=i=>{const e=Yu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},MS=i=>{const e=Yu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Va=3;class NS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Va&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||Va))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var ju=(i,e,t=Va)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const Et=i=>{const e=v=>U(i,v).pipe(Si(void 0)),s=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>U(i,v))).pipe(w(v=>v.type==="ended"?i.readyState<2:i.readyState<3),me()),r=H(U(i,"progress"),U(i,"timeupdate")).pipe(w(()=>ju(i.buffered,i.currentTime))),n=za().browser===_d.Safari?Ce({play:e("play").pipe(ge()),playing:e("playing")}).pipe(Si(void 0)):e("playing"),o=U(i,"volumechange").pipe(w(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe(w(()=>i.playbackRate)),d=U(i,"error").pipe(ee(()=>!!(i.error||i.played.length)),w(()=>{var v;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:O.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),l=U(i,"timeupdate").pipe(w(()=>i.currentTime)),c=new L,h=.3;let f;l.subscribe(v=>{i.loop&&k(f)&&k(v)&&f>=i.duration-h&&v<=h&&c.next(f),f=v});const m=U(i,"enterpictureinpicture"),b=U(i,"leavepictureinpicture"),E=new S(MS(i));m.subscribe(()=>E.next(!0)),b.subscribe(()=>E.next(!1));const g=new S(Jo(i));return U(i,"fullscreenchange").pipe(w(()=>Jo(i))).subscribe(g),{playing$:n,pause$:e("pause").pipe(ee(()=>!i.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$:U(i,"durationchange").pipe(w(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:E,inFullscreen$:g}},bn=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var FS=et,US=Zs,VS=an,HS=rn;FS({target:"Array",proto:!0},{at:function(e){var t=US(this),s=VS(t),r=HS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var GS=gn,YS=GS("Array","at"),jS=YS,qS=jS,zS=qS,WS=zS,ht=zs(WS);let yn=!1,ft={};const QS=i=>{yn=i},KS=()=>{ft={}},JS=i=>{i(ft)},bs=(i,e)=>{var t;yn&&(ft.meta=(t=ft.meta)!==null&&t!==void 0?t:{},ft.meta[i]=e)};class nt{constructor(e){this.name=e}next(e){var t,s;if(!yn)return;ft.series=(t=ft.series)!==null&&t!==void 0?t:{};const r=(s=ft.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ft.series[this.name]=r}}var Yt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(Yt||(Yt={}));const XS=new nt("best_bitrate"),ZS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class eb{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const wi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,b,E;const g=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,_=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*s.containerSizeFactor,height:e.height*g*s.containerSizeFactor},v=_&&zt(_),T=s.considerPlaybackRate&&k(o)?o:1,$=i.filter(M=>!Mi(M.quality)).sort((M,C)=>Ps(M.quality,C.quality)?-1:1),R=(f=ht($,-1))===null||f===void 0?void 0:f.quality,V=(m=ht($,0))===null||m===void 0?void 0:m.quality,K=re(r)||k(r.min)&&k(r.max)&&Ds(r.max,r.min)||k(r.min)&&V&&Ps(r.min,V)||k(r.max)&&R&&Ds(r.max,R),F=T*ZS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y={},x=$.filter(M=>(v?Ds(M.quality,v):!0)?(k(t)&&isFinite(t)&&k(M.bitrate)?t-a>=M.bitrate*F:!0)?s.lazyQualitySwitch&&k(s.minBufferToSwitchUp)&&u&&!Mi(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Ps(M.quality,u.quality)?(Y[M.quality]=Yt.Buffer,!1):!!l&&ba(M.quality,l)?(Y[M.quality]=Yt.DroppedFramesLimit,!1):K||(re(r.max)||kd(M.quality,r.max))&&(re(r.min)||ba(M.quality,r.min))?!0:(Y[M.quality]=Yt.FitsQualityLimits,!1):(Y[M.quality]=Yt.FitsThroughput,!1):(Y[M.quality]=Yt.FitsContainer,!1))[0];x&&x.bitrate&&XS.next(x.bitrate);const B=(b=x!=null?x:$[Math.ceil(($.length-1)/2)])!==null&&b!==void 0?b:i[0];B.quality!==((E=d==null?void 0:d.last)===null||E===void 0?void 0:E.quality)&&c({message:`
|
|
7
|
+
[available tracks] ${i.map(M=>M.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
10
|
-
containerQualityLimit: ${
|
|
10
|
+
containerQualityLimit: ${v},
|
|
11
11
|
throughput: ${t},
|
|
12
12
|
reserve: ${a},
|
|
13
|
-
bitrateFactor: ${
|
|
13
|
+
bitrateFactor: ${F},
|
|
14
14
|
forwardBufferHealth: ${n},
|
|
15
15
|
minBufferToSwitchUp: ${s.minBufferToSwitchUp},
|
|
16
16
|
droppedVideoMaxQualityLimit: ${l},
|
|
17
|
-
limitsAreInvalid: ${
|
|
17
|
+
limitsAreInvalid: ${K},
|
|
18
18
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
19
19
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
20
20
|
|
|
21
21
|
[limited tracks]
|
|
22
|
-
${Object.entries(Y).map(([
|
|
22
|
+
${Object.entries(Y).map(([M,C])=>`${M}: ${C}`).join(`
|
|
23
23
|
`)||"All tracks are available"}
|
|
24
24
|
|
|
25
|
-
[best track] ${
|
|
26
|
-
[selected track] ${
|
|
27
|
-
`});const
|
|
28
|
-
[last selected] ${
|
|
29
|
-
`}),F}return d==null||d.recordSwitch(H),H};var De=i=>new URL(i).hostname;const KS=300,Bs=(i,e=KS)=>new Hs(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,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(i),()=>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&&!xi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(U(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(Ye(this.droppedFramesChecker.checkTime)),s=G(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>ws(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const _i={};var Q;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const ye=(i,e)=>new Hs(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});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(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&t!==Q.STOPPED&&s!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case p.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:V(t)}break}case p.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:V(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:V(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),R(this.params.desiredState.playbackState,p.PAUSED);break;case Q.STOPPED:this.prepare();break;default:V(t)}break}default:V(s)}},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(De(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},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);er(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(_i.MediaPlayer=r.MediaPlayer,_i.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(_i.MediaPlayer,"dashjs not loaded"),P(_i.Debug,"dashjs not loaded"),this.player=_i.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,s=m=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,y)=>this.subscription.add(m.subscribe(y,s));r(Bs(this.video),this.elementSize$),r(ye(this.player,"error").pipe(w(m=>{const y=typeof m.error=="object"?m.error.code:m.error,A=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${y}`,message:A}})),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 y;return(y=this.videoTracks$.getValue().find(({bitrateInfo:A})=>A.qualityIndex===m))===null||y===void 0?void 0:y.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,y;const A=this.player.getQualityFor("video");return(y=(m=this.videoTracks$.getValue().find(({bitrateInfo:D})=>D.qualityIndex===A))===null||m===void 0?void 0:m.track)===null||y===void 0?void 0:y.id},m=>{var y;if(se(m))return;const A=(y=this.videoTracks$.getValue().find(({track:D})=>D.id===m))===null||y===void 0?void 0:y.bitrateInfo;A&&this.player.setQualityFor("video",A.qualityIndex)},{changed$:a.pipe(w(m=>m==null?void 0:m.id)),onError:s}))},s)),this.subscription.add(Je(t.autoVideoTrackSwitching,()=>{var m,y,A;return(A=(y=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||y===void 0?void 0:y.autoSwitchBitrate)===null||A===void 0?void 0:A.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),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:y}})=>{var A,D;const j=this.player.getDashMetrics(),X=j.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),N=(A=j.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&A!==void 0?A:Li.HTTP1,Y=(D={1:!0,0:!1}[X])!==null&&D!==void 0?D:void 0;this.params.output.httpConnectionType$.next(N),this.params.output.httpConnectionReused$.next(Y),e.hostname$.next(De(y))}),r(ye(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:y,availableFrom:A}}})=>{this.isLive$.next(y),this.availableFrom$.next(A.getTime()),y||e.duration$.next(m);const D=[],j=this.player.getQualityFor("video");let X;for(const N of this.player.getBitrateInfoListFor("video")){const Y=N.qualityIndex.toString(10),K=Vt(N),O=N.bitrate/1e3,H={width:N.width,height:N.height},ne=this.frameRatesByFrameHeight[N.height];if(K){const F={id:Y,quality:K,bitrate:O,size:H,fps:ne};D.push({track:F,bitrateInfo:N}),N.qualityIndex===j&&(X=F)}}this.videoTracks$.next(D),e.availableVideoTracks$.next(D.map(({track:N})=>N)),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 y=m.requestEndDate.getTime()-m.firstByteDate.getTime(),A=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(A,y)}),r(G(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(),y=mi(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}),A=t.autoVideoTrackLimits.getTransition();A&&e.autoVideoTrackLimits$.next(A.to);const D=this.videoTracks$.getValue().find(({track:j})=>j===y);D!=null&&D.bitrateInfo&&this.player.setQualityFor("video",D==null?void 0:D.bitrateInfo.qualityIndex,!1)}),r(Be({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(Be({availableFrom:this.availableFrom$.pipe(re(k)),currentTime:n}),({availableFrom:m,currentTime:y})=>this.params.output.liveTime$.next(m+y*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),R(t.playbackState,p.PLAYING)}),r(ye(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(ye(this.player,"playbackPaused"),()=>{this.videoState.setState(Q.PAUSED),R(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=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(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(Be({isLive:this.isLive$,isShort:e.duration$.pipe(w(m=>m<60))}),({isLive:m,isShort:y})=>{const A=!m&&y;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:A}}})}),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$,s))},s)),r(ye(this.player,"manifestLoaded"),m=>{var y,A,D,j,X,N,Y;if(!((A=(y=m.data)===null||y===void 0?void 0:y.Period)===null||A===void 0)&&A.AdaptationSet){const K=[];for(const O of(j=(D=m.data)===null||D===void 0?void 0:D.Period)===null||j===void 0?void 0:j.AdaptationSet)if(O.contentType==="text"){const H=(X=O.Representation)===null||X===void 0?void 0:X.id,ne=new URL((N=O.Representation)===null||N===void 0?void 0:N.BaseURL,(Y=m.data)===null||Y===void 0?void 0:Y.baseUri).toString(),F="internal",I=O.lang;K.push({id:H,url:ne,type:F,language:I})}t.internalTextTracks.startTransitionTo(K)}}),this.subscription.add(jt(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:g,inFullscreen$:E,pause$:$,playing$:T}=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$:T,pause$:$,tracks$:this.videoTracks$.pipe(w(m=>m.map(({track:y})=>y)))}),this.subscription.add(gt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Rt(this.video,t.playbackRate,v,s)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(E.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),R(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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/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 Wi=i=>{switch(i){case"mobile":return Qe.Q_144P;case"lowest":return Qe.Q_240P;case"low":return Qe.Q_360P;case"sd":case"medium":return Qe.Q_480P;case"hd":case"high":return Qe.Q_720P;case"fullhd":case"full":return Qe.Q_1080P;case"quadhd":case"quad":return Qe.Q_1440P;case"ultrahd":case"ultra":return Qe.Q_2160P}};const qo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Dt=i=>ue(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!qo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return qo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function ke(){return me()}function Fu(i){return ke()-i}function zo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function JS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Ds(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,g=2e3,E=()=>{if(u)return;P(l);const O=Fu(l);let H;if(O<g){H=g-O,setTimeout(E,H);return}g*=2,g>v&&(g=v),n&&n.abort(),n=new r,D()};const $=O=>(a=O,K),T=O=>(c=O,K),m=()=>(f="json",K),y=()=>{if(!u){if(--d>=0){E(),s&&s();return}u=!0,c&&c(),t&&t()}},A=O=>(h=O,K),D=()=>{l=ke(),n=new r,n.open("get",i);let O=0,H,ne=0;const F=()=>(P(l),Math.max(l,Math.max(H||0,ne||0)));if(a&&n.addEventListener("progress",I=>{const B=ke();a.updateChunk&&I.loaded>O&&(a.updateChunk(F(),I.loaded-O),O=I.loaded,H=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const B=n.response.byteLength-O;B&&a.updateChunk&&a.updateChunk(F(),B)}c&&c(),n&&e(n.response)}else y()}),n.addEventListener("error",()=>{y()}),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:$,withParallel:A,withJSONResponse:m,withRetryCount:O=>(d=O,K),withRetryInterval:(O,H)=>(k(O)&&(g=O),k(H)&&(v=H),K),withTimeout:O=>(o=O,K),withFinally:T,send:D,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,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-eb;if(t-e>ZS){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>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,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=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()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ms=1e4,gs=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 s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||k(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{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(gs,ms,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const y=a&&(!l||l===this.rep);return y||t("Not running!"),y},h=(y,A,D)=>{u&&u.abort(),u=Ds(this.urlResolver.resolve(y,!1),A,D,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(gs).withFinally(()=>{u=null}).send()},f=(y,A,D)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),A,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=y=>{const A=s.playbackRate;s.playbackRate!==y&&(t(`Playback rate switch: ${A}=>${y}`),s.playbackRate=y)},g=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),E()},E=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const D=ke()-1e4;let j=0;for(let N=0;N<this.bufferStates.length;N++){const Y=this.bufferStates[N];y=Math.min(y,Y.buf),Y.ts<D&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${y} drop=${j} jitter=${this.sourceJitter}`);let X=y-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)}},$=y=>{let A;const D=()=>A&&A.start?A.start.length:0,j=I=>A.start[I]/1e3,X=I=>A.dur[I]/1e3,N=I=>A.fragIndex+I,Y=(I,B)=>({chunkIdx:N(I),startTS:j(I),dur:X(I),discontinuity:B}),K=()=>{let I=0;if(A&&A.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=B;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let Se=A.dur.length-1;for(;Se>=0&&(pe-=A.dur[Se],!(pe<=0));--Se);I=Math.min(Se,A.dur.length-1-Z),I=Math.max(I,0)}return Y(I,!0)},O=I=>{const B=D();if(!(B<=0)){if(k(I)){for(let Z=0;Z<B;Z++)if(j(Z)>I)return Y(Z)}return K()}},H=I=>{const B=D(),Z=I?I.chunkIdx+1:0,pe=Z-A.fragIndex;if(!(B<=0)){if(!I||pe<0||pe-B>nb)return t(`Resync: offset=${pe} bChunks=${B} chunk=`+JSON.stringify(I)),K();if(!(pe>=B))return Y(Z-A.fragIndex,!1)}},ne=(I,B,Z)=>{d&&d.abort(),d=Ds(this.urlResolver.resolve(I,!0,this.lowLatency),B,Z,()=>this._retryCallback()).withTimeout(ms).withRetryCount(gs).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,B)=>{ne(y,Z=>{if(!c())return;A=Z;const pe=!!A.lowLatency;pe!==this.lowLatency&&g(pe);let Se=0;for(let Ie=0;Ie<A.dur.length;++Ie)Se+=A.dur[Ie];Se>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,I(O(B))},()=>this._handleNetworkError())},nextChunk:H}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{const{videoElement:A,logger:D}=this.params;let j=$(e.jidxUrl),X,N,Y,K,O=0,H,ne,F;const I=()=>{H&&(clearTimeout(H),H=void 0);const ee=Math.max(db,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Re=O+ee,Ue=ke(),Ce=Math.min(1e4,Re-Ue);O=Ue;const Ve=()=>{d||c()&&j.seek(()=>{c()&&(O=ke(),B(),I())})};Ce>0?H=window.setTimeout(()=>{this.paused?I():Ve()},Ce):Ve()},B=()=>{let ee;for(;ee=j.nextChunk(K);)K=ee,Ze(ee);const Re=j.nextChunk(Y);if(Re){if(Y&&Re.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?I():(T(),this._initPlayerWith(e));return}Ie(Re)}else I()},Z=(ee,Re)=>{if(!c()||!this.sourceBuffer)return;let Ue,Ce,Ve;const qt=It=>{window.setTimeout(()=>{c()&&Z(ee,Re)},It)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),qt(100);else{const It=ke(),zt=A.currentTime;!this.paused&&A.buffered.length>1&&ne===zt&&It-F>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),ne!==zt&&(ne=zt,F=It);const Wt=this._getBufferSizeSec();if(Wt>30)D(`Buffered ${Wt} seconds; delaying appendBuffer`),qt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:It,buf:Wt}),E(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Re&&Re()}catch(Ki){if(Ki.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Ue=this.sourceBuffer.buffered.start(0),Ce=zt,Ce-Ue>4&&this.sourceBuffer.remove(Ue,Ce-3)),qt(1e3);else throw Ki}}},pe=()=>{N&&X&&(D([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(Y)]),Z(N,function(){N=null,B()}))},Se=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ie=ee=>{c()&&f(Se(ee),(Re,Ue)=>{if(c()){if(Ue/=1e3,N=Re,Y=ee,n=ee.startTS,Ue){const Ce=Math.min(10,ee.dur/Ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ce:Ce}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,!se(y)||ee.startTS>y?Ie(ee):(Y=ee,B())}},y),e.cachedHeader?Tt(e.cachedHeader):h(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=ke();if(this.chunkRateEstimator.addInterval(h,v,f)){const E=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:E}),!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;s(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,s){this.manifestRequest=Ds(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).withRetryCount(gs).withRetryInterval(sb,rb).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Dt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,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}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ab))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.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=Wi(c.name))!==null&&n!==void 0?n:Vt(c.video),v=c.bitrate/1e3,g=Object.assign({},c.video);if(!f)continue;const E={id:h,quality:f,bitrate:v,size:g};l.push({track:E,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 V(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})};G(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(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===W.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Be({zeroTime:this.zeroTime$.pipe(re(k)),position:s.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,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Rt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&$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 V(r.to)}},t)).add(G(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(Ye(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,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&k(u)?u:(a=mi(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 s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===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=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?Li.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},_t=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const fb=i=>{const e=document.createElement("a");return e.href=i,e.origin},pb=i=>{const e=document.createElement("a");return e.href=i,e.host};class Vu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=ji(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 s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(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(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let 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+"-"+s;this._params.requestQuic&&(v=li(v)),this._lastXhr=new Vu(v,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const E=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:E,speed:8*g.length/(E/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 E=Date.now()-c;h>=100*1024&&E>=1e3&&(this._params.onBandwidthChange({size:h,duration:E,speed:8*h/(E/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,E,$)=>this._params.onError(g,E,$))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class 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)?)?$/,s=(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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=li(s)),new Vu(s,t,r=>{this.attachManifest(r,t,fb(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(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,E,$,T,m,y,A,D,j,X,N,Y,K,O;const H=d.getElementsByTagName("SegmentBase")[0],ne=H&&n(H,"indexRange").split("-"),F=H&&H.getElementsByTagName("Initialization")[0],I=F&&n(F,"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=(s?s+"/":"")+((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 B=.1,Z=Number((E=d.attributes.getNamedItem("bandwidth"))===null||E===void 0?void 0:E.value),pe=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Se;const Ie=(T=($=d.attributes.getNamedItem("frameRate"))===null||$===void 0?void 0:$.value)!==null&&T!==void 0?T:void 0;Se=Ie?cn(Ie):void 0,o.push({width:Number((m=d.attributes.getNamedItem("width"))===null||m===void 0?void 0:m.value),height:Number((y=d.attributes.getNamedItem("height"))===null||y===void 0?void 0:y.value),bandwidth:Z,baseURL:pe,failoverHosts:t,indexFrom:Number(ne[0]),indexTo:Number(ne[1]),initFrom:Number(I[0]),initTo:Number(I[1]),codecs:(D=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&D!==void 0?D: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:B*Z/8,bufferLength:B,name:(Y=(N=d.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.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 s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let 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()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,a;const n=()=>{const 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=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ns({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,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||se(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var J;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const 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:s})=>{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&&Wi(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)),(s==null?void 0:s.length)>0){const u=[];for(const d of s){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 s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!s)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?R(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(J.PAUSED),R(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&&R(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&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),G(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${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(De(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:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category: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,s=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,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{se(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$,s)),this.subscription.add(jt(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),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)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(J.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(G(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$,U(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(),E=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let $;if(!E&&k(f))$=f;else{const T=_t(this.video.buffered,this.video.currentTime*1e3),m=E?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,y=Math.min(T/m,1);$=(u=mi(c.map(({track:D})=>D),{container:g,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:y,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:D})=>D===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 A=t.autoVideoTrackLimits.getTransition();A&&e.autoVideoTrackLimits$.next(A.to)}return k($)?(d=c.find(({track:T})=>T.id===$))===null||d===void 0?void 0:d.representation:void 0}),ve()).subscribe(this.currentRepresentation$,s)).add(Be({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),s)).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(De(o.baseURL)))},s)).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,s)).add(this.dashLiteEvents.representationPlay$.pipe(re(k)).subscribe(this.handleRepresentationPlay,s)).add(G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0)).subscribe(this.syncPlayback,s))}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 V(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),R(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(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Ae||(Ae={}));var Fs;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Fs||(Fs={}));var Ge;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ge||(Ge={}));var te;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(te||(te={}));var ci;(function(i){i.MP4="mp4",i.WEBM="webm"})(ci||(ci={}));var Us;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Us||(Us={}));var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));class Wo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class 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 s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Gu.prototype[Symbol.toStringTag]="AbortController",Hu.prototype[Symbol.toStringTag]="AbortSignal");function Yu(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Sb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Yu({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(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,Bi=sr?ju.fetch:window.fetch;sr?ju.Request:window.Request;const di=sr?Gu:window.AbortController;var Ma=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const bb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},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(i){console.error(i)}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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ue(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ue(this,void 0,void 0,function*(){return new Promise(t=>{let s;qu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category: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:V(t)}}}var Ko=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.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 s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class $b extends ut{parseChildrenBoxes(){return gi(this.content)}}class Ab extends ut{constructor(e){super(e),this.data=this.content}}class Qi extends ut{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _b extends Qi{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class wb extends ut{parseChildrenBoxes(){return gi(this.content)}}class kb extends ut{parseChildrenBoxes(){return gi(this.content)}}var Ft;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ft||(Ft={}));class Pb extends Qi{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 Qi{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Db extends Qi{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 gi(this.content)}}class Cb extends Qi{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 gi(this.content)}}class Lb extends ut{parseChildrenBoxes(){return gi(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 s=Ob[e];return s?new s(t):new zu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return rr.createBox(s,new DataView(e.buffer,e.byteOffset))}}const rr=new Mb;function Ri(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const a=t.decode(new DataView(i.buffer,s,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+o>i.byteLength?null:rr.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function Bb(i,e){const t=[];let s=0;for(;s<i.byteLength;){const r=Ri(new DataView(i.buffer,i.byteOffset+s,i.byteLength-s),e);if(r)t.push(r),s+=r.size+r.source.byteOffset;else break}return t}function gi(i){const e=[];let t=0;for(;t<i.byteLength;){const s=rr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Nb=new TextDecoder("ascii"),Fb=i=>Nb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Ub=i=>{const e=rr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:te.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Vb=i=>{const e=Bb(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},Hb=i=>{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(Ri(i,"sv3d")){e.is3dVideo=!0;const s=Ri(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=Ri(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Ri(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Gb={validateData:Fb,parseInit:Hb,getIndexRange:()=>{},parseSegments:Ub,parseFeedableSegmentChunk:Vb};var _;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(_||(_={}));var C;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(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=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Vs(i,t),r=s in Jo,a=r?Jo[s].type:C.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,l=Vs(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Vs=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},rt=(i,e)=>{switch(e){case C.SignedInteger:return i.getInt8(0);case C.UnsignedInteger:return Vs(i);case C.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(i);case C.UTF8:return new TextDecoder("utf-8").decode(i);case C.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case C.Master:return i;case C.Binary:return i;default:V(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Wu(s);if(!e(r))return;r.type===C.Master&&hi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Yb=i=>{if(i.getUint32(0)!==_.EBML)return!1;let e,t,s;const r=Wu(i);return hi(r.value,({tag:a,type:n,value:o})=>(a===_.EBMLReadVersion?e=rt(o,n):a===_.DocType?t=rt(o,n):a===_.DocTypeReadVersion&&(s=rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=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=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return hi(i,({tag:h,type:f,value:v,valueSize:g})=>{if(h===_.SeekID){const E=rt(v,f);d=Vs(E)}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?s=rt(v,f):h===_.Duration?r=rt(v,f):h===_.SeekPosition&&d===_.Cues?u=rt(v,f):h===_.Tracks?hi(v,({tag:E,type:$,value:T})=>E===_.ProjectionType?(l=rt(T,$)===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"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zb=i=>{if(se(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wb=(i,e)=>{let t=!1,s=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return hi(i,({tag:o,type: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)&&(s=!0)}return!(t&&s)}),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=i=>{let e=0,t=!1;try{hi(i,s=>s.tag===_.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):jb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[_.SimpleBlock,_.BlockGroup,_.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Kb={validateData:Yb,parseInit:qb,getIndexRange:zb,parseSegments:Wb,parseFeedableSegmentChunk:Qb},Ku=1e4,Jb=3e4,Xb=5e3,Zb=Ku,ey=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Wi(a):void 0)!==null&&n!==void 0?n:Vt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},ty=({id:i,bitrate:e})=>({id:i,bitrate:e}),iy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=it(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:it(i,-1)},sy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Ss=i=>{const e=[];let t=0,s=i.length-1;for(;t<Ku&&s>=0;)e.unshift(i[s]),t+=i[s].time.to-i[s].time.from,s--;return e};class Xo{constructor(e,t,s,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=Le(this.destroyAbortController.signal,function(l){return Oe(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(U(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(U(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 E=Math.min(this.bufferLimit,Ko(this.sourceBuffer.buffered)*.8);this.bufferLimit=E,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=Le(this.destroyAbortController.signal,function(l){return Oe(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(se(f)||se(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=Le(this.destroyAbortController.signal,function(l){return Oe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield M(void 0);for(const E of this.representations.keys()){const $=l.find(y=>y.id===E);$&&this.representations.set(E,$);const T=this.representations.get(E);if(!T)return yield M(void 0);const m=Ss(T.segmentReference.segments);this.segments.set(T.id,m)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=Ss(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=s,s){case ci.MP4:this.containerParser=Gb;break;case ci.WEBM:this.containerParser=Kb;break;default:V(s)}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(se(e)||se(this.downloadingRepresentationId)||se(this.playingRepresentationId)||se(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.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(s,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(s,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;for(const r of e)r.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:r.time.from}),s=r.time.to;k(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,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 s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n)return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],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=Ss(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,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const g=h<=s&&f>=s,E=h>s||g||v===0&&s===0,$=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=s+$||f<=s+$;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&E&&T&&this.sourceBuffer&&!Ma(this.sourceBuffer.buffered,s))&&E&&T});if(r===-1)return[];if(t!==Ge.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,s="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ge.BYTE_RANGE:{r=t.segmentReference.url,a={from:it(e,0).byte.from,to:it(e,-1).byte.to};break}case Ge.TEMPLATE:{const d=it(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:V(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 Le(u,function(){return Oe(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:s}).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 s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(s=_t((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),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===Ge.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const E=f?h.byte.from-s:0,$=f?h.byte.to-s:e.byteLength,T=E<r,m=$<=r;if(h.status===te.DOWNLOADING&&T&&m){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const y=new DataView(e.buffer,e.byteOffset+E,v);this.sourceBufferTaskQueue.append(y,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(v,r-E),c.loadedBytes>c.feedingBytes)){const y=new DataView(e.buffer,e.byteOffset+E+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===v?y:this.containerParser.parseFeedableSegmentChunk(y);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(D=>{if(a.aborted)n();else if(D)c.fedBytes+=A.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 s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Qo(()=>er(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Le(this.destroyAbortController.signal,function(){return Oe(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?Ss(l):l),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ue(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||se(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&&s){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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Qo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(se(this.sourceBuffer)||se(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==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(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(ni||(ni={}));class ry{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!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=Le(this.abortAllController.signal,function(r){return Oe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield M(Bi(a,{signal:this.abortAllController.signal}).catch(wi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Le(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 Oe(this,arguments,function*(){let g=r;const E=new Headers;if(n)switch(a){case ni.HEADER:{E.append("Range",`bytes=${n.from}-${n.to}`);break}case ni.PARAM:{const B=new URL(g,location.href);B.searchParams.append("bytes",`${n.from}-${n.to}`),g=B.toString();break}default:V(a)}this.requestQuic&&(g=li(g));let $=this.abortAllController.signal,T;if(d){const B=new di;if(T=G(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{B.abort()}catch(Z){wi(Z)}}),this.abortAllController.signal.aborted||d.aborted)try{B.abort()}catch(Z){wi(Z)}$=B.signal}const m=me(),y=yield yield M(Bi(g,{priority:u,headers:E,signal:$}).catch(wi)),A=me();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(A-m),!y)return T==null||T.unsubscribe(),yield M(null);if(!y.ok||!y.body)return T==null||T.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`)));this.onHeadersReceived(y.headers);const D=parseInt((h=y.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!D){const B=yield yield M(y.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(B.byteLength,me()-A),o==null||o(new DataView(B),B.byteLength),T==null||T.unsubscribe(),yield M(B)}if(!o&&!l)return T==null||T.unsubscribe(),yield M(y.arrayBuffer());const[j,X]=y.body.tee(),N=j.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(X));let Y=0;const K=new ArrayBuffer(D),O=new Uint8Array(K),H=new DataView(K);let ne=!1;const F=B=>{T==null||T.unsubscribe(),ne=!0,wi(B)},I=Le($,function({done:B,value:Z}){return Oe(this,arguments,function*(){if(Y===0&&this.lastRequestFirstBytes$.next(me()-m),$.aborted)return T==null||T.unsubscribe(),yield M(void 0);!B&&Z&&(O.set(Z,Y),Y+=Z.byteLength,o==null||o(H,Y),yield yield M(N==null?void 0:N.read().then(I,F)))})}.bind(this));return yield yield M(N==null?void 0:N.read().then(I,F)),T==null||T.unsubscribe(),yield M(ne?null:K)})}.bind(this)),this.fetchByteRangeRepresentation=Le(this.abortAllController.signal,function(r,a,n){var o;return Oe(this,arguments,function*(){if(r.type!==Ge.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 E=new DataView(g,u-l,d-l+1);if(!a.validateData(E))throw new Error("Invalid media file");const $=a.parseInit(E),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange($);if(!T)throw new ReferenceError("No way to load representation index");let m;if(h)m=new DataView(g,T.from-l,T.to-T.from+1);else{const A=yield yield M(this.fetch(r.url,{range:T,priority:n,measureThroughput:!1}));if(!A)return yield M(null);m=new DataView(A)}const y=a.parseSegments(m,$,T);return yield M({init:$,dataView:new DataView(g),segments:y})})}.bind(this)),this.fetchTemplateRepresentation=Le(this.abortAllController.signal,function(r,a){return Oe(this,arguments,function*(){if(r.type!==Ge.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=s}onHeadersReceived(e){const{type:t,reused:s}=Uu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ge.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ge.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:V(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const wi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var ay=vt,ny=Fi,oy=Pe,dy=oy("match"),uy=function(i){var e;return ay(i)&&((e=i[dy])!==void 0?!!e:ny(i)=="RegExp")},ly=Yi,cy=String,hy=function(i){if(ly(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return cy(i)},fy=mt,py=function(){var i=fy(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},vy=Fe,my=ot,gy=js,Sy=py,Zo=RegExp.prototype,by=function(i){var e=i.flags;return e===void 0&&!("flags"in Zo)&&!my(i,"flags")&&gy(Zo,i)?vy(Sy,i):e},fn=qe,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(i,e,t,s,r,a){var n=t+i.length,o=s.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 i;case"`":return Xr(e,0,t);case"'":return Xr(e,n);case"<":c=r[Xr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ty(h/10);return f===0?d:f<=o?s[f-1]===void 0?Jr(l,1):s[f-1]+Jr(l,1):d}c=s[h-1]}return c===void 0?"":c})},wy=Xe,ky=Fe,pn=qe,ed=Ua,Py=Ee,Ry=Ui,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(i,e,t){return t>i.length?-1:e===""?t:Ju(i,e,t)};wy({target:"String",proto:!0},{replaceAll:function(e,t){var s=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,s,t);if(r)return By(ti(s),e,t)}for(o=ti(s),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=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Zr=(i,e)=>{let t=i;t=sd(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=sd(t,n,(o,u)=>se(a)?o:se(u)?a:a.padStart(parseInt(u,10),"0"))}return t},jy=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,v,g,E,$,T,m,y,A,D,j,X,N,Y,K,O,H,ne,F,I,B,Z,pe,Se,Ie,Ze,Tt,ee;const Ue=new DOMParser().parseFromString(i,"application/xml"),Ce={video:[],audio:[],text:[]},Ve=Ue.children[0],qt=Ve.getElementsByTagName("Period")[0],It=qt.children,zt=Ve.getAttribute("type")==="dynamic",Wt=Ve.getAttribute("availabilityStartTime"),Ki=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 ze=rd(mn);k(ze)&&(Ct=ze)}else gn&&(Ct=parseInt(gn,10));let al=0;const nr=(s=(t=Ve.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],nl=nr.includes(Fs.WEBM_AS_IN_FFMPEG)||nr.includes(Fs.WEBM_AS_IN_SPEC)?ci.WEBM:ci.MP4;for(const ze of It){const Ji=ze.getAttribute("mimeType"),ol=ze.getAttribute("codecs"),Sn=(r=ze.getAttribute("contentType"))!==null&&r!==void 0?r:Ji==null?void 0:Ji.split("/")[0],dl=(n=(a=ze.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],bn=ze.querySelectorAll("Representation"),ul=ze.querySelector("SegmentTemplate");if(Sn===Ae.TEXT){for(const be of bn){const xt=be.getAttribute("id")||"",Xi=ze.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();Ce[Ae.TEXT].push({id:xt,lang:Xi,kind:Ae.TEXT,url:or})}continue}for(const be of bn){const xt=(l=be.getAttribute("mimeType"))!==null&&l!==void 0?l:Ji,Xi=(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=(E=(g=ze.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&E!==void 0?E:[],ll=parseInt(($=be.getAttribute("width"))!==null&&$!==void 0?$:"",10),yn=parseInt((T=be.getAttribute("height"))!==null&&T!==void 0?T:"",10),Tn=parseInt((m=be.getAttribute("bandwidth"))!==null&&m!==void 0?m:"",10)/1e3,En=(y=be.getAttribute("frameRate"))!==null&&y!==void 0?y:"",cl=(A=be.getAttribute("quality"))!==null&&A!==void 0?A:void 0,hl=En?cn(En):void 0,fl=(D=be.getAttribute("id"))!==null&&D!==void 0?D:(al++).toString(10),pl=Qt==="video"?`${yn}p`:Qt==="audio"?`${Tn}Kbps`:Xi,vl=`${fl}@${pl}`,ml=(N=(X=(j=be.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||X===void 0?void 0:X.trim())!==null&&N!==void 0?N:"",$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 Si=(O=(K=be.querySelector("SegmentBase Initialization"))===null||K===void 0?void 0:K.getAttribute("range"))!==null&&O!==void 0?O:"",[bi,lr]=Si.split("-").map(Kt=>parseInt(Kt,10)),yi={from:bi,to:lr},Ti=(H=be.querySelector("SegmentBase"))===null||H===void 0?void 0:H.getAttribute("indexRange"),[cr,Zi]=Ti?Ti.split("-").map(Kt=>parseInt(Kt,10)):[],Ei=Ti?{from:cr,to:Zi}:void 0;dr={type:Ge.BYTE_RANGE,url:$n,initRange:yi,indexRange:Ei}}else if(Lt){const Si={representationId:(ne=be.getAttribute("id"))!==null&&ne!==void 0?ne:void 0,bandwidth:(F=be.getAttribute("bandwidth"))!==null&&F!==void 0?F:void 0},bi=parseInt((I=Lt.getAttribute("timescale"))!==null&&I!==void 0?I:"",10),lr=(B=Lt.getAttribute("initialization"))!==null&&B!==void 0?B:"",yi=Lt.getAttribute("media"),Ti=(pe=parseInt((Z=Lt.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&pe!==void 0?pe:1,cr=Zr(lr,Si);if(!yi)throw new ReferenceError("No media attribute in SegmentTemplate");const Zi=(Se=Lt.querySelectorAll("SegmentTimeline S"))!==null&&Se!==void 0?Se:[],Ei=[];let Kt=0;if(Zi.length){let hr=Ti,lt=0;for(const $i of Zi){const Et=parseInt((Ie=$i.getAttribute("d"))!==null&&Ie!==void 0?Ie:"",10),Ot=parseInt((Ze=$i.getAttribute("r"))!==null&&Ze!==void 0?Ze:"",10)||0,es=parseInt((Tt=$i.getAttribute("t"))!==null&&Tt!==void 0?Tt:"",10);lt=Number.isFinite(es)?es:lt;const fr=Et/bi*1e3,An=lt/bi*1e3;for(let ts=0;ts<Ot+1;ts++){const bl=Zr(yi,Object.assign(Object.assign({},Si),{segmentNumber:hr.toString(10),segmentTime:(lt+ts*Et).toString(10)})),_n=(An||0)+ts*fr,yl=_n+fr;hr++,Ei.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)/bi*1e3,$i=Math.ceil(Ct/lt);let Et=0;for(let Ot=1;Ot<$i;Ot++){const es=Zr(yi,Object.assign(Object.assign({},Si),{segmentNumber:Ot.toString(10),segmentTime:Et.toString(10)}));Ei.push({time:{from:Et,to:Et+lt},url:es}),Et+=lt}}dr={type:Ge.TEMPLATE,baseUrl:$n,initUrl:cr,totalSegmentsDurationMs:Kt,segments:Ei}}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&&Ce[ur].push({id:vl,kind:ur,segmentReference:dr,profiles:gl,duration:Ct,bitrate:Tn,mime:xt,codecs:Xi,width:ll,height:yn,fps:hl,quality:cl})}}return{dynamic:zt,liveAvailabilityStartTime:Ki,duration:Ct,container:nl,representations:Ce}},Ba=1e3,ad=["timeupdate","progress","play","seeked","stalled","waiting"];var He;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(He||(He={}));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(He.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=Le(this.destroyController.signal,function(t,s,r){var a;return Oe(this,arguments,function*(){this.element=t,this.manifestUrlString=nt(s,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(He.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(He.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Le(this.destroyController.signal,function(){var t;return Oe(this,arguments,function*(){const s=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(this.manifest);let r;try{r=jy(s!=null?s:"",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:ji(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Le(this.destroyController.signal,function(t,s){return Oe(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(He.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(s)&&(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(G(...ad.map(o=>U(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,E;return(E=(g=v.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&E!==void 0?E: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,E=l!==0&&u<c;if(E||g){const $=o-(c+h),T=Math.trunc(l+$/d);let m;u?T>0?m=T:m=0:m=l,this.manifestUrlString=nt(this.manifestUrlString,m,Te.DASH_CMAF_OFFSET_P)}(v||E||g)&&(yield this.updateLive(),o=0)})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({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(G(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield 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(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(He.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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,s,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((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){P(this.element),this.state$.setState(He.RUNNING),this.subscription.add(G(...ad.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(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 s={[Ae.VIDEO]:this.videoBufferManager,[Ae.AUDIO]:this.audioBufferManager,[Ae.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;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((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),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(He.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,s=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):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,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Qy=`#define GLSLIFY 1
|
|
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;}`,
|
|
25
|
+
[best track] ${x==null?void 0:x.quality}
|
|
26
|
+
[selected track] ${B==null?void 0:B.quality}
|
|
27
|
+
`});const te=B&&d&&d.history[B.id]&&le()-d.history[B.id]<=s.trackCooldown&&(!d.last||B.id!==d.last.id);if(B!=null&&B.id&&d&&!te&&d.recordSelection(B),te&&(d!=null&&d.last)){const M=d.last;return d==null||d.recordSwitch(M),c({message:`
|
|
28
|
+
[last selected] ${M==null?void 0:M.quality}
|
|
29
|
+
`}),M}return d==null||d.recordSwitch(B),B};var Le=i=>new URL(i).hostname;const tb=300,Us=(i,e=tb)=>new qs(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Ll(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(i),()=>a.disconnect()});class nr{constructor(){this.onDroopedVideoFramesLimit$=new L,this.subscription=new ne,this.playing=!1,this.tracks=[],this.forceChecker$=new L,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&&!Mi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(U(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Os(this.droppedFramesChecker.checkTime).pipe(ee(()=>this.playing),ee(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Ye(this.droppedFramesChecker.checkTime)),s=H(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Ds(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Di={};var Q;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const ye=(i,e)=>new qs(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class Xo{constructor(e){this.subscription=new ne,this.videoState=new he(Q.DOWNLOADING_LIB),this.textTracksManager=new ct,this.droppedFramesManager=new nr,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 ar,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&t!==Q.STOPPED&&s!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case p.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:G(t)}break}case p.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:G(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:G(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:G(t)}break}default:G(s)}},this.video=yt(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(Le(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:O.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);rr(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Di.MediaPlayer=r.MediaPlayer,Di.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(Di.MediaPlayer,"dashjs not loaded"),P(Di.Debug,"dashjs not loaded"),this.player=Di.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?bn(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&CS(this.player),DS(this.player),this.params.tuning.requestQuick&&IS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:O.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,T)=>this.subscription.add(v.subscribe(T,s));r(Us(this.video),this.elementSize$),r(ye(this.player,"error").pipe(w(v=>{const T=typeof v.error=="object"?v.error.code:v.error,$=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${T}`,message:$}})),e.error$),r(ye(this.player,"playbackError").pipe(w(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=ye(this.player,"qualityChangeRendered").pipe(ee(({mediaType:v})=>v==="video"),w(({newQuality:v})=>{var T;return(T=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===v))===null||T===void 0?void 0:T.track}));a.pipe(ee(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(ee(({to:v})=>v===Q.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(Ze(t.videoTrack,()=>{var v,T;const $=this.player.getQualityFor("video");return(T=(v=this.videoTracks$.getValue().find(({bitrateInfo:R})=>R.qualityIndex===$))===null||v===void 0?void 0:v.track)===null||T===void 0?void 0:T.id},v=>{var T;if(re(v))return;const $=(T=this.videoTracks$.getValue().find(({track:R})=>R.id===v))===null||T===void 0?void 0:T.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a.pipe(w(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(Ze(t.autoVideoTrackSwitching,()=>{var v,T,$;return($=(T=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||T===void 0?void 0:T.autoSwitchBitrate)===null||$===void 0?void 0:$.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(ye(this.player,"bufferStateChanged").pipe(ee(({mediaType:v})=>v==="video"),w(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(ye(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:T}})=>{var $,R;const V=this.player.getDashMetrics(),K=V.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),F=($=V.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&$!==void 0?$:Ni.HTTP1,Y=(R={1:!0,0:!1}[K])!==null&&R!==void 0?R:void 0;this.params.output.httpConnectionType$.next(F),this.params.output.httpConnectionReused$.next(Y),e.hostname$.next(Le(T))}),r(ye(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:T,availableFrom:$}}})=>{this.isLive$.next(T),this.availableFrom$.next($.getTime()),T||e.duration$.next(v);const R=[],V=this.player.getQualityFor("video");let K;for(const F of this.player.getBitrateInfoListFor("video")){const Y=F.qualityIndex.toString(10),J=zt(F),x=F.bitrate/1e3,B={width:F.width,height:F.height},te=this.frameRatesByFrameHeight[F.height];if(J){const M={id:Y,quality:J,bitrate:x,size:B,fps:te};R.push({track:M,bitrateInfo:F}),F.qualityIndex===V&&(K=M)}}this.videoTracks$.next(R),e.availableVideoTracks$.next(R.map(({track:F})=>F)),K&&e.currentVideoTrack$.next(K),this.videoState.setState(Q.STREAM_INITIALIZED),this.videoState.startTransitionTo(Q.READY)}),r(ye(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const T=v.requestEndDate.getTime()-v.firstByteDate.getTime(),$=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,T)}),r(H(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 v=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=wi(this.videoTracks$.getValue().map(({track:V})=>V),{container:this.elementSize$.getValue(),throughput:v,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:V})=>V===T);R!=null&&R.bitrateInfo&&this.player.setQualityFor("video",R==null?void 0:R.bitrateInfo.qualityIndex,!1)}),r(Ce({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(ee(k))}).pipe(ee(({isLive:v})=>v),w(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=ye(this.player,"playbackTimeUpdated").pipe(w(({time:v})=>v!=null?v:0));r(Ce({availableFrom:this.availableFrom$.pipe(ee(k)),currentTime:n}),({availableFrom:v,currentTime:T})=>this.params.output.liveTime$.next(v+T*1e3)),r(n.pipe(ee(()=>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(()=>ju(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 v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===Q.READY&&this.videoState.setState(Q.READY)}),r(this.isLive$,e.isLive$),r(Us(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=RS(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(Ce({isLive:this.isLive$,isShort:e.duration$.pipe(w(v=>v<60))}),({isLive:v,isShort:T})=>{const $=!v&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(ee(v=>v>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(),Si(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(ye(this.player,"manifestLoaded"),v=>{var T,$,R,V,K,F,Y;if(!(($=(T=v.data)===null||T===void 0?void 0:T.Period)===null||$===void 0)&&$.AdaptationSet){const J=[];for(const x of(V=(R=v.data)===null||R===void 0?void 0:R.Period)===null||V===void 0?void 0:V.AdaptationSet)if(x.contentType==="text"){const B=(K=x.Representation)===null||K===void 0?void 0:K.id,te=new URL((F=x.Representation)===null||F===void 0?void 0:F.BaseURL,(Y=v.data)===null||Y===void 0?void 0:Y.baseUri).toString(),M="internal",C=x.lang;J.push({id:B,url:te,type:M,language:C})}t.internalTextTracks.startTransitionTo(J)}}),this.subscription.add(Jt(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:b,inFullscreen$:E,pause$:g,playing$:_}=Et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:_,pause$:g,tracks$:this.videoTracks$.pipe(w(v=>v.map(({track:T})=>T)))}),this.subscription.add(bt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Ct(this.video,t.playbackRate,m,s)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(E.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=ut(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){}Tt(this.video),this.params.output.element$.next(void 0)}}var Xi=i=>{switch(i){case"mobile":return Je.Q_144P;case"lowest":return Je.Q_240P;case"low":return Je.Q_360P;case"sd":case"medium":return Je.Q_480P;case"hd":case"high":return Je.Q_720P;case"fullhd":case"full":return Je.Q_1080P;case"quadhd":case"quad":return Je.Q_1440P;case"ultrahd":case"ultra":return Je.Q_2160P}};const Zo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Lt=i=>ae(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Zo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return Zo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function ke(){return le()}function qu(i){return ke()-i}function ed(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ib(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Ls(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,b=2e3,E=()=>{if(u)return;P(l);const x=qu(l);let B;if(x<b){B=b-x,setTimeout(E,B);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,R()};const g=x=>(a=x,J),_=x=>(c=x,J),v=()=>(f="json",J),T=()=>{if(!u){if(--d>=0){E(),s&&s();return}u=!0,c&&c(),t&&t()}},$=x=>(h=x,J),R=()=>{l=ke(),n=new r,n.open("get",i);let x=0,B,te=0;const M=()=>(P(l),Math.max(l,Math.max(B||0,te||0)));if(a&&n.addEventListener("progress",C=>{const ie=ke();a.updateChunk&&C.loaded>x&&(a.updateChunk(M(),C.loaded-x),x=C.loaded,B=ie)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;P(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const ie=n.response.byteLength-x;ie&&a.updateChunk&&a.updateChunk(M(),ie)}c&&c(),n&&e(n.response)}else T()}),n.addEventListener("error",()=>{T()}),h){const C=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(te=ke(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),J},J={withBitrateReporting:g,withParallel:$,withJSONResponse:v,withRetryCount:x=>(d=x,J),withRetryInterval:(x,B)=>(k(x)&&(b=x),k(B)&&(m=B),J),withTimeout:x=>(o=x,J),withFinally:_,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return J}const sb=100,rb=2e3,ab=500;let nb=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-ab;if(t-e>rb){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>sb&&(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 ob{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=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()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ls(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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ys=1e4,Ts=3,db=300,ub=2e3,lb=6e4,cb=10,hb=1,fb=500;class pb{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 nb(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ed(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ed(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||k(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{ib(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 ob(Ts,ys,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const T=a&&(!l||l===this.rep);return T||t("Not running!"),T},h=(T,$,R)=>{u&&u.abort(),u=Ls(this.urlResolver.resolve(T,!1),$,R,()=>this._retryCallback()).withTimeout(ys).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ts).withFinally(()=>{u=null}).send()},f=(T,$,R)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),$,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=T=>{const $=s.playbackRate;s.playbackRate!==T&&(t(`Playback rate switch: ${$}=>${T}`),s.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),E()},E=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const R=ke()-1e4;let V=0;for(let F=0;F<this.bufferStates.length;F++){const Y=this.bufferStates[F];T=Math.min(T,Y.buf),Y.ts<R&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${T} drop=${V} jitter=${this.sourceJitter}`);let K=T-hb;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?m(1.15):K>1?m(1.1):K>.3?m(1.05):m(1)}},g=T=>{let $;const R=()=>$&&$.start?$.start.length:0,V=C=>$.start[C]/1e3,K=C=>$.dur[C]/1e3,F=C=>$.fragIndex+C,Y=(C,ie)=>({chunkIdx:F(C),startTS:V(C),dur:K(C),discontinuity:ie}),J=()=>{let C=0;if($&&$.dur){let ie=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=ie;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let Se=$.dur.length-1;for(;Se>=0&&(ve-=$.dur[Se],!(ve<=0));--Se);C=Math.min(Se,$.dur.length-1-oe),C=Math.max(C,0)}return Y(C,!0)},x=C=>{const ie=R();if(!(ie<=0)){if(k(C)){for(let oe=0;oe<ie;oe++)if(V(oe)>C)return Y(oe)}return J()}},B=C=>{const ie=R(),oe=C?C.chunkIdx+1:0,ve=oe-$.fragIndex;if(!(ie<=0)){if(!C||ve<0||ve-ie>cb)return t(`Resync: offset=${ve} bChunks=${ie} chunk=`+JSON.stringify(C)),J();if(!(ve>=ie))return Y(oe-$.fragIndex,!1)}},te=(C,ie,oe)=>{d&&d.abort(),d=Ls(this.urlResolver.resolve(C,!0,this.lowLatency),ie,oe,()=>this._retryCallback()).withTimeout(ys).withRetryCount(Ts).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(C,ie)=>{te(T,oe=>{if(!c())return;$=oe;const ve=!!$.lowLatency;ve!==this.lowLatency&&b(ve);let Se=0;for(let xe=0;xe<$.dur.length;++xe)Se+=$.dur[xe];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,C(x(ie))},()=>this._handleNetworkError())},nextChunk:B}},_=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:T=>{const{videoElement:$,logger:R}=this.params;let V=g(e.jidxUrl),K,F,Y,J,x=0,B,te,M;const C=()=>{B&&(clearTimeout(B),B=void 0);const Z=Math.max(fb,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),De=x+Z,Ue=ke(),Oe=Math.min(1e4,De-Ue);x=Ue;const Ve=()=>{d||c()&&V.seek(()=>{c()&&(x=ke(),ie(),C())})};Oe>0?B=window.setTimeout(()=>{this.paused?C():Ve()},Oe):Ve()},ie=()=>{let Z;for(;Z=V.nextChunk(J);)J=Z,tt(Z);const De=V.nextChunk(Y);if(De){if(Y&&De.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?C():(_(),this._initPlayerWith(e));return}xe(De)}else C()},oe=(Z,De)=>{if(!c()||!this.sourceBuffer)return;let Ue,Oe,Ve;const Xt=Ot=>{window.setTimeout(()=>{c()&&oe(Z,De)},Ot)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Xt(100);else{const Ot=ke(),Zt=$.currentTime;!this.paused&&$.buffered.length>1&&te===Zt&&Ot-M>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),te!==Zt&&(te=Zt,M=Ot);const ei=this._getBufferSizeSec();if(ei>30)R(`Buffered ${ei} seconds; delaying appendBuffer`),Xt(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:ei}),E(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),De&&De()}catch(Zi){if(Zi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Ue=this.sourceBuffer.buffered.start(0),Oe=Zt,Oe-Ue>4&&this.sourceBuffer.remove(Ue,Oe-3)),Xt(1e3);else throw Zi}}},ve=()=>{F&&K&&(R([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Y)]),oe(F,function(){F=null,ie()}))},Se=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),xe=Z=>{c()&&f(Se(Z),(De,Ue)=>{if(c()){if(Ue/=1e3,F=De,Y=Z,n=Z.startTS,Ue){const Oe=Math.min(10,Z.dur/Ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}ve()}},()=>this._handleNetworkError())},tt=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(Z),!1)))},At=Z=>{c()&&(e.cachedHeader=Z,oe(Z,()=>{K=!0,ve()}))};a=!0,V.seek(Z=>{if(c()){if(x=ke(),!Z){C();return}J=Z,!re(T)||Z.startTS>T?xe(Z):(Y=Z,ie())}},T),e.cachedHeader?At(e.cachedHeader):h(e.headerUrl,At,()=>this._handleNetworkError())},stop:_,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const m=ke();if(this.chunkRateEstimator.addInterval(h,m,f)){const E=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:E}),!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&&qu(n)<3e4)return;s(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,s){this.manifestRequest=Ls(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ys).withRetryCount(Ts).withRetryInterval(db,ub).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Lt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,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}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},lb))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const mb=[z.PAUSED,z.PLAYING,z.READY],vb=[z.PAUSED,z.PLAYING,z.READY];class gb{constructor(e){this.subscription=new ne,this.videoState=new he(z.STOPPED),this.representations$=new S([]),this.textTracksManager=new ct,this.droppedFramesManager=new nr,this.maxSeekBackTime$=new S(1/0),this.zeroTime$=new S(void 0),this.liveOffset=new ar,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:O.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=Xi(c.name))!==null&&n!==void 0?n:zt(c.video),m=c.bitrate/1e3,b=Object.assign({},c.video);if(!f)continue;const E={id:h,quality:f,bitrate:m,size:b};l.push({track:E,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(vb.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===W.Requested&&mb.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(ut(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 G(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.WTF,message:"DashLiveProvider internal logic error",thrown:r})};H(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=yt(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(Le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===W.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ce({zeroTime:this.zeroTime$.pipe(ee(k)),position:s.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(bt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Ct(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&Dl(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 G(r.to)}},t)).add(H(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(Ye(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),Tt(this.video)}createLiveDashPlayer(){const e=new pb({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),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=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&k(u)?u:(a=wi(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===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 m=(n=o.find(({track:b})=>b.id===l))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===z.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ut(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var zu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?Ni.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Pt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Sb=i=>{const e=document.createElement("a");return e.href=i,e.origin},bb=i=>{const e=document.createElement("a");return e.href=i,e.host};class Wu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=Qi(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 s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(bb(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 Vs{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=b=>{r(Vs._str2ua(b.substr(u))),u=b.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=bi(m)),this._lastXhr=new Wu(m,e.failoverHosts,b=>{this._lastXhr=void 0,f(b);const E=Date.now()-d;this._params.onBandwidthChange({size:b.length,duration:E,speed:8*b.length/(E/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),a==null||a()},b=>{if(b.length-u>o&&f(b),c===0){c=Date.now();return}h=b.length-l;const E=Date.now()-c;h>=100*1024&&E>=1e3&&(this._params.onBandwidthChange({size:h,duration:E,speed:8*h/(E/1e3)}),h=0,l=b.length,c=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},n,(b,E,g)=>this._params.onError(b,E,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Vs._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class yb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(o,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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=bi(s)),new Wu(s,t,r=>{this.attachManifest(r,t,Sb(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(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,m,b,E,g,_,v,T,$,R,V,K,F,Y,J,x;const B=d.getElementsByTagName("SegmentBase")[0],te=B&&n(B,"indexRange").split("-"),M=B&&B.getElementsByTagName("Initialization")[0],C=M&&n(M,"range").split("-");if(!C||!te){const tt=d.parentElement;if((tt==null?void 0:tt.getAttribute("contentType"))==="text"){const At=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(s?s+"/":"")+((m=(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||m===void 0?void 0:m.data),De=(b=tt.getAttribute("lang"))!==null&&b!==void 0?b:void 0;Z&&u.push({id:At,url:Z,language:De})}return}const ie=.1,oe=Number((E=d.attributes.getNamedItem("bandwidth"))===null||E===void 0?void 0:E.value),ve=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Se;const xe=(_=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&_!==void 0?_:void 0;Se=xe?bn(xe):void 0,o.push({width:Number((v=d.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((T=d.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(te[0]),indexTo:Number(te[1]),initFrom:Number(C[0]),initTo:Number(C[1]),codecs:(R=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&R!==void 0?R:void 0,mimeType:(K=(V=d.attributes.getNamedItem("mimeType"))===null||V===void 0?void 0:V.value)!==null&&K!==void 0?K:void 0,fps:Se,bufferSize:ie*oe/8,bufferLength:ie,name:(Y=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Y!==void 0?Y:void 0,id:(x=(J=d.attributes.getNamedItem("id"))===null||J===void 0?void 0:J.value)!==null&&x!==void 0?x: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 s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let 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),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,a;const n=()=>{const 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 m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Vs({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,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||re(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var X;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const Tb=[X.PAUSED,X.PLAYING];class Eb{constructor(e){this.videoState=new he(X.STOPPED),this.subscription=new ne,this.representations$=new S([]),this.currentRepresentation$=new S(void 0),this.textTracksManager=new ct,this.droppedFramesManager=new nr,this.elementSize$=new S(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,a,n;const o=[];for(const 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&&Xi(u.name))!==null&&n!==void 0?n:zt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const m={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:m,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(s==null?void 0:s.length)>0){const u=[];for(const d of s){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(X.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.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(X.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===W.Requested&&Tb.includes(t)&&this.seek(n.position,n.forcePrecise),t){case X.STOPPED:this.videoState.startTransitionTo(X.MANIFEST_LOADED),this.prepare();return;case X.MANIFEST_LOADED:this.videoState.startTransitionTo(X.INITIAL_REPRESENTATION_SELECTED);return;case X.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(X.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case X.METADATA_LOADED:this.videoState.startTransitionTo(X.READY),this.dash.updateRefsForCurrentTime();return;case X.READY:r===p.READY?D(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case X.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),H(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=yt(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(Le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new NS(this.video),this.dash=new yb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:O.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:O.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=Et(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{re(this.params.desiredState.seekState.getState().state!==W.Applying)&&(this.videoState.getState()===X.PLAYING||this.videoState.getState()===X.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Jt(this.video,t.isLooped,s)),this.subscription.add(bt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ct(this.video,t.playbackRate,a.playbackRateState$,s)),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(Us(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===X.READY&&this.videoState.setState(X.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),D(this.params.desiredState.playbackState,p.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(X.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:O.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(H(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(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(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),E=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!E&&k(f))g=f;else{const _=Pt(this.video.buffered,this.video.currentTime*1e3),v=E?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(_/v,1);g=(u=wi(c.map(({track:R})=>R),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,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(g)?(d=c.find(({track:_})=>_.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(Ce({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(ee(o=>o.to===X.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(ee(k))}).pipe(ge()).subscribe(()=>this.videoState.setState(X.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(ee(k),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Pt(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(Le(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=zu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),Si(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(ee(k)).subscribe(this.handleRepresentationPlay,s)).add(H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Tt(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 G(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Lt(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.DOM,thrown:e}))}}var Ae;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Ae||(Ae={}));var at;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(at||(at={}));var Hs;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Hs||(Hs={}));var Ge;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ge||(Ge={}));var q;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(q||(q={}));var yi;(function(i){i.MP4="mp4",i.WEBM="webm"})(yi||(yi={}));var Gs;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Gs||(Gs={}));var fe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(fe||(fe={}));class td{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Qu extends td{constructor(){super(),this.listeners||td.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 Ku=class{constructor(){Object.defineProperty(this,"signal",{value:new Qu,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ku.prototype[Symbol.toStringTag]="AbortController",Qu.prototype[Symbol.toStringTag]="AbortSignal");function Ju(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function $b(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Ju({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(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,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const or=Ju({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Xu=or?$b({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Vi=or?Xu.fetch:window.fetch;or?Xu.Request:window.Request;const gi=or?Ku:window.AbortController;var Ha=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Ab=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},wb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",id=wb?Ab:window.requestIdleCallback;var ia,sa;let Zu=!1;try{Zu=za().browser===_d.Safari&&parseInt((sa=(ia=navigator.userAgent.match(/Version\/(\d+)/))===null||ia===void 0?void 0:ia[1])!==null&&sa!==void 0?sa:"",10)<16}catch(i){console.error(i)}class _b{constructor(e){this.bufferFull$=new L,this.error$=new L,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:O.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ae(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ae(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ae(this,void 0,void 0,function*(){return new Promise(t=>{let s;Zu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:O.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:G(t)}}}var sd=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class ze{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 el extends ze{}class kb extends ze{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class Pb extends ze{parseChildrenBoxes(){return xt(this.content)}}class Db extends ze{parseChildrenBoxes(){return xt(this.content)}}class Rb extends ze{constructor(e){super(e),this.data=this.content}}class $t extends ze{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Ib extends $t{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class Cb extends ze{parseChildrenBoxes(){return xt(this.content)}}class Lb extends ze{parseChildrenBoxes(){return xt(this.content)}}var jt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(jt||(jt={}));class xb extends $t{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=jt.MONOSCOPIC;break;case 1:this.stereoMode=jt.TOP_BOTTOM;break;case 2:this.stereoMode=jt.LEFT_RIGHT;break;case 3:this.stereoMode=jt.STEREO_CUSTOM;break;case 4:this.stereoMode=jt.RIGHT_LEFT;break}this.cursor+=1}}class Ob extends $t{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Bb extends $t{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Mb extends ze{parseChildrenBoxes(){return xt(this.content)}}class Nb extends $t{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 Fb extends ze{parseChildrenBoxes(){return xt(this.content)}}class Ub extends ze{parseChildrenBoxes(){return xt(this.content)}}class Vb extends $t{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Hb extends ze{parseChildrenBoxes(){return xt(this.content)}}class Gb extends $t{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Yb extends $t{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class jb extends $t{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const qb={ftyp:kb,moov:Pb,moof:Db,mdat:Rb,sidx:Ib,trak:Cb,mdia:Mb,mfhd:Vb,tkhd:Nb,traf:Hb,tfhd:Gb,tfdt:Yb,trun:jb,minf:Fb,sv3d:Lb,st3d:xb,prhd:Ob,proj:Ub,equi:Bb,unknown:el};class zb{createBox(e,t){const s=qb[e];return s?new s(t):new el(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return dr.createBox(s,new DataView(e.buffer,e.byteOffset))}}const dr=new zb;function Li(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(n=>n.charCodeAt(0));let r=i.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===s[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+o>i.buffer.byteLength?null:dr.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function Ga(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=Li(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function xt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=dr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Wb=new TextDecoder("ascii"),Qb=i=>Wb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Kb=i=>{const e=dr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:q.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Jb=i=>{const e=Ga(i,"mdat"),t=Ga(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],a=s.source.byteOffset,o=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,a,o)},Xb=(i,e)=>{const t=Ga(i,"traf"),s=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=s.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Zb=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Gs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Li(i,"sv3d")){e.is3dVideo=!0;const s=Li(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=Li(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Li(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},ey={validateData:Qb,parseInit:Zb,getIndexRange:()=>{},parseSegments:Kb,parseFeedableSegmentChunk:Jb,getSegmentEndTime:Xb};var A;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(A||(A={}));var I;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(I||(I={}));const rd={[A.EBML]:{type:I.Master},[A.EBMLVersion]:{type:I.UnsignedInteger},[A.EBMLReadVersion]:{type:I.UnsignedInteger},[A.EBMLMaxIDLength]:{type:I.UnsignedInteger},[A.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[A.DocType]:{type:I.String},[A.DocTypeVersion]:{type:I.UnsignedInteger},[A.DocTypeReadVersion]:{type:I.UnsignedInteger},[A.Void]:{type:I.Binary},[A.Segment]:{type:I.Master},[A.SeekHead]:{type:I.Master},[A.Seek]:{type:I.Master},[A.SeekID]:{type:I.Binary},[A.SeekPosition]:{type:I.UnsignedInteger},[A.Info]:{type:I.Master},[A.TimestampScale]:{type:I.UnsignedInteger},[A.Duration]:{type:I.Float},[A.Tracks]:{type:I.Master},[A.TrackEntry]:{type:I.Master},[A.Video]:{type:I.Master},[A.Projection]:{type:I.Master},[A.ProjectionType]:{type:I.UnsignedInteger},[A.ProjectionPrivate]:{type:I.Master},[A.Chapters]:{type:I.Master},[A.Cluster]:{type:I.Master},[A.Timestamp]:{type:I.UnsignedInteger},[A.SilentTracks]:{type:I.Master},[A.SilentTrackNumber]:{type:I.UnsignedInteger},[A.Position]:{type:I.UnsignedInteger},[A.PrevSize]:{type:I.UnsignedInteger},[A.SimpleBlock]:{type:I.Binary},[A.BlockGroup]:{type:I.Master},[A.EncryptedBlock]:{type:I.Binary},[A.Attachments]:{type:I.Master},[A.Tags]:{type:I.Master},[A.Cues]:{type:I.Master},[A.CuePoint]:{type:I.Master},[A.CueTime]:{type:I.UnsignedInteger},[A.CueTrackPositions]:{type:I.Master},[A.CueTrack]:{type:I.UnsignedInteger},[A.CueClusterPosition]:{type:I.UnsignedInteger},[A.CueRelativePosition]:{type:I.UnsignedInteger},[A.CueDuration]:{type:I.UnsignedInteger},[A.CueBlockNumber]:{type:I.UnsignedInteger},[A.CueCodecState]:{type:I.UnsignedInteger},[A.CueReference]:{type:I.Master},[A.CueRefTime]:{type:I.UnsignedInteger}},tl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Ys(i,t),r=s in rd,a=r?rd[s].type:I.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,l=Ys(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ys=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(i,e)=>{switch(e){case I.SignedInteger:return i.getInt8(0);case I.UnsignedInteger:return Ys(i);case I.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(i);case I.UTF8:return new TextDecoder("utf-8").decode(i);case I.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case I.Master:return i;case I.Binary:return i;default:G(e)}},Ti=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=tl(s);if(!e(r))return;r.type===I.Master&&Ti(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},ty=i=>{if(i.getUint32(0)!==A.EBML)return!1;let e,t,s;const r=tl(i);return Ti(r.value,({tag:a,type:n,value:o})=>(a===A.EBMLReadVersion?e=ot(o,n):a===A.DocType?t=ot(o,n):a===A.DocTypeReadVersion&&(s=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},il=[A.Info,A.SeekHead,A.Tracks,A.TrackEntry,A.Video,A.Projection,A.ProjectionType,A.ProjectionPrivate,A.Chapters,A.Cluster,A.Cues,A.Attachments,A.Tags],iy=[A.Timestamp,A.SilentTracks,A.SilentTrackNumber,A.Position,A.PrevSize,A.SimpleBlock,A.BlockGroup,A.EncryptedBlock],sy=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return Ti(i,({tag:h,type:f,value:m,valueSize:b})=>{if(h===A.SeekID){const E=ot(m,f);d=Ys(E)}else h!==A.SeekPosition&&(d=void 0);return h===A.Segment?(e=m.byteOffset,t=m.byteOffset+b):h===A.Info?a=!0:h===A.SeekHead?n=!0:h===A.TimestampScale?s=ot(m,f):h===A.Duration?r=ot(m,f):h===A.SeekPosition&&d===A.Cues?u=ot(m,f):h===A.Tracks?Ti(m,({tag:E,type:g,value:_})=>E===A.ProjectionType?(l=ot(_,g)===1,!1):!0):a&&n&&il.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"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:Gs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ry=i=>{if(re(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ay=(i,e)=>{let t=!1,s=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return Ti(i,({tag:o,type:u,value:d})=>{switch(o){case A.Cues:t=!0;break;case A.CuePoint:n&&r(n)&&a.push(n),n={};break;case A.CueTime:n&&(n.time=ot(d,u));break;case A.CueTrackPositions:break;case A.CueClusterPosition:n&&(n.position=ot(d,u));break;default:t&&il.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:q.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}}})},ny=i=>{let e=0,t=!1;try{Ti(i,s=>s.tag===A.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):iy.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[A.SimpleBlock,A.BlockGroup,A.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},oy={validateData:ty,parseInit:sy,getIndexRange:ry,parseSegments:ay,parseFeedableSegmentChunk:ny};var dy=gt,uy=Gi,ly=Pe,cy=ly("match"),hy=function(i){var e;return dy(i)&&((e=i[cy])!==void 0?!!e:uy(i)=="RegExp")},fy=Wi,py=String,my=function(i){if(fy(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return py(i)},vy=St,gy=function(){var i=vy(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Sy=Fe,by=lt,yy=Qs,Ty=gy,ad=RegExp.prototype,Ey=function(i){var e=i.flags;return e===void 0&&!("flags"in ad)&&!by(i,"flags")&&yy(ad,i)?Sy(Ty,i):e},Tn=qe,$y=Zs,Ay=Math.floor,ra=Tn("".charAt),wy=Tn("".replace),aa=Tn("".slice),_y=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ky=/\$([$&'`]|\d{1,2})/g,Py=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=ky;return r!==void 0&&(r=$y(r),u=_y),wy(a,u,function(d,l){var c;switch(ra(l,0)){case"$":return"$";case"&":return i;case"`":return aa(e,0,t);case"'":return aa(e,n);case"<":c=r[aa(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ay(h/10);return f===0?d:f<=o?s[f-1]===void 0?ra(l,1):s[f-1]+ra(l,1):d}c=s[h-1]}return c===void 0?"":c})},Dy=et,Ry=Fe,En=qe,nd=Wa,Iy=Ee,Cy=Yi,Ly=hy,di=my,xy=Xs,Oy=Ey,By=Py,My=Pe,Ny=My("replace"),Fy=TypeError,sl=En("".indexOf),Uy=En("".replace),od=En("".slice),Vy=Math.max,dd=function(i,e,t){return t>i.length?-1:e===""?t:sl(i,e,t)};Dy({target:"String",proto:!0},{replaceAll:function(e,t){var s=nd(this),r,a,n,o,u,d,l,c,h,f=0,m=0,b="";if(!Cy(e)){if(r=Ly(e),r&&(a=di(nd(Oy(e))),!~sl(a,"g")))throw Fy("`.replaceAll` does not allow non-global regexes");if(n=xy(e,Ny),n)return Ry(n,e,s,t);if(r)return Uy(di(s),e,t)}for(o=di(s),u=di(e),d=Iy(t),d||(t=di(t)),l=u.length,c=Vy(1,l),f=dd(o,u,0);f!==-1;)h=d?di(t(u,f,o)):By(u,o,f,[],void 0,t),b+=od(o,m,f)+h,m=f+l,f=dd(o,u,f+c);return m<o.length&&(b+=od(o,m)),b}});var Hy=gn,Gy=Hy("String","replaceAll"),Yy=Gy,jy=Yy,qy=jy,zy=qy,ud=zs(zy);const ld=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ci=(i,e)=>{let t=i;t=ud(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=ud(t,n,(o,u)=>re(a)?o:re(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Wy=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,m,b,E,g,_,v,T,$,R,V,K,F,Y,J,x,B,te,M,C,ie,oe,ve,Se,xe,tt,At,Z;const Ue=new DOMParser().parseFromString(i,"application/xml"),Oe={video:[],audio:[],text:[]},Ve=Ue.children[0],Xt=Ve.getElementsByTagName("Period")[0],Ot=Xt.children,Zt=Ve.getAttribute("type")==="dynamic",ei=Ve.getAttribute("availabilityStartTime"),Zi=ei?new Date(ei).getTime():void 0;let Bt;const An=Ve.getAttribute("mediaPresentationDuration"),wn=Xt.getAttribute("duration"),ur=Ve.getElementsByTagName("vk:Attrs")[0],_n=ur==null?void 0:ur.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(An)Bt=ld(An);else if(wn){const We=ld(wn);k(We)&&(Bt=We)}else _n&&(Bt=parseInt(_n,10));let ll=0;const lr=(s=(t=Ve.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],cl=lr.includes(Hs.WEBM_AS_IN_FFMPEG)||lr.includes(Hs.WEBM_AS_IN_SPEC)?yi.WEBM:yi.MP4;for(const We of Ot){const es=We.getAttribute("mimeType"),hl=We.getAttribute("codecs"),kn=(r=We.getAttribute("contentType"))!==null&&r!==void 0?r:es==null?void 0:es.split("/")[0],fl=(n=(a=We.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Pn=We.querySelectorAll("Representation"),pl=We.querySelector("SegmentTemplate");if(kn===Ae.TEXT){for(const be of Pn){const Mt=be.getAttribute("id")||"",ts=We.getAttribute("lang"),ti=(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:"",cr=new URL(ti,e).toString();Oe[Ae.TEXT].push({id:Mt,lang:ts,kind:Ae.TEXT,url:cr})}continue}for(const be of Pn){const Mt=(l=be.getAttribute("mimeType"))!==null&&l!==void 0?l:es,ts=(h=(c=be.getAttribute("codecs"))!==null&&c!==void 0?c:hl)!==null&&h!==void 0?h:"",ti=(m=(f=be.getAttribute("contentType"))!==null&&f!==void 0?f:Mt==null?void 0:Mt.split("/")[0])!==null&&m!==void 0?m:kn,cr=(E=(b=We.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&E!==void 0?E:[],ml=parseInt((g=be.getAttribute("width"))!==null&&g!==void 0?g:"",10),Dn=parseInt((_=be.getAttribute("height"))!==null&&_!==void 0?_:"",10),Rn=parseInt((v=be.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,In=(T=be.getAttribute("frameRate"))!==null&&T!==void 0?T:"",vl=($=be.getAttribute("quality"))!==null&&$!==void 0?$:void 0,gl=In?bn(In):void 0,Sl=(R=be.getAttribute("id"))!==null&&R!==void 0?R:(ll++).toString(10),bl=ti==="video"?`${Dn}p`:ti==="audio"?`${Rn}Kbps`:ts,yl=`${Sl}@${bl}`,Tl=(F=(K=(V=be.querySelector("BaseURL"))===null||V===void 0?void 0:V.textContent)===null||K===void 0?void 0:K.trim())!==null&&F!==void 0?F:"",Cn=new URL(Tl,e).toString(),El=[...lr,...fl,...cr];let hr;const $l=be.querySelector("SegmentBase"),Nt=(Y=be.querySelector("SegmentTemplate"))!==null&&Y!==void 0?Y:pl;if($l){const Ft=(x=(J=be.querySelector("SegmentBase Initialization"))===null||J===void 0?void 0:J.getAttribute("range"))!==null&&x!==void 0?x:"",[Ut,pr]=Ft.split("-").map(ii=>parseInt(ii,10)),wt={from:Ut,to:pr},_i=(B=be.querySelector("SegmentBase"))===null||B===void 0?void 0:B.getAttribute("indexRange"),[mr,is]=_i?_i.split("-").map(ii=>parseInt(ii,10)):[],ki=_i?{from:mr,to:is}:void 0;hr={type:Ge.BYTE_RANGE,url:Cn,initRange:wt,indexRange:ki}}else if(Nt){const Ft={representationId:(te=be.getAttribute("id"))!==null&&te!==void 0?te:void 0,bandwidth:(M=be.getAttribute("bandwidth"))!==null&&M!==void 0?M:void 0},Ut=parseInt((C=Nt.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),pr=(ie=Nt.getAttribute("initialization"))!==null&&ie!==void 0?ie:"",wt=Nt.getAttribute("media"),_i=(ve=parseInt((oe=Nt.getAttribute("startNumber"))!==null&&oe!==void 0?oe:"",10))!==null&&ve!==void 0?ve:1,mr=ci(pr,Ft);if(!wt)throw new ReferenceError("No media attribute in SegmentTemplate");const is=(Se=Nt.querySelectorAll("SegmentTimeline S"))!==null&&Se!==void 0?Se:[],ki=[];let ii=0,vr="",gr=0;if(is.length){let ss=_i,Qe=0;for(const si of is){const it=parseInt((xe=si.getAttribute("d"))!==null&&xe!==void 0?xe:"",10),Vt=parseInt((tt=si.getAttribute("r"))!==null&&tt!==void 0?tt:"",10)||0,rs=parseInt((At=si.getAttribute("t"))!==null&&At!==void 0?At:"",10);Qe=Number.isFinite(rs)?rs:Qe;const Sr=it/Ut*1e3,br=Qe/Ut*1e3;for(let as=0;as<Vt+1;as++){const wl=ci(wt,Object.assign(Object.assign({},Ft),{segmentNumber:ss.toString(10),segmentTime:(Qe+as*it).toString(10)})),Ln=(br!=null?br:0)+as*Sr,_l=Ln+Sr;ss++,ki.push({time:{from:Ln,to:_l},url:wl})}Qe+=(Vt+1)*it,ii+=(Vt+1)*Sr}gr=Qe/Ut*1e3,vr=ci(wt,Object.assign(Object.assign({},Ft),{segmentNumber:ss.toString(10),segmentTime:Qe.toString(10)}))}else if(k(Bt)){const Qe=parseInt((Z=Nt.getAttribute("duration"))!==null&&Z!==void 0?Z:"",10)/Ut*1e3,si=Math.ceil(Bt/Qe);let it=0;for(let Vt=1;Vt<si;Vt++){const rs=ci(wt,Object.assign(Object.assign({},Ft),{segmentNumber:Vt.toString(10),segmentTime:it.toString(10)}));ki.push({time:{from:it,to:it+Qe},url:rs}),it+=Qe}gr=it,vr=ci(wt,Object.assign(Object.assign({},Ft),{segmentNumber:si.toString(10),segmentTime:it.toString(10)}))}const Al={time:{from:gr,to:1/0},url:vr};hr={type:Ge.TEMPLATE,baseUrl:Cn,segmentTemplateUrl:wt,initUrl:mr,totalSegmentsDurationMs:ii,segments:ki,nextSegmentBeyondManifest:Al,timescale:Ut}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ti||!Mt)continue;const fr={video:Ae.VIDEO,audio:Ae.AUDIO,text:Ae.TEXT}[ti];fr&&Oe[fr].push({id:yl,kind:fr,segmentReference:hr,profiles:El,duration:Bt,bitrate:Rn,mime:Mt,codecs:ts,width:ml,height:Dn,fps:gl,quality:vl})}}return{dynamic:Zt,liveAvailabilityStartTime:Zi,duration:Bt,container:cl,representations:Oe}},Qy=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Xi(a):void 0)!==null&&n!==void 0?n:zt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Ky=({id:i,bitrate:e})=>({id:i,bitrate:e}),Jy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ht(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ht(i,-1)},Xy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),cd=i=>"size"in i,ui=i=>i.type===Ge.TEMPLATE,Ya=i=>!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20);class hd{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){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 L,this.gaps=[],this.subscription=new ne,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new gi,this.destroyAbortController=new gi,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){const h=this.representations.get(c);P(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new _b(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},E=>this.error$.next({id:"SegmentEjection",category:O.WTF,message:"Error when trying to clear segments ejected by browser",thrown:E}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:O.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(E=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,sd(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),E)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(E=>this.error$.next(E))),yield yield N(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),m=this.segments.get(h.id),b=this.parsedInitData.get(h.id);if(P(f,"No init buffer for starting representation"),P(m,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield N(void 0);this.searchGaps(m,h),yield yield N(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(b)})}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield N(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);P(h,`No such representation ${c}`);let f=this.segments.get(c),m=this.initData.get(c);if(re(m)||re(f)?yield yield N(this.loadInit(h,"high",!1)):m instanceof Promise&&(yield yield N(m)),f=this.segments.get(c),P(f,"No segments for starting representation"),m=this.initData.get(c),!m||!(m instanceof ArrayBuffer)||!this.sourceBuffer)return yield N(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield N(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const b=this.getCurrentPosition();k(b)&&this.maintain(b)})}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,function(c){var h;return Ie(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield N(void 0);for(const _ of this.representations.keys()){const v=c.find(R=>R.id===_);v&&this.representations.set(_,v);const T=this.representations.get(_);if(!T||!ui(T.segmentReference))return yield N(void 0);const $=this.getActualLiveStartingSegments(T.segmentReference);this.segments.set(T.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const b=this.segments.get(f);P(b,"No segments for starting representation");const E=this.initData.get(f);if(P(E,"No init buffer for starting representation"),!(E instanceof ArrayBuffer))return yield N(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield N(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(b,m),yield yield N(this.sourceBufferTaskQueue.append(E,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=s,s){case yi.MP4:this.containerParser=ey;break;case yi.WEBM:this.containerParser=oy;break;default:G(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new gi,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(re(e)||re(this.downloadingRepresentationId)||re(this.playingRepresentationId)||re(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Pt(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)&&sd(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Pt(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(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=ht(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===q.FED&&!o.length&&Pt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=ht(s,-1);u&&u.status===q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;k(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!ui(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:q.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=ht(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!ui(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=ci(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:q.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const b=h<=s&&f>=s,E=h>s||b||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),_=this.preloadOnly&&h<=s+g||f<=s+g;return(c===q.NONE||c===q.PARTIALLY_EJECTED&&E&&_&&this.sourceBuffer&&!Ha(this.sourceBuffer.buffered,s))&&E&&_});if(r===-1)return[];if(t!==Ge.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===q.NONE||h.status===q.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ae(this,void 0,void 0,function*(){t.segmentReference.type===Ge.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return ae(this,void 0,void 0,function*(){e.status=q.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Re(o,function(){return Ie(this,arguments,function*(){const d=yr(this.failedDownloads,this.tuning.downloadBackoff);yield yield N(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const l=new DataView(d);if(this.isActiveLowLatency()){const c=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,c)}u&&r.feedingBytes?r.segment.status=q.DOWNLOADED:this.sourceBufferTaskQueue.append(l,o).then(c=>{this.onSegmentFullyAppended(r,t.id)}),this.failedDownloads=0}catch(d){if(Ya(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,s="auto"){return ae(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=q.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Re(n,function(){return Ie(this,arguments,function*(){const u=yr(this.failedDownloads,this.tuning.downloadBackoff);yield yield N(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){if(Ya(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(ui(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:ht(e,0).byte.from,to:ht(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:O.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ui(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl).toString(),{signal:r}=this.downloadAbortController,a=()=>{this.abort()},o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!r.aborted)try{this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:r,onSegmentAppendFailed:a,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:O.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:s,signal:r,onProgress:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(s=Pt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:O.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;const n=this.representations.get(t);if(n)for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=q.PARTIALLY_FED,o.feedingBytes+=l.byteLength,this.sourceBufferTaskQueue.append(l).then(c=>{o.fedBytes+=l.byteLength,u.status===q.DOWNLOADED&&this.onSegmentFullyAppended(o,n.id)}))}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===Ge.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const b=h?c.byte.from-s:0,E=h?c.byte.to-s:e.byteLength,g=b<r,_=E<=r;if(c.status===q.DOWNLOADING&&g&&_){c.status=q.DOWNLOADED,this.activeSegments.delete(l);const v=new DataView(e.buffer,e.byteOffset+b,f);this.sourceBufferTaskQueue.append(v,a).then(T=>T&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(l.loadedBytes=Math.min(f,r-b),l.loadedBytes>l.feedingBytes)){const v=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===f?v:this.containerParser.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(c.status=q.PARTIALLY_FED,l.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=T.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=q.FED,cd(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===q.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=q.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===q.PARTIALLY_FED||e.status===q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=q.NONE),e.status=q.PARTIALLY_EJECTED):e.status=q.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=id(()=>rr(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ae(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Re(this.destroyAbortController.signal,function(){return Ie(this,arguments,function*(){const o=yr(this.failedDownloads,this.tuning.downloadBackoff);yield yield N(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>ae(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&ui(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:O.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ae(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||re(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=cd(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===q.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===q.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===q.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const 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===q.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=id(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:O.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(re(this.sourceBuffer)||re(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==q.FED&&a!==q.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=q.PARTIALLY_EJECTED:r.status=q.NONE)}}}var mi;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(mi||(mi={}));class Zy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.abortAllController=new gi,this.subscription=new ne,this.fetchManifest=Re(this.abortAllController.signal,function(r){return Ie(this,arguments,function*(){let a=r;this.requestQuic&&(a=bi(a));const n=yield yield N(Vi(a,{signal:this.abortAllController.signal}).catch(Ri));return n?(this.onHeadersReceived(n.headers),yield N(n.text())):yield N(null)})}.bind(this)),this.fetch=Re(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?mi.HEADER:mi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return Ie(this,arguments,function*(){let m=r;const b=new Headers;if(n)switch(a){case mi.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case mi.PARAM:{const B=new URL(m,location.href);B.searchParams.append("bytes",`${n.from}-${n.to}`),m=B.toString();break}default:G(a)}this.requestQuic&&(m=bi(m));let E=this.abortAllController.signal,g;if(d){const B=new gi;if(g=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{B.abort()}catch(te){Ri(te)}}),this.abortAllController.signal.aborted||d.aborted)try{B.abort()}catch(te){Ri(te)}E=B.signal}const _=le(),v=yield yield N(Vi(m,{priority:u,headers:b,signal:E}).catch(Ri)),T=le();if(!v)return g==null||g.unsubscribe(),yield N(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-_),!v.ok||!v.body)return g==null||g.unsubscribe(),yield N(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!o&&!l)return g==null||g.unsubscribe(),yield N(v.arrayBuffer());const[$,R]=v.body.tee(),V=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(R,c));let K=0,F=new Uint8Array(0),Y=!1;const J=B=>{g==null||g.unsubscribe(),Y=!0,Ri(B)},x=Re(E,function({done:B,value:te}){return Ie(this,arguments,function*(){if(K===0&&this.lastRequestFirstBytes$.next(le()-_),E.aborted)return g==null||g.unsubscribe(),yield N(void 0);if(!B&&te){const M=new Uint8Array(F.length+te.length);M.set(F),M.set(te,F.length),F=M,K+=te.byteLength,o==null||o(new DataView(F.buffer),K),yield yield N(V==null?void 0:V.read().then(x,J))}})}.bind(this));return yield yield N(V==null?void 0:V.read().then(x,J)),g==null||g.unsubscribe(),yield N(Y?null:F.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,function(r,a,n){var o;return Ie(this,arguments,function*(){if(r.type!==Ge.BYTE_RANGE)return yield N(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const b=yield yield N(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!b)return yield N(null);const E=new DataView(b,u-l,d-l+1);if(!a.validateData(E))throw new Error("Invalid media file");const g=a.parseInit(E),_=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!_)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(b,_.from-l,_.to-_.from+1);else{const $=yield yield N(this.fetch(r.url,{range:_,priority:n,measureThroughput:!1}));if(!$)return yield N(null);v=new DataView($)}const T=a.parseSegments(v,g,_);return yield N({init:g,dataView:new DataView(b),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,function(r,a){return Ie(this,arguments,function*(){if(r.type!==Ge.TEMPLATE)return yield N(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield N(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield N(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:q.NONE,size:void 0}));return yield N({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=zu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ae(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ge.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ge.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:G(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ri=i=>{if(Ya(i))throw i},ja=1e3,js=(i,e,t)=>t*e+(1-t)*i,rl=(i,e)=>i.reduce((t,s)=>t+s,0)/e,eT=(i,e,t,s)=>{let r=0,a=t;const n=rl(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class $n{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 s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new nt(`raw_${s}`),this.smoothedSeries$=new nt(`smoothed_${s}`),this.reportedSeries$=new nt(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(re(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 tT extends $n{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=js(this.slow,e,this.params.emaAlphaSlow),this.fast=js(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class iT extends $n{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=rl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=js(this.emaSmoothed,e,this.params.emaAlpha);const s=eT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class sT extends $n{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?js(this.smoothed,e,this.params.emaAlpha):e}}class qa{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new tT({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new iT({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new sT(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const rT=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},fd=["timeupdate","progress","play","seeked","stalled","waiting"];var He;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(He||(He={}));let aT=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ne,this.representationSubscription=new ne,this.state$=new he(He.NONE),this.currentVideoRepresentation$=new S(void 0),this.currentVideoRepresentationInit$=new S(void 0),this.error$=new L,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.livePositionFromPlayer$=new S(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new gi,this.initManifest=Re(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){this.element=t,this.manifestUrlString=ut(s,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(He.MANIFEST_READY),this.manifest=yield yield N(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(He.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:O.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,function(){var t;return Ie(this,arguments,function*(){const s=yield yield N(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:O.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield N(this.manifest);let r;try{r=Wy(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:O.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield N(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 r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield N(Object.assign(Object.assign({},r),{representations:Qi(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,function(t,s){return Ie(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(He.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new hd(Ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(s)&&(this.audioBufferManager=new hd(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(Os(ja).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Qo(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=ut(this.manifestUrlString,d+ja,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...fd.map(o=>U(this.element,o))).pipe(w(o=>this.element?Pt(this.element.buffered,this.element.currentTime*1e3):0),me(),ee(o=>!!o)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ee(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),rT(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var b,E;return(E=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&E!==void 0?E:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Ce({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:u,bufferLength:d})=>ae(this,void 0,void 0,function*(){if(P(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=Qo(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,b=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,E=this.isActiveLowLatency?d:u;let g=at.None;if(this.isActiveLowLatency?g=at.ActiveLowLatency:E<f+b&&E>=f?g=at.LiveWithTargetOffset:c!==0&&E<f&&(g=at.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),g===at.LiveForwardBuffering||g===at.LiveWithTargetOffset){const _=o-(f+m),v=Math.trunc(c+_/l);let T;u?v>0?T=v:T=0:T=c,this.manifestUrlString=ut(this.manifestUrlString,T,Te.DASH_CMAF_OFFSET_P)}g!==at.None&&g!==at.ActiveLowLatency&&(o=0,this.updateLive())})))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Ce({allBuffersFull:a,someBufferEnded:n}).pipe(ee(({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:O.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...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 N(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(s)?yield yield N(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield N(this.videoBufferManager.startWith(t)),this.state$.setState(He.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Os(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:O.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Zy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=qa.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return ae(this,void 0,void 0,function*(){P(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.manifestUrlString=ut(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((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){P(this.element),this.state$.setState(He.RUNNING),this.subscription.add(H(...fd.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:O.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ha(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ae(this,void 0,void 0,function*(){const s={[Ae.VIDEO]:this.videoBufferManager,[Ae.AUDIO]:this.audioBufferManager,[Ae.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;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((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Ha(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(He.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 ae(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class nT{constructor(e,t){this.fov=e,this.orientation=t}}class oT{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var dT=`#define GLSLIFY 1
|
|
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;}`,uT=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|
|
33
33
|
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,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new 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"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Qy,this.gl.VERTEX_SHADER),s=this.createShader(Ky,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,l=t+r,c=e-s,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,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===W.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==he.STOPPED&&n!==p.STOPPED){const l=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s: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),R(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),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&R(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&&R(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&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(a)}}},this.init3DScene=t=>{var s,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:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=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(De(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,s=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:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:l})=>l)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(re(k),ge()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Rt(this.video,t.playbackRate,s.playbackRateState$,r)),a(Bs(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===He.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(($,T)=>T.bitrate-$.bitrate),v=Array.from(h.video).sort(($,T)=>T.bitrate-$.bitrate),g=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const $ of f){const T=ty($);T&&this.audioTracks.push({track:T,representation:$})}for(const $ of v){const T=ey($);if(T){c.push({track:T,representation:$});const m=!this.params.tuning.isAudioDisabled&&iy(f,v,$);m&&this.audioRepresentations.set($.id,m)}}this.videoTracks$.next(c);for(const $ of g){const T=sy($);T&&this.textTracks.push({track:T,representation:$})}this.params.output.availableVideoTracks$.next(c.map(({track:$})=>$)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:$})=>$)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:$})=>$));const E=this.selectVideoRepresentation();P(E),this.player.initRepresentations(E.id,(l=this.audioRepresentations.get(E.id))===null||l===void 0?void 0:l.id)}else d===He.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(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==He.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(G(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(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks$.getValue().find(({track:{id:$}})=>$===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&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),g=mi(this.videoTracks$.getValue().map(({track:$})=>$),{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}),E=o?g!=null?g:d:d!=null?d:g;return E&&((n=this.videoTracks$.getValue().find(({track:$})=>$===E))===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),R(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:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Zy extends Xu{constructor(e){super(e),this.liveOffset=new tr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(Be({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(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===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 ie;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ie||(ie={}));const ki=(i,e)=>new Hs(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class eT{constructor(e){this.subscription=new ae,this.videoState=new ce(ie.INITIALIZING),this.textTracksManager=new dt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==ie.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:V(t)}break;case p.READY:switch(t){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:V(t)}break;case p.PLAYING:switch(t){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:V(t)}break;case p.PAUSED:switch(t){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED);break;case ie.PLAYING:this.pause();break;default:V(t)}break;default:V(s)}},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(De(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},s=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(s),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(ie.STOPPED)}subscribe(){P(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=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,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(jt(this.video,e.isLooped,s)),this.subscription.add(gt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Rt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ki(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(ie.PLAYING),R(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),a(ki(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:E}=c,$=(f=Wi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Vt({width:g,height:E});if(!$)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,m={id:v.toString(),quality:$,bitrate:c.bitrate/1e3,size:{width:g,height:E},fps:T};return this.trackLevels.set(v,{track:m,level:c}),l.push(m),l},[]))),t.availableVideoTracks$),a(ki(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(ki(this.hls,tt.Events.LEVEL_LOADING).pipe(w(({url:d})=>De(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:s}));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=ki(this.hls,tt.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(re(k)).subscribe(t.currentVideoTrack$,s),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(se(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:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=G(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(ie.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(ie.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(ie.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(ie.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(ie.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0)}}const nd="X-Playback-Duration";var od=i=>ue(void 0,void 0,void 0,function*(){var e;const t=yield Bi(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(nd)?parseInt(t.headers.get(nd),10):void 0});const tT=i=>{let e=null;if(i.QUALITY&&(e=Wi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Vt({width:t,height:s})}return e!=null?e:null},Zu=(i,e=i)=>ue(void 0,void 0,void 0,function*(){var t;const a=(yield(yield Bi(i)).text()).split(`
|
|
38
|
-
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=ji(d[1].split(",").map($=>$.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=tT(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[$,T]=l.RESOLUTION.split("x").map(m=>parseInt(m,10));$&&T&&(g={width:$,height:T})}const E=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:E,bandwidth:f,size:g,fps:v})}return n});var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.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),R(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?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),R(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&&R(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&&(R(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case oe.CHANGING_MANIFEST:break;default:return V(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:Qe.INVARIANT,url:this.params.source.url};Zu(nt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...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(De(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:s,videoTrack:r}=this.params.desiredState,a=s.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",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,s=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,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),R(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),R(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),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(De(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)},s)),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)},s)),this.subscription.add(Be({startTime:this.manifestStartTime$.pipe(re(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(se(e))return;const t=this.params.format===b.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,s=nt(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",s),this.video.load(),od(s).then(r=>{var a;if(!se(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(se(n)||!isFinite(n))try{Bi(s).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,s).toString();od(l).then(c=>{se(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),this.liveOffset.pause(),R(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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.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),R(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?R(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(le.PAUSED),R(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&&R(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&&R(this.params.desiredState.playbackState,p.PAUSED);return;case le.CHANGING_MANIFEST:break;default:return V(r)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Qe.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(De(this.params.source.url)),Zu(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",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,s=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));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,s)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),R(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),R(t.playbackState,p.PAUSED)},s)).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()},s).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(De(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)},s))),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$,s));const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();se(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),R(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(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.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,s,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),R(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=(s=this.trackUrls[l.to])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested&&this.seek(c.position),a){case fe.READY:n===p.READY?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(fe.PAUSED),R(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&&R(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&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(a)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},r=yt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(jt(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),R(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),R(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.READY);const 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()},s)),this.textTracksManager.connect(this.video,t,e);const n=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){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=li(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(De(t))}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),R(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,s,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(s=Object.values(this.trackUrls).find(d=>yd(d.track.quality,e)))===null||s===void 0?void 0:s.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=mi(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 s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ue(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls: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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),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(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.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(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===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),R(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:s===p.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(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,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};G(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,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===de.READY&&this.videoState.setState(de.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(gt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).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 V(n.to)}},s)).add(G(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Qe.INVARIANT}),this.video.srcObject=e,R(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),R(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,bs,oa,ys,da,Ts,ua,Es,la,$s,ca,As,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"',We={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},xe={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=(bs=window.MediaSource)===null||bs===void 0?void 0:bs.isTypeSupported)===null||oa===void 0)&&oa.call(bs,uT)),h265:!!(!((da=(ys=window.MediaSource)===null||ys===void 0?void 0:ys.isTypeSupported)===null||da===void 0)&&da.call(ys,lT)),vp9:!!(!((ua=(Ts=window.MediaSource)===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||ua===void 0)&&ua.call(Ts,tl)),av1:!!(!((la=(Es=window.MediaSource)===null||Es===void 0?void 0:Es.isTypeSupported)===null||la===void 0)&&la.call(Es,il)),aac:!!(!((ca=($s=window.MediaSource)===null||$s===void 0?void 0:$s.isTypeSupported)===null||ca===void 0)&&ca.call($s,cT)),opus:!!(!((ha=(As=window.MediaSource)===null||As===void 0?void 0:As.isTypeSupported)===null||ha===void 0)&&ha.call(As,hT))},ii=(at.h264||at.h265)&&at.aac;var At;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(At||(At={}));var ft;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(ft||(ft={}));let Bt;const fT=()=>ue(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:il})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:tl})}))]);Bt={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}});try{fT()}catch(i){console.error(i)}const Ni=We.hls&&xe.mp4,pT=()=>Object.keys(at).filter(i=>at[i]),vT=(i,e=!1)=>i.filter(t=>{switch(t){case b.DASH:return We.mse&&xe.mp4&ⅈcase b.DASH_SEP:return We.mse&&xe.mp4&ⅈcase b.DASH_WEBM:return We.mse&&xe.webm&&at.vp9&&at.opus;case b.DASH_WEBM_AV1:return We.mse&&xe.webm&&at.av1&&at.opus;case b.DASH_LIVE:return We.mse&&xe.mp4&ⅈcase b.DASH_LIVE_CMAF:return We.mse&&xe.mp4&&ii&&xe.cmaf;case b.DASH_ONDEMAND:return We.mse&&xe.mp4&ⅈcase b.HLS:case b.HLS_ONDEMAND:return Ni||e&&We.mse&&xe.mp4&ⅈcase b.HLS_LIVE:case b.HLS_LIVE_CMAF:return Ni;case b.MPEG:return xe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return We.webrtc&&We.ws&&at.h264&&(xe.mp4||xe.webm);default:return V(t)}}),Pi=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){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:V(i)}return[e,t]},mT=({webmCodec:i,androidPreferredFormat:e})=>{if(el)switch(e){case ft.MPEG:return[b.MPEG,...Pi(i),b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case ft.HLS:return[b.HLS,b.HLS_ONDEMAND,...Pi(i),b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.MPEG];case ft.DASH:return[...Pi(i),b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]}return Ni?[...Pi(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[...Pi(i),b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},gT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[b.DASH_LIVE_CMAF,b.DASH_LIVE]:[b.DASH_LIVE,b.DASH_LIVE_CMAF],r=e?[b.HLS_LIVE_CMAF,b.HLS_LIVE]:[b.HLS_LIVE,b.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(el)switch(i){case ft.DASH:{o=a;break}case ft.HLS:case ft.MPEG:{o=n;break}}else Ni?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},ld=i=>i?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE_CMAF]:[b.DASH_WEBM,b.DASH_WEBM_AV1,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var ST=i=>new Hs(e=>{const t=new ae,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new x;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.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),i.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:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new 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(se(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==W.None;if(this.params.desiredState.seekState.setState({state:W.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case we.SCREEN:return this.createScreenProvider(t);case we.CHROMECAST:return this.createChromecastProvider(t);default:return V(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new gb(Object.assign(Object.assign({},n),{source:o,config:bT}))}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.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 b.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 b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ni||!this.params.tuning.useHlsJs?new sT(Object.assign(Object.assign({},n),{source:o})):new eT(Object.assign(Object.assign({},n),{source:o}))}case b.HLS_LIVE:case b.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 b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new rT(Object.assign(Object.assign({},n),{source:o}))}case b.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 b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new dT({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new $S({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?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 V(e)}}skipFormat(e){switch(e){case we.SCREEN:return this.screenFormatsIterator.next();case we.CHROMECAST:return this.chromecastFormatsIterator.next();default:return V(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 V(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return ji(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,s=0;return e.add(G(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=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:we.SCREEN)}})),e}}const Na=(i,e,t)=>t*e+(1-t)*i,sl=(i,e)=>i.reduce((t,s)=>t+s,0)/e,ET=(i,e,t,s)=>{let r=0,a=t;const n=sl(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class 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 s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${s}`),this.smoothedSeries$=new st(`smoothed_${s}`),this.reportedSeries$=new st(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(se(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 s=ET(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class cd{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new $T({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new AT({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const _T=5e3,hd="one_video_throughput",fd="one_video_rtt",pt=window.navigator.connection,pd=()=>{const i=pt==null?void 0:pt.downlink;if(k(i)&&i!==10)return i*1e3},vd=()=>{const i=pt==null?void 0:pt.rtt;if(k(i)&&i!==3e3)return i},md=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Ci{constructor(e){var t,s;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ci.load(hd)||(e.useBrowserEstimation?pd():void 0)||_T,a=(s=(t=Ci.load(fd))!==null&&t!==void 0?t:e.useBrowserEstimation?vd():void 0)!==null&&s!==void 0?s: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(U(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(Be({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,s=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(U(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,s=me()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=me()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=me(),u=n-t,d=o-s;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 s=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(s,me()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=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,s=1){if(Ci.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=pr.get(e);if(k(s))return(t=parseInt(s,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},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,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=i=>{var e;return Object.assign(Object.assign({},wl(i,gd)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...gd.configName]})};var Sd=({seekState:i,position$:e})=>G(i.stateChangeEnded$.pipe(w(({to:t})=>{var s;return t.state===W.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),re(k)),e.pipe(re(()=>i.getState().state===W.None))),kT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.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 Ci(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(s)}`,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,s,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:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state: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 s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t,s,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?(s=this.providerContainer)===null||s===void 0||s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(se(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===W.None?void 0:t.position;return k(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(G(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)=>xi(o)?1:xi(u)?-1:_s(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(Be({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(Be({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(G(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 s=new S(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>s.next(!1)));let r=0;const a=G(e.providerOutput.isBuffering$,t,s).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(G(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(G(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===$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((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(s=>s.length>0),ge()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=mi(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(G(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(s=>YS(s)),this.providerContainer.current$.subscribe(({type:s})=>vs("provider",s)),t.duration$.subscribe(s=>vs("duration",s)),t.availableVideoTracks$.pipe(re(s=>!!s.length),ge()).subscribe(s=>vs("tracks",s)),this.events.fatalError$.subscribe(new st("fatalError")),this.events.managedError$.subscribe(new st("managedError")),t.position$.subscribe(new st("position")),t.currentVideoTrack$.pipe(w(s=>s==null?void 0:s.quality)).subscribe(new st("quality")),this.info.currentBuffer$.subscribe(new st("buffer")),t.isBuffering$.subscribe(new st("isBuffering"))].forEach(s=>this.subscription.add(s)),vs("codecs",pT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(r)})})});this.subscription.add(G(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const LT=`@vkontakte/videoplayer-core@${Rl}`;export{$e as ChromecastState,Li 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,b 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 lT{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new nT(this.params.fov,this.params.orientation),this.cameraRotationManager=new oT(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(dT,this.gl.VERTEX_SHADER),s=this.createShader(uT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,l=t+r,c=e-s,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 al{constructor(e){this.subscription=new ne,this.videoState=new he(fe.STOPPED),this.elementSize$=new S(void 0),this.textTracksManager=new ct,this.droppedFramesManager=new nr,this.videoTracks$=new S([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new eb,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===W.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==fe.STOPPED&&n!==p.STOPPED){const l=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.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(fe.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case fe.STOPPED:this.videoState.startTransitionTo(fe.READY),this.prepare();return;case fe.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()):(o==null?void 0:o.to)===p.READY&&D(this.params.desiredState.playbackState,p.READY);return;case fe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(fe.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 fe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(fe.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 G(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new lT(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=yt(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(Le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new aT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=Et(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:O.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:l})=>l)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ee(k),ge()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Jt(this.video,t.isLooped,r)),this.subscription.add(bt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ct(this.video,t.playbackRate,s.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),D(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),D(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===fe.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===He.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((g,_)=>_.bitrate-g.bitrate),m=Array.from(h.video).sort((g,_)=>_.bitrate-g.bitrate),b=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const _=Ky(g);_&&this.audioTracks.push({track:_,representation:g})}for(const g of m){const _=Qy(g);if(_){c.push({track:_,representation:g});const v=!this.params.tuning.isAudioDisabled&&Jy(f,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of b){const _=Xy(g);_&&this.textTracks.push({track:_,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const E=this.selectVideoRepresentation();P(E),this.player.initRepresentations(E.id,(l=this.audioRepresentations.get(E.id))===null||l===void 0?void 0:l.id)}else d===He.REPRESENTATIOS_READY&&(this.videoState.setState(fe.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:O.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==He.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(me(),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),me());this.subscription.add(H(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(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks$.getValue().find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=Pt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!o&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),b=wi(this.videoTracks$.getValue().map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),E=o?b!=null?b:d:d!=null?d:b;return E&&((n=this.videoTracks$.getValue().find(({track:g})=>g===E))===null||n===void 0?void 0:n.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Lt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),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:O.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),Tt(this.video)}}class cT extends al{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class hT extends al{constructor(e){super(e),this.liveOffset=new ar}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ce({interval:Os(ja),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===fe.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ce({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===fe.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const rt={};var se;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));const Ii=(i,e)=>new qs(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class fT{constructor(e){this.subscription=new ne,this.videoState=new he(se.INITIALIZING),this.textTracksManager=new ct,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==se.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===W.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case se.STOPPED:break;case se.READY:case se.PLAYING:case se.PAUSED:this.stop();break;default:G(t)}break;case p.READY:switch(t){case se.STOPPED:this.prepare();break;case se.READY:case se.PLAYING:case se.PAUSED:break;default:G(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:G(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:G(t)}break;default:G(s)}},this.video=yt(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(Le(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),Tt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:O.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);rr(import("hls.js").then(r=>{e||(rt.Hls=r.default,rt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(rt.Hls,"hls.js not loaded"),this.hls=new rt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(se.STOPPED)}subscribe(){P(rt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:O.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Et(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Jt(this.video,e.isLooped,s)),this.subscription.add(bt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ct(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(Ii(this.hls,rt.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:O.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)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),D(e.playbackState,p.PAUSED)},s)).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()},s)),a(Ii(this.hls,rt.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:b,height:E}=c,g=(f=Xi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:zt({width:b,height:E});if(!g)return l;const _=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:b,height:E},fps:_};return this.trackLevels.set(m,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(Ii(this.hls,rt.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,b="internal";l.push({id:h,url:f,language:m,type:b})}e.internalTextTracks.startTransitionTo(l)}}),a(Ii(this.hls,rt.Events.LEVEL_LOADING).pipe(w(({url:d})=>Le(d))),t.hostname$),this.subscription.add(Ze(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));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=Ii(this.hls,rt.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(ee(k)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Ze(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(re(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,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(w(d=>d==null?void 0:d.id)),onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(se.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ae(this,void 0,void 0,function*(){this.videoState.startTransitionTo(se.PLAYING),(yield Lt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.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 pd="X-Playback-Duration";var md=i=>ae(void 0,void 0,void 0,function*(){var e;const t=yield Vi(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(pd)?parseInt(t.headers.get(pd),10):void 0});const pT=i=>{let e=null;if(i.QUALITY&&(e=Xi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=zt({width:t,height:s})}return e!=null?e:null},nl=(i,e=i)=>ae(void 0,void 0,void 0,function*(){var t;const a=(yield(yield Vi(i)).text()).split(`
|
|
38
|
+
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=Qi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=pT(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[g,_]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));g&&_&&(b={width:g,height:_})}const E=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:E,bandwidth:f,size:b,fps:m})}return n});var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(de||(de={}));class mT{constructor(e){var t;this.subscription=new ne,this.videoState=new he(de.STOPPED),this.textTracksManager=new ct,this.manifests$=new S([]),this.liveOffset=new ar,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!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(u||d){const h=this.videoState.getState();this.videoState.setState(de.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(de.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case de.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(de.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.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 de.CHANGING_MANIFEST:break;default:return G(a)}},this.params=e,this.video=yt(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:Je.INVARIANT,url:this.params.source.url};nl(ut(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:O.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(Le(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:s,videoTrack:r}=this.params.desiredState,a=s.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",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,s=o=>{e.error$.next({id:"HlsLiveProvider",category:O.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Et(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(bt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ct(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),D(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),D(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),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(Le(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===W.Requested&&this.seek(o.position)},s)),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)},s)),this.subscription.add(Ce({startTime:this.manifestStartTime$.pipe(ee(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Tt(this.video)}prepare(){const e=this.selectManifest();if(re(e))return;const t=this.params.format===y.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,s=ut(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",s),this.video.load(),md(s).then(r=>{var a;if(!re(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(re(n)||!isFinite(n))try{Vi(s).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,s).toString();md(l).then(c=>{re(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Lt(this.video).then(e=>{e||(this.videoState.setState(de.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:O.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ce;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ce||(ce={}));class vT{constructor(e){this.subscription=new ne,this.videoState=new he(ce.STOPPED),this.textTracksManager=new ct,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!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.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(ce.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(ce.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 ce.READY:a===p.READY?D(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ce.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;case ce.CHANGING_MANIFEST:break;default:return G(r)}},this.params=e,this.video=yt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Je.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(Le(this.params.source.url)),nl(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:O.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",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,s=o=>{e.error$.next({id:"HlsProvider",category:O.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Et(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));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,s)),this.subscription.add(bt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ct(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),D(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),D(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},s).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(Le(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ce.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===W.Requested&&this.seek(o.position)},s))),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$,s));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Tt(this.video)}prepare(){const e=this.selectManifest();re(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Lt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var pe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(pe||(pe={}));class gT{constructor(e){this.subscription=new ne,this.videoState=new he(pe.STOPPED),this.trackUrls={},this.textTracksManager=new ct,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.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(pe.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!==pe.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===pe.STOPPED){this.videoState.startTransitionTo(pe.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=(s=this.trackUrls[l.to])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===W.Requested&&this.seek(c.position),a){case pe.READY:n===p.READY?D(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(pe.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed());return;case pe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case pe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(a)}},this.params=e,this.video=yt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:O.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Et(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Jt(this.video,t.isLooped,s)),this.subscription.add(bt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ct(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(pe.PLAYING),D(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(pe.PAUSED),D(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===pe.READY&&this.videoState.setState(pe.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()===pe.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Tt(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=bi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Le(t))}playIfAllowed(){Lt(this.video).then(e=>{e||(this.videoState.setState(pe.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(s=Object.values(this.trackUrls).find(d=>kd(d.track.quality,e)))===null||s===void 0?void 0:s.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&&ba(u.quality,n.quality)&&(a=n)}else if(!e){const n=Object.values(this.trackUrls).map(o=>o.track);a=wi(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 vd=["stun:videostun.mycdn.me:80"],ST=1e3,bT=3,na=()=>null;class yT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=na,this.externalStopCallback=na,this.externalErrorCallback=na,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ae(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 ae(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:vd}]};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 ae(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 ae(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:O.WTF,message:e.message})}onPeerConnectionStream(e){return ae(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 ae(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),ST)}normalizeOptions(e={}){const t={stunServerList:vd,maxRetryNumber:bT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ue;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ue||(ue={}));class TT{constructor(e){this.videoState=new he(ue.STOPPED),this.maxSeekBackTime$=new S(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),D(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case ue.READY:s===p.PAUSED?(this.videoState.setState(ue.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&D(this.params.desiredState.playbackState,p.PLAYING);return;case ue.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&D(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(t)}},this.subscription=new ne,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=yt(e.container),this.liveStreamClient=new yT(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),Tt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:O.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(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=Et(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===ue.READY&&this.videoState.setState(ue.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(bt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ue.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case ue.READY:break;case ue.PAUSED:t.playbackState.setState(p.PAUSED);break;case ue.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return G(n.to)}},s)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(Ye(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Le(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:Je.INVARIANT}),this.video.srcObject=e,D(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ue.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:O.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Lt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),D(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class gd{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 oa,da,ua,la,ca,ha,Es,fa,$s,pa,As,ma,ws,va,_s,ga,ks,Sa;const ol=za().device===Rl.Android,Dt=document.createElement("video"),ET='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$T='video/mp4; codecs="hev1.1.6.L93.B0"',dl='video/webm; codecs="vp09.00.10.08"',ul='video/webm; codecs="av01.0.00M.08"',AT='audio/mp4; codecs="mp4a.40.2"',wT='audio/webm; codecs="opus"',Ke={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((da=(oa=window.SourceBuffer)===null||oa===void 0?void 0:oa.prototype)===null||da===void 0)&&da.appendBuffer)),hls:!!(!((ua=Dt.canPlayType)===null||ua===void 0)&&ua.call(Dt,"application/x-mpegurl")||!((la=Dt.canPlayType)===null||la===void 0)&&la.call(Dt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Be={mp4:!!(!((ca=Dt.canPlayType)===null||ca===void 0)&&ca.call(Dt,"video/mp4")),webm:!!(!((ha=Dt.canPlayType)===null||ha===void 0)&&ha.call(Dt,"video/webm")),cmaf:!0},dt={h264:!!(!((fa=(Es=window.MediaSource)===null||Es===void 0?void 0:Es.isTypeSupported)===null||fa===void 0)&&fa.call(Es,ET)),h265:!!(!((pa=($s=window.MediaSource)===null||$s===void 0?void 0:$s.isTypeSupported)===null||pa===void 0)&&pa.call($s,$T)),vp9:!!(!((ma=(As=window.MediaSource)===null||As===void 0?void 0:As.isTypeSupported)===null||ma===void 0)&&ma.call(As,dl)),av1:!!(!((va=(ws=window.MediaSource)===null||ws===void 0?void 0:ws.isTypeSupported)===null||va===void 0)&&va.call(ws,ul)),aac:!!(!((ga=(_s=window.MediaSource)===null||_s===void 0?void 0:_s.isTypeSupported)===null||ga===void 0)&&ga.call(_s,AT)),opus:!!(!((Sa=(ks=window.MediaSource)===null||ks===void 0?void 0:ks.isTypeSupported)===null||Sa===void 0)&&Sa.call(ks,wT))},li=(dt.h264||dt.h265)&&dt.aac;var kt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(kt||(kt={}));var mt;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(mt||(mt={}));let Gt;const _T=()=>ae(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:ul})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:dl})}))]);Gt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}});try{_T()}catch(i){console.error(i)}const Hi=Ke.hls&&Be.mp4,kT=()=>Object.keys(dt).filter(i=>dt[i]),PT=(i,e=!1)=>i.filter(t=>{switch(t){case y.DASH:return Ke.mse&&Be.mp4&&li;case y.DASH_SEP:return Ke.mse&&Be.mp4&&li;case y.DASH_WEBM:return Ke.mse&&Be.webm&&dt.vp9&&dt.opus;case y.DASH_WEBM_AV1:return Ke.mse&&Be.webm&&dt.av1&&dt.opus;case y.DASH_LIVE:return Ke.mse&&Be.mp4&&li;case y.DASH_LIVE_CMAF:return Ke.mse&&Be.mp4&&li&&Be.cmaf;case y.DASH_ONDEMAND:return Ke.mse&&Be.mp4&&li;case y.HLS:case y.HLS_ONDEMAND:return Hi||e&&Ke.mse&&Be.mp4&&li;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Hi;case y.MPEG:return Be.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ke.webrtc&&Ke.ws&&dt.h264&&(Be.mp4||Be.webm);default:return G(t)}}),Ci=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case kt.VP9:return[e,t];case kt.AV1:return[t,e];case kt.NONE:return[];case kt.SMOOTH:return Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case kt.POWER_EFFICIENT:return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:G(i)}return[e,t]},DT=({webmCodec:i,androidPreferredFormat:e})=>{if(ol)switch(e){case mt.MPEG:return[y.MPEG,...Ci(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case mt.HLS:return[y.HLS,y.HLS_ONDEMAND,...Ci(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case mt.DASH:return[...Ci(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Hi?[...Ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...Ci(i),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},RT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(ol)switch(i){case mt.DASH:{o=a;break}case mt.HLS:case mt.MPEG:{o=n;break}}else Hi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Sd=i=>i?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var IT=i=>new qs(e=>{const t=new ne,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new L;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.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),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const CT={cacheDuration:12e4},LT={chunkDuration:5e3,maxParallelRequests:5};class xT{constructor(e){this.current$=new S({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,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 L,warning$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new 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 ne,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=PT([...RT(this.params.tuning),...DT(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>k(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new gd(a);const n=[...Sd(!0),...Sd(!1)];this.chromecastFormatsIterator=new gd(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(re(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:O.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==W.None;if(this.params.desiredState.seekState.setState({state:W.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return G(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new Eb(Object.assign(Object.assign({},n),{source:o,config:CT}))}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 Xo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new cT(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 Xo(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new hT(Object.assign(Object.assign({},n),{source:o}))}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Hi||!this.params.tuning.useHlsJs?new vT(Object.assign(Object.assign({},n),{source:o})):new fT(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 mT(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 gT(Object.assign(Object.assign({},n),{source:o}))}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new gb(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},LT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new TT({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return G(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new PS({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return G(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return G(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return G(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Qi(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ne;let t=!1,s=0;return e.add(H(this.providerOutput.error$,IT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:O.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(ee(({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===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(_e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===O.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:_e.SCREEN)}})),e}}const OT=5e3,bd="one_video_throughput",yd="one_video_rtt",vt=window.navigator.connection,Td=()=>{const i=vt==null?void 0:vt.downlink;if(k(i)&&i!==10)return i*1e3},Ed=()=>{const i=vt==null?void 0:vt.rtt;if(k(i)&&i!==3e3)return i},$d=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class Bi{constructor(e){var t,s;this.subscription=new ne,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Bi.load(bd)||(e.useBrowserEstimation?Td():void 0)||OT,a=(s=(t=Bi.load(yd))!==null&&t!==void 0?t:e.useBrowserEstimation?Ed():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new S(r),this.rtt$=new S(a),this.rttAdjustedThroughput$=new S($d(r,a,e.rttPenaltyRequestSize)),this.throughput=qa.getSmoothedValue(r,-1,e),this.rtt=qa.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Td();u&&this.throughput.next(u);const d=Ed();k(d)&&this.rtt.next(d)};vt&&"onchange"in vt&&this.subscription.add(U(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Tr.set(bd,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Tr.set(yd,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ce({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>$d(n,o,e.rttPenaltyRequestSize)),ee(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=le();const r=new ne;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,s=le()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=le()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-s;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=l=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>ae(this,void 0,void 0,function*(){l?(!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e)):c&&(t?(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval&&le()-a<this.tuningConfig.lowLatency.separateByteSequenceInterval?n+=c.byteLength:(this.addRawSpeed(n,le()-a,this.concurrentDownloads.size,t),n=c.byteLength,a=le()),o=le()):(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le())),yield s==null?void 0:s.read().then(d,u))});this.concurrentDownloads.add(e),s==null||s.read().then(d,u)}addRawSpeed(e,t,s=1,r=!1){if(r||Bi.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=Tr.get(e);if(k(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Ad={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:5,separateByteSequenceInterval:100}},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},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},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:kt.VP9,androidPreferredFormat:mt.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:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!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}},BT=i=>{var e;return Object.assign(Object.assign({},Il(i,Ad)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Ad.configName]})};var wd=({seekState:i,position$:e})=>H(i.stateChangeEnded$.pipe(w(({to:t})=>{var s;return t.state===W.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ee(k)),e.pipe(ee(()=>i.getState().state===W.None))),MT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};class GT{constructor(e={configName:[]}){if(this.subscription=new ne,this.logger=new Cl,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:W.None}),volume:new he({volume:1,muted:!1}),videoTrack:new he(void 0),autoVideoTrackSwitching:new he(!0),autoVideoTrackLimits:new he({}),isLooped:new he(!1),playbackRate:new he(1),externalTextTracks:new he([]),internalTextTracks:new he([]),currentTextTrack:new he(void 0),textTrackCuesSettings:new he({}),cameraOrientation:new he({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 L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new S(void 0),tuningConfigName$:new S([]),enableDebugTelemetry$:new S(!1),dumpTelemetry:JS},this.initLogs(),this.tuning=BT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Bl({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(s)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:O.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=MT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new xT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state: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 s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t,s,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?(s=this.providerContainer)===null||s===void 0||s.providerOutput.availableTextTracks$.pipe(ee(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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(re(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===W.None?void 0:t.position;return k(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(H(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(ee(({from:e})=>e===p.STOPPED),ge()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===W.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:W.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:O.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),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>Mi(o)?1:Mi(u)?-1:Ps(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(me()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(me()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(me()).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(Ce({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:wd({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}),me(),xs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Ce({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),me(),xs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),me()).subscribe(this.info.volume$)).add(wd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(Si(!0)),e.providerOutput.seekedEvent$.pipe(Si(!1))).pipe(me()).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:O.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:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),w(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),w(()=>le()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new S(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new S(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ee(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>s.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,s).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),me());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,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(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),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 ne;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ee(s=>s.length>0),ge()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=wi(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(H(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),KS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>QS(s)),this.providerContainer.current$.subscribe(({type:s})=>bs("provider",s)),t.duration$.subscribe(s=>bs("duration",s)),t.availableVideoTracks$.pipe(ee(s=>!!s.length),ge()).subscribe(s=>bs("tracks",s)),this.events.fatalError$.subscribe(new nt("fatalError")),this.events.managedError$.subscribe(new nt("managedError")),t.position$.subscribe(new nt("position")),t.currentVideoTrack$.pipe(w(s=>s==null?void 0:s.quality)).subscribe(new nt("quality")),this.info.currentBuffer$.subscribe(new nt("buffer")),t.isBuffering$.subscribe(new nt("isBuffering"))].forEach(s=>this.subscription.add(s)),bs("codecs",kT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ae(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:O.DOM,message:String(r)})})});this.subscription.add(H(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const YT=`@vkontakte/videoplayer-core@${xl}`;export{$e as ChromecastState,Ni as HttpConnectionType,zT as Observable,p as PlaybackState,GT as Player,YT as SDK_VERSION,WT as Subject,QT as Subscription,_t as Surface,xl as VERSION,KT as ValueSubject,y as VideoFormat,JT as VideoQuality};
|