@vkontakte/videoplayer-core 2.0.103-dev.620e0c0f.0 → 2.0.103-dev.af88f935.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 +12 -12
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +7 -7
- package/esnext.cjs.js +9 -9
- package/esnext.esm.js +16 -16
- package/evergreen.esm.js +14 -14
- package/index.d.ts +10 -0
- package/package.json +2 -2
package/es2015.esm.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.103-dev.
|
|
3
|
-
* Fri, 31 May 2024
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.103-dev.af88f935.0
|
|
3
|
+
* Fri, 31 May 2024 10:15:29 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-103/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as y,Subject as D,Subscription as re,isNonNullable as R,ErrorCategory as I,isNullable as K,fromEvent as x,assertNever as H,merge as F,tap as Oi,map as $,observableFrom as He,filterChanged as pe,assertNonNullable as P,debounce as rt,getHighestQuality as Tu,timeout as Eu,getCurrentBrowser as Na,CurrentClientBrowser as yl,combine as Ve,once as _e,mapTo as _s,filter as fe,VideoQuality as Le,now as le,assertNotEmptyArray as $u,videoSizeToQuality as Mt,isInvariantQuality as Bt,isHigher as hi,isLower as $s,isHigherOrEqual as ua,isLowerOrEqual as Cs,interval as Ci,videoQualityToHeight as Au,abortable as Ce,getExponentialDelay as As,throttle as wu,Observable as Fa,observeElementSize as ku,isIOS as Pu,CurrentClientDevice as Ru,safeStorage as hr,fillWithDefault as _u,Logger as Cu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as FT,Subject as VT,Subscription as UT,ValueSubject as HT,VideoQuality as jT}from"@vkontakte/videoplayer-shared/es2015.esm.js";const Iu="2.0.103-dev.620e0c0f.0";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_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var Ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var ye;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ye||(ye={}));var ca;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ca||(ca={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var bt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(bt||(bt={}));function te(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(d){try{l(s.next(d))}catch(c){n(c)}}function u(d){try{l(s.throw(d))}catch(c){n(c)}}function l(d){d.done?a(d.value):r(d.value).then(o,u)}l((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function Ie(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,v){a.push([h,f,m,v])>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 M?Promise.resolve(h.value.v).then(l,d):c(a[0][2],h)}function l(h){o("next",h)}function d(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Du=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 Lu{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ye.NOT_AVAILABLE),this.errorEvent$=new D,this.realCastState$=new y(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=R((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||Du("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:I.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(){R(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(x(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return H(r.sessionState)}})).add(F(x(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Oi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),He([s.getCastState()])).pipe(pe(),$(xu),Oi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=R(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const l=u.getCastDevice(),d=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?R(this.connection$.getValue())?ye.CONNECTED:ye.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:I.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const xu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return H(i)}};var fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Vs(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}},Ou=je,Us=!Ou(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Tl=Us,El=Function.prototype,ha=El.call,Mu=Tl&&El.bind.bind(ha,ha),Ge=Tl?Mu:function(i){return function(){return ha.apply(i,arguments)}},$l=Ge,Bu=$l({}.toString),Nu=$l("".slice),Vi=function(i){return Nu(Bu(i),8,-1)},Fu=Ge,Vu=je,Uu=Vi,pr=Object,Hu=Fu("".split),ju=Vu(function(){return!pr("z").propertyIsEnumerable(0)})?function(i){return Uu(i)=="String"?Hu(i,""):pr(i)}:pr,Ui=function(i){return i==null},Gu=Ui,Yu=TypeError,Va=function(i){if(Gu(i))throw Yu("Can't call method on "+i);return i},qu=ju,Wu=Va,Hi=function(i){return qu(Wu(i))},gi={},is=function(i){return i&&i.Math==Math&&i},Ee=is(typeof globalThis=="object"&&globalThis)||is(typeof window=="object"&&window)||is(typeof self=="object"&&self)||is(typeof fr=="object"&&fr)||function(){return this}()||fr||Function("return this")(),fa=typeof document=="object"&&document.all,zu=typeof fa=="undefined"&&fa!==void 0,Al={all:fa,IS_HTMLDDA:zu},wl=Al,Qu=wl.all,ge=wl.IS_HTMLDDA?function(i){return typeof i=="function"||i===Qu}:function(i){return typeof i=="function"},Ku=Ee,Ju=ge,_n=Ku.WeakMap,Xu=Ju(_n)&&/native code/.test(String(_n)),Cn=ge,kl=Al,Zu=kl.all,ft=kl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Cn(i)||i===Zu}:function(i){return typeof i=="object"?i!==null:Cn(i)},ec=je,$t=!ec(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Vt={},tc=Ee,In=ft,pa=tc.document,ic=In(pa)&&In(pa.createElement),Ua=function(i){return ic?pa.createElement(i):{}},sc=$t,rc=je,ac=Ua,Pl=!sc&&!rc(function(){return Object.defineProperty(ac("div"),"a",{get:function(){return 7}}).a!=7}),nc=$t,oc=je,Rl=nc&&oc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),lc=ft,dc=String,uc=TypeError,pt=function(i){if(lc(i))return i;throw uc(dc(i)+" is not an object")},cc=Us,ss=Function.prototype.call,Oe=cc?ss.bind(ss):function(){return ss.apply(ss,arguments)},Ha={},vr=Ha,mr=Ee,hc=ge,Dn=function(i){return hc(i)?i:void 0},Ut=function(i,e){return arguments.length<2?Dn(vr[i])||Dn(mr[i]):vr[i]&&vr[i][e]||mr[i]&&mr[i][e]},fc=Ge,Hs=fc({}.isPrototypeOf),js=typeof navigator!="undefined"&&String(navigator.userAgent)||"",_l=Ee,gr=js,Ln=_l.process,xn=_l.Deno,On=Ln&&Ln.versions||xn&&xn.version,Mn=On&&On.v8,We,Is;Mn&&(We=Mn.split("."),Is=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Is&&gr&&(We=gr.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=gr.match(/Chrome\/(\d+)/),We&&(Is=+We[1])));var Cl=Is,Bn=Cl,pc=je,vc=Ee,mc=vc.String,Il=!!Object.getOwnPropertySymbols&&!pc(function(){var i=Symbol();return!mc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Bn&&Bn<41}),gc=Il,Dl=gc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Sc=Ut,bc=ge,yc=Hs,Tc=Dl,Ec=Object,Ll=Tc?function(i){return typeof i=="symbol"}:function(i){var e=Sc("Symbol");return bc(e)&&yc(e.prototype,Ec(i))},$c=String,Gs=function(i){try{return $c(i)}catch(e){return"Object"}},Ac=ge,wc=Gs,kc=TypeError,Ht=function(i){if(Ac(i))return i;throw kc(wc(i)+" is not a function")},Pc=Ht,Rc=Ui,Ys=function(i,e){var t=i[e];return Rc(t)?void 0:Pc(t)},Sr=Oe,br=ge,yr=ft,_c=TypeError,Cc=function(i,e){var t,s;if(e==="string"&&br(t=i.toString)&&!yr(s=Sr(t,i))||br(t=i.valueOf)&&!yr(s=Sr(t,i))||e!=="string"&&br(t=i.toString)&&!yr(s=Sr(t,i)))return s;throw _c("Can't convert object to primitive value")},xl={exports:{}},Ic=!0,Nn=Ee,Dc=Object.defineProperty,Lc=function(i,e){try{Dc(Nn,i,{value:e,configurable:!0,writable:!0})}catch(t){Nn[i]=e}return e},xc=Ee,Oc=Lc,Fn="__core-js_shared__",Mc=xc[Fn]||Oc(Fn,{}),ja=Mc,Vn=ja;(xl.exports=function(i,e){return Vn[i]||(Vn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Ol=xl.exports,Bc=Va,Nc=Object,qs=function(i){return Nc(Bc(i))},Fc=Ge,Vc=qs,Uc=Fc({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return Uc(Vc(e),t)},Hc=Ge,jc=0,Gc=Math.random(),Yc=Hc(1 .toString),Ml=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Yc(++jc+Gc,36)},qc=Ee,Wc=Ol,Un=nt,zc=Ml,Qc=Il,Kc=Dl,li=qc.Symbol,Tr=Wc("wks"),Jc=Kc?li.for||li:li&&li.withoutSetter||zc,Pe=function(i){return Un(Tr,i)||(Tr[i]=Qc&&Un(li,i)?li[i]:Jc("Symbol."+i)),Tr[i]},Xc=Oe,Hn=ft,jn=Ll,Zc=Ys,eh=Cc,th=Pe,ih=TypeError,sh=th("toPrimitive"),rh=function(i,e){if(!Hn(i)||jn(i))return i;var t=Zc(i,sh),s;if(t){if(e===void 0&&(e="default"),s=Xc(t,i,e),!Hn(s)||jn(s))return s;throw ih("Can't convert object to primitive value")}return e===void 0&&(e="number"),eh(i,e)},ah=rh,nh=Ll,Ga=function(i){var e=ah(i,"string");return nh(e)?e:e+""},oh=$t,lh=Pl,dh=Rl,rs=pt,Gn=Ga,uh=TypeError,Er=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,$r="enumerable",Ar="configurable",wr="writable";Vt.f=oh?dh?function(e,t,s){if(rs(e),t=Gn(t),rs(s),typeof e=="function"&&t==="prototype"&&"value"in s&&wr in s&&!s[wr]){var r=ch(e,t);r&&r[wr]&&(e[t]=s.value,s={configurable:Ar in s?s[Ar]:r[Ar],enumerable:$r in s?s[$r]:r[$r],writable:!1})}return Er(e,t,s)}:Er:function(e,t,s){if(rs(e),t=Gn(t),rs(s),lh)try{return Er(e,t,s)}catch(r){}if("get"in s||"set"in s)throw uh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ws=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},hh=$t,fh=Vt,ph=Ws,ji=hh?function(i,e,t){return fh.f(i,e,ph(1,t))}:function(i,e,t){return i[e]=t,i},vh=Ol,mh=Ml,Yn=vh("keys"),Ya=function(i){return Yn[i]||(Yn[i]=mh(i))},qa={},gh=Xu,Bl=Ee,Sh=ft,bh=ji,kr=nt,Pr=ja,yh=Ya,Th=qa,qn="Object already initialized",va=Bl.TypeError,Eh=Bl.WeakMap,Ds,Mi,Ls,$h=function(i){return Ls(i)?Mi(i):Ds(i,{})},Ah=function(i){return function(e){var t;if(!Sh(e)||(t=Mi(e)).type!==i)throw va("Incompatible receiver, "+i+" required");return t}};if(gh||Pr.state){var Xe=Pr.state||(Pr.state=new Eh);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Ds=function(i,e){if(Xe.has(i))throw va(qn);return e.facade=i,Xe.set(i,e),e},Mi=function(i){return Xe.get(i)||{}},Ls=function(i){return Xe.has(i)}}else{var ei=yh("state");Th[ei]=!0,Ds=function(i,e){if(kr(i,ei))throw va(qn);return e.facade=i,bh(i,ei,e),e},Mi=function(i){return kr(i,ei)?i[ei]:{}},Ls=function(i){return kr(i,ei)}}var Nl={set:Ds,get:Mi,has:Ls,enforce:$h,getterFor:Ah},wh=Us,Fl=Function.prototype,Wn=Fl.apply,zn=Fl.call,Vl=typeof Reflect=="object"&&Reflect.apply||(wh?zn.bind(Wn):function(){return zn.apply(Wn,arguments)}),kh=Vi,Ph=Ge,Ul=function(i){if(kh(i)==="Function")return Ph(i)},Wa={},Hl={},jl={}.propertyIsEnumerable,Gl=Object.getOwnPropertyDescriptor,Rh=Gl&&!jl.call({1:2},1);Hl.f=Rh?function(e){var t=Gl(this,e);return!!t&&t.enumerable}:jl;var _h=$t,Ch=Oe,Ih=Hl,Dh=Ws,Lh=Hi,xh=Ga,Oh=nt,Mh=Pl,Qn=Object.getOwnPropertyDescriptor;Wa.f=_h?Qn:function(e,t){if(e=Lh(e),t=xh(t),Mh)try{return Qn(e,t)}catch(s){}if(Oh(e,t))return Dh(!Ch(Ih.f,e,t),e[t])};var Bh=je,Nh=ge,Fh=/#|\.prototype\./,Gi=function(i,e){var t=Uh[Vh(i)];return t==jh?!0:t==Hh?!1:Nh(e)?Bh(e):!!e},Vh=Gi.normalize=function(i){return String(i).replace(Fh,".").toLowerCase()},Uh=Gi.data={},Hh=Gi.NATIVE="N",jh=Gi.POLYFILL="P",Yl=Gi,Kn=Ul,Gh=Ht,Yh=Us,qh=Kn(Kn.bind),zs=function(i,e){return Gh(i),e===void 0?i:Yh?qh(i,e):function(){return i.apply(e,arguments)}},as=Ee,Wh=Vl,zh=Ul,Qh=ge,Kh=Wa.f,Jh=Yl,ti=Ha,Xh=zs,ii=ji,Jn=nt,Zh=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 Wh(i,this,arguments)};return e.prototype=i.prototype,e},Qe=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?as:r?as[t]:(as[t]||{}).prototype,o=s?ti:ti[t]||ii(ti,t,{})[t],u=o.prototype,l,d,c,h,f,m,v,g,S;for(h in e)l=Jh(s?h:t+(r?".":"#")+h,i.forced),d=!l&&n&&Jn(n,h),m=o[h],d&&(i.dontCallGetSet?(S=Kh(n,h),v=S&&S.value):v=n[h]),f=d&&v?v:e[h],!(d&&typeof m==typeof f)&&(i.bind&&d?g=Xh(f,as):i.wrap&&d?g=Zh(f):a&&Qh(f)?g=zh(f):g=f,(i.sham||f&&f.sham||m&&m.sham)&&ii(g,"sham",!0),ii(o,h,g),a&&(c=t+"Prototype",Jn(ti,c)||ii(ti,c,{}),ii(ti[c],h,f),i.real&&u&&(l||!u[h])&&ii(u,h,f)))},ma=$t,ef=nt,ql=Function.prototype,tf=ma&&Object.getOwnPropertyDescriptor,za=ef(ql,"name"),sf=za&&function(){}.name==="something",rf=za&&(!ma||ma&&tf(ql,"name").configurable),af={EXISTS:za,PROPER:sf,CONFIGURABLE:rf},Wl={},nf=Math.ceil,of=Math.floor,lf=Math.trunc||function(e){var t=+e;return(t>0?of:nf)(t)},df=lf,Qa=function(i){var e=+i;return e!==e||e===0?0:df(e)},uf=Qa,cf=Math.max,hf=Math.min,ff=function(i,e){var t=uf(i);return t<0?cf(t+e,0):hf(t,e)},pf=Qa,vf=Math.min,mf=function(i){return i>0?vf(pf(i),9007199254740991):0},gf=mf,Ka=function(i){return gf(i.length)},Sf=Hi,bf=ff,yf=Ka,Xn=function(i){return function(e,t,s){var r=Sf(e),a=yf(r),n=bf(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}},Tf={includes:Xn(!0),indexOf:Xn(!1)},Ef=Ge,Rr=nt,$f=Hi,Af=Tf.indexOf,wf=qa,Zn=Ef([].push),kf=function(i,e){var t=$f(i),s=0,r=[],a;for(a in t)!Rr(wf,a)&&Rr(t,a)&&Zn(r,a);for(;e.length>s;)Rr(t,a=e[s++])&&(~Af(r,a)||Zn(r,a));return r},zl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Pf=kf,Rf=zl,_f=Object.keys||function(e){return Pf(e,Rf)},Cf=$t,If=Rl,Df=Vt,Lf=pt,xf=Hi,Of=_f;Wl.f=Cf&&!If?Object.defineProperties:function(e,t){Lf(e);for(var s=xf(t),r=Of(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],s[o]);return e};var Mf=Ut,Ql=Mf("document","documentElement"),Bf=pt,Nf=Wl,eo=zl,Ff=qa,Vf=Ql,Uf=Ua,Hf=Ya,to=">",io="<",ga="prototype",Sa="script",Kl=Hf("IE_PROTO"),_r=function(){},Jl=function(i){return io+Sa+to+i+io+"/"+Sa+to},so=function(i){i.write(Jl("")),i.close();var e=i.parentWindow.Object;return i=null,e},jf=function(){var i=Uf("iframe"),e="java"+Sa+":",t;return i.style.display="none",Vf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Jl("document.F=Object")),t.close(),t.F},ns,ws=function(){try{ns=new ActiveXObject("htmlfile")}catch(e){}ws=typeof document!="undefined"?document.domain&&ns?so(ns):jf():so(ns);for(var i=eo.length;i--;)delete ws[ga][eo[i]];return ws()};Ff[Kl]=!0;var Xl=Object.create||function(e,t){var s;return e!==null?(_r[ga]=Bf(e),s=new _r,_r[ga]=null,s[Kl]=e):s=ws(),t===void 0?s:Nf.f(s,t)},Gf=je,Yf=!Gf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),qf=nt,Wf=ge,zf=qs,Qf=Ya,Kf=Yf,ro=Qf("IE_PROTO"),ba=Object,Jf=ba.prototype,Zl=Kf?ba.getPrototypeOf:function(i){var e=zf(i);if(qf(e,ro))return e[ro];var t=e.constructor;return Wf(t)&&e instanceof t?t.prototype:e instanceof ba?Jf:null},Xf=ji,Ja=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Xf(i,e,t),i},Zf=je,ep=ge,tp=ft,ip=Xl,ao=Zl,sp=Ja,rp=Pe,ya=rp("iterator"),ed=!1,ct,Cr,Ir;[].keys&&(Ir=[].keys(),"next"in Ir?(Cr=ao(ao(Ir)),Cr!==Object.prototype&&(ct=Cr)):ed=!0);var ap=!tp(ct)||Zf(function(){var i={};return ct[ya].call(i)!==i});ap?ct={}:ct=ip(ct);ep(ct[ya])||sp(ct,ya,function(){return this});var td={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:ed},np=Pe,op=np("toStringTag"),id={};id[op]="z";var Xa=String(id)==="[object z]",lp=Xa,dp=ge,ks=Vi,up=Pe,cp=up("toStringTag"),hp=Object,fp=ks(function(){return arguments}())=="Arguments",pp=function(i,e){try{return i[e]}catch(t){}},Yi=lp?ks:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=pp(e=hp(i),cp))=="string"?t:fp?ks(e):(s=ks(e))=="Object"&&dp(e.callee)?"Arguments":s},vp=Xa,mp=Yi,gp=vp?{}.toString:function(){return"[object "+mp(this)+"]"},Sp=Xa,bp=Vt.f,yp=ji,Tp=nt,Ep=gp,$p=Pe,no=$p("toStringTag"),Za=function(i,e,t,s){if(i){var r=t?i:i.prototype;Tp(r,no)||bp(r,no,{configurable:!0,value:e}),s&&!Sp&&yp(r,"toString",Ep)}},Ap=td.IteratorPrototype,wp=Xl,kp=Ws,Pp=Za,Rp=gi,_p=function(){return this},Cp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=wp(Ap,{next:kp(+!s,t)}),Pp(i,r,!1,!0),Rp[r]=_p,i},Ip=Qe,Dp=Oe,sd=af,Lp=Cp,xp=Zl,Op=Za,oo=Ja,Mp=Pe,lo=gi,rd=td,Bp=sd.PROPER;sd.CONFIGURABLE;rd.IteratorPrototype;var os=rd.BUGGY_SAFARI_ITERATORS,Dr=Mp("iterator"),uo="keys",ls="values",co="entries",Np=function(){return this},Fp=function(i,e,t,s,r,a,n){Lp(t,e,s);var o=function(S){if(S===r&&h)return h;if(!os&&S in d)return d[S];switch(S){case uo:return function(){return new t(this,S)};case ls:return function(){return new t(this,S)};case co:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[Dr]||d["@@iterator"]||r&&d[r],h=!os&&c||o(r),f=e=="Array"&&d.entries||c,m,v,g;if(f&&(m=xp(f.call(new i)),m!==Object.prototype&&m.next&&(Op(m,u,!0,!0),lo[u]=Np)),Bp&&r==ls&&c&&c.name!==ls&&(l=!0,h=function(){return Dp(c,this)}),r)if(v={values:o(ls),keys:a?h:o(uo),entries:o(co)},n)for(g in v)(os||l||!(g in d))&&oo(d,g,v[g]);else Ip({target:e,proto:!0,forced:os||l},v);return n&&d[Dr]!==h&&oo(d,Dr,h,{name:r}),lo[e]=h,v},Vp=function(i,e){return{value:i,done:e}},Up=Hi,ho=gi,ad=Nl;Vt.f;var Hp=Fp,ds=Vp,nd="Array Iterator",jp=ad.set,Gp=ad.getterFor(nd);Hp(Array,"Array",function(i,e){jp(this,{type:nd,target:Up(i),index:0,kind:e})},function(){var i=Gp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ds(void 0,!0)):t=="keys"?ds(s,!1):t=="values"?ds(e[s],!1):ds([s,e[s]],!1)},"values");ho.Arguments=ho.Array;var Yp=Pe,qp=gi,Wp=Yp("iterator"),zp=Array.prototype,Qp=function(i){return i!==void 0&&(qp.Array===i||zp[Wp]===i)},Kp=Yi,fo=Ys,Jp=Ui,Xp=gi,Zp=Pe,ev=Zp("iterator"),od=function(i){if(!Jp(i))return fo(i,ev)||fo(i,"@@iterator")||Xp[Kp(i)]},tv=Oe,iv=Ht,sv=pt,rv=Gs,av=od,nv=TypeError,ov=function(i,e){var t=arguments.length<2?av(i):e;if(iv(t))return sv(tv(t,i));throw nv(rv(i)+" is not iterable")},lv=Oe,po=pt,dv=Ys,uv=function(i,e,t){var s,r;po(i);try{if(s=dv(i,"return"),!s){if(e==="throw")throw t;return t}s=lv(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return po(s),t},cv=zs,hv=Oe,fv=pt,pv=Gs,vv=Qp,mv=Ka,vo=Hs,gv=ov,Sv=od,mo=uv,bv=TypeError,Ps=function(i,e){this.stopped=i,this.result=e},go=Ps.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=cv(e,s),l,d,c,h,f,m,v,g=function(E){return l&&mo(l,"normal",E),new Ps(!0,E)},S=function(E){return r?(fv(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)l=i.iterator;else if(n)l=i;else{if(d=Sv(i),!d)throw bv(pv(i)+" is not iterable");if(vv(d)){for(c=0,h=mv(i);h>c;c++)if(f=S(i[c]),f&&vo(go,f))return f;return new Ps(!1)}l=gv(i,d)}for(m=a?i.next:l.next;!(v=hv(m,l)).done;){try{f=S(v.value)}catch(E){mo(l,"throw",E)}if(typeof f=="object"&&f&&vo(go,f))return f}return new Ps(!1)},yv=Ga,Tv=Vt,Ev=Ws,$v=function(i,e,t){var s=yv(e);s in i?Tv.f(i,s,Ev(0,t)):i[s]=t},Av=Qe,wv=en,kv=$v;Av({target:"Object",stat:!0},{fromEntries:function(e){var t={};return wv(e,function(s,r){kv(t,s,r)},{AS_ENTRIES:!0}),t}});var Pv=Ha,Rv=Pv.Object.fromEntries,_v={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},Cv=_v,Iv=Ee,Dv=Yi,Lv=ji,So=gi,xv=Pe,bo=xv("toStringTag");for(var Lr in Cv){var yo=Iv[Lr],xr=yo&&yo.prototype;xr&&Dv(xr)!==bo&&Lv(xr,bo,Lr),So[Lr]=So.Array}var Ov=Rv,Mv=Ov,Bv=Mv,Nv=Bv,xs=Vs(Nv),Fv=Vi,Qs=typeof process!="undefined"&&Fv(process)=="process",Vv=Vt,Uv=function(i,e,t){return Vv.f(i,e,t)},Hv=Ut,jv=Uv,Gv=Pe,Yv=$t,To=Gv("species"),qv=function(i){var e=Hv(i);Yv&&e&&!e[To]&&jv(e,To,{configurable:!0,get:function(){return this}})},Wv=Hs,zv=TypeError,Qv=function(i,e){if(Wv(e,i))return i;throw zv("Incorrect invocation")},Kv=Ge,Jv=ge,Ta=ja,Xv=Kv(Function.toString);Jv(Ta.inspectSource)||(Ta.inspectSource=function(i){return Xv(i)});var ld=Ta.inspectSource,Zv=Ge,em=je,dd=ge,tm=Yi,im=Ut,sm=ld,ud=function(){},rm=[],cd=im("Reflect","construct"),tn=/^\s*(?:class|function)\b/,am=Zv(tn.exec),nm=!tn.exec(ud),ki=function(e){if(!dd(e))return!1;try{return cd(ud,rm,e),!0}catch(t){return!1}},hd=function(e){if(!dd(e))return!1;switch(tm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nm||!!am(tn,sm(e))}catch(t){return!0}};hd.sham=!0;var om=!cd||em(function(){var i;return ki(ki.call)||!ki(Object)||!ki(function(){i=!0})||i})?hd:ki,lm=om,dm=Gs,um=TypeError,cm=function(i){if(lm(i))return i;throw um(dm(i)+" is not a constructor")},Eo=pt,hm=cm,fm=Ui,pm=Pe,vm=pm("species"),fd=function(i,e){var t=Eo(i).constructor,s;return t===void 0||fm(s=Eo(t)[vm])?e:hm(s)},mm=Ge,gm=mm([].slice),Sm=TypeError,bm=function(i,e){if(i<e)throw Sm("Not enough arguments");return i},ym=js,pd=/(?:ipad|iphone|ipod).*applewebkit/i.test(ym),xe=Ee,Tm=Vl,Em=zs,$o=ge,$m=nt,vd=je,Ao=Ql,Am=gm,wo=Ua,wm=bm,km=pd,Pm=Qs,Ea=xe.setImmediate,$a=xe.clearImmediate,Rm=xe.process,Or=xe.Dispatch,_m=xe.Function,ko=xe.MessageChannel,Cm=xe.String,Mr=0,Ii={},Po="onreadystatechange",Bi,Ct,Br,Nr;vd(function(){Bi=xe.location});var sn=function(i){if($m(Ii,i)){var e=Ii[i];delete Ii[i],e()}},Fr=function(i){return function(){sn(i)}},Ro=function(i){sn(i.data)},_o=function(i){xe.postMessage(Cm(i),Bi.protocol+"//"+Bi.host)};(!Ea||!$a)&&(Ea=function(e){wm(arguments.length,1);var t=$o(e)?e:_m(e),s=Am(arguments,1);return Ii[++Mr]=function(){Tm(t,void 0,s)},Ct(Mr),Mr},$a=function(e){delete Ii[e]},Pm?Ct=function(i){Rm.nextTick(Fr(i))}:Or&&Or.now?Ct=function(i){Or.now(Fr(i))}:ko&&!km?(Br=new ko,Nr=Br.port2,Br.port1.onmessage=Ro,Ct=Em(Nr.postMessage,Nr)):xe.addEventListener&&$o(xe.postMessage)&&!xe.importScripts&&Bi&&Bi.protocol!=="file:"&&!vd(_o)?(Ct=_o,xe.addEventListener("message",Ro,!1)):Po in wo("script")?Ct=function(i){Ao.appendChild(wo("script"))[Po]=function(){Ao.removeChild(this),sn(i)}}:Ct=function(i){setTimeout(Fr(i),0)});var md={set:Ea,clear:$a},gd=function(){this.head=null,this.tail=null};gd.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 Sd=gd,Im=js,Dm=/ipad|iphone|ipod/i.test(Im)&&typeof Pebble!="undefined",Lm=js,xm=/web0s(?!.*chrome)/i.test(Lm),Nt=Ee,Co=zs,Om=Wa.f,Vr=md.set,Mm=Sd,Bm=pd,Nm=Dm,Fm=xm,Ur=Qs,Io=Nt.MutationObserver||Nt.WebKitMutationObserver,Do=Nt.document,Lo=Nt.process,us=Nt.Promise,xo=Om(Nt,"queueMicrotask"),Aa=xo&&xo.value,si,Hr,jr,cs,Oo;if(!Aa){var hs=new Mm,fs=function(){var i,e;for(Ur&&(i=Lo.domain)&&i.exit();e=hs.get();)try{e()}catch(t){throw hs.head&&si(),t}i&&i.enter()};!Bm&&!Ur&&!Fm&&Io&&Do?(Hr=!0,jr=Do.createTextNode(""),new Io(fs).observe(jr,{characterData:!0}),si=function(){jr.data=Hr=!Hr}):!Nm&&us&&us.resolve?(cs=us.resolve(void 0),cs.constructor=us,Oo=Co(cs.then,cs),si=function(){Oo(fs)}):Ur?si=function(){Lo.nextTick(fs)}:(Vr=Co(Vr,Nt),si=function(){Vr(fs)}),Aa=function(i){hs.head||si(),hs.add(i)}}var Vm=Aa,Um=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}}},Hm=Ee,Si=Hm.Promise,bd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",jm=bd,Gm=Qs,Ym=!jm&&!Gm&&typeof window=="object"&&typeof document=="object",qm=Ee,Di=Si,Wm=ge,zm=Yl,Qm=ld,Km=Pe,Jm=Ym,Xm=bd,Gr=Cl,Mo=Di&&Di.prototype,Zm=Km("species"),wa=!1,yd=Wm(qm.PromiseRejectionEvent),eg=zm("Promise",function(){var i=Qm(Di),e=i!==String(Di);if(!e&&Gr===66||!(Mo.catch&&Mo.finally))return!0;if(!Gr||Gr<51||!/native code/.test(i)){var t=new Di(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Zm]=s,wa=t.then(function(){})instanceof s,!wa)return!0}return!e&&(Jm||Xm)&&!yd}),qi={CONSTRUCTOR:eg,REJECTION_EVENT:yd,SUBCLASSING:wa},bi={},Bo=Ht,tg=TypeError,ig=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw tg("Bad Promise constructor");e=s,t=r}),this.resolve=Bo(e),this.reject=Bo(t)};bi.f=function(i){return new ig(i)};var sg=Qe,Os=Qs,Et=Ee,Wi=Oe,rg=Ja,ag=Za,ng=qv,og=Ht,ka=ge,lg=ft,dg=Qv,ug=fd,Td=md.set,an=Vm,cg=Um,hg=rn,fg=Sd,Ed=Nl,Pa=Si,nn=qi,$d=bi,Ks="Promise",Ad=nn.CONSTRUCTOR,pg=nn.REJECTION_EVENT;nn.SUBCLASSING;var Yr=Ed.getterFor(Ks),vg=Ed.set,mg=Pa&&Pa.prototype,di=Pa,qr=mg,wd=Et.TypeError,Ra=Et.document,on=Et.process,_a=$d.f,gg=_a,Sg=!!(Ra&&Ra.createEvent&&Et.dispatchEvent),kd="unhandledrejection",bg="rejectionhandled",No=0,Pd=1,yg=2,ln=1,Rd=2,ps,Fo,Tg,_d=function(i){var e;return lg(i)&&ka(e=i.then)?e:!1},Cd=function(i,e){var t=e.value,s=e.state==Pd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,l,d;try{r?(s||(e.rejection===Rd&&$g(e),e.rejection=ln),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===i.promise?n(wd("Promise-chain cycle")):(l=_d(u))?Wi(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Id=function(i,e){i.notified||(i.notified=!0,an(function(){for(var t=i.reactions,s;s=t.get();)Cd(s,i);i.notified=!1,e&&!i.rejection&&Eg(i)}))},Dd=function(i,e,t){var s,r;Sg?(s=Ra.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Et.dispatchEvent(s)):s={promise:e,reason:t},!pg&&(r=Et["on"+i])?r(s):i===kd&&cg("Unhandled promise rejection",t)},Eg=function(i){Wi(Td,Et,function(){var e=i.facade,t=i.value,s=Vo(i),r;if(s&&(r=hg(function(){Os?on.emit("unhandledRejection",t,e):Dd(kd,e,t)}),i.rejection=Os||Vo(i)?Rd:ln,r.error))throw r.value})},Vo=function(i){return i.rejection!==ln&&!i.parent},$g=function(i){Wi(Td,Et,function(){var e=i.facade;Os?on.emit("rejectionHandled",e):Dd(bg,e,i.value)})},ui=function(i,e,t){return function(s){i(e,s,t)}},fi=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=yg,Id(i,!0))},Ca=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw wd("Promise can't be resolved itself");var s=_d(e);s?an(function(){var r={done:!1};try{Wi(s,e,ui(Ca,r,i),ui(fi,r,i))}catch(a){fi(r,a,i)}}):(i.value=e,i.state=Pd,Id(i,!1))}catch(r){fi({done:!1},r,i)}}};Ad&&(di=function(e){dg(this,qr),og(e),Wi(ps,this);var t=Yr(this);try{e(ui(Ca,t),ui(fi,t))}catch(s){fi(t,s)}},qr=di.prototype,ps=function(e){vg(this,{type:Ks,done:!1,notified:!1,parent:!1,reactions:new fg,rejection:!1,state:No,value:void 0})},ps.prototype=rg(qr,"then",function(e,t){var s=Yr(this),r=_a(ug(this,di));return s.parent=!0,r.ok=ka(e)?e:!0,r.fail=ka(t)&&t,r.domain=Os?on.domain:void 0,s.state==No?s.reactions.add(r):an(function(){Cd(r,s)}),r.promise}),Fo=function(){var i=new ps,e=Yr(i);this.promise=i,this.resolve=ui(Ca,e),this.reject=ui(fi,e)},$d.f=_a=function(i){return i===di||i===Tg?new Fo(i):gg(i)});sg({global:!0,constructor:!0,wrap:!0,forced:Ad},{Promise:di});ag(di,Ks,!1,!0);ng(Ks);var Ag=Pe,Ld=Ag("iterator"),xd=!1;try{var wg=0,Uo={next:function(){return{done:!!wg++}},return:function(){xd=!0}};Uo[Ld]=function(){return this},Array.from(Uo,function(){throw 2})}catch(i){}var kg=function(i,e){if(!e&&!xd)return!1;var t=!1;try{var s={};s[Ld]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Pg=Si,Rg=kg,_g=qi.CONSTRUCTOR,Od=_g||!Rg(function(i){Pg.all(i).then(void 0,function(){})}),Cg=Qe,Ig=Oe,Dg=Ht,Lg=bi,xg=rn,Og=en,Mg=Od;Cg({target:"Promise",stat:!0,forced:Mg},{all:function(e){var t=this,s=Lg.f(t),r=s.resolve,a=s.reject,n=xg(function(){var o=Dg(t.resolve),u=[],l=0,d=1;Og(e,function(c){var h=l++,f=!1;d++,Ig(o,t,c).then(function(m){f||(f=!0,u[h]=m,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),s.promise}});var Bg=Qe,Ng=qi.CONSTRUCTOR,Ho=Si;Ho&&Ho.prototype;Bg({target:"Promise",proto:!0,forced:Ng,real:!0},{catch:function(i){return this.then(void 0,i)}});var Fg=Qe,Vg=Oe,Ug=Ht,Hg=bi,jg=rn,Gg=en,Yg=Od;Fg({target:"Promise",stat:!0,forced:Yg},{race:function(e){var t=this,s=Hg.f(t),r=s.reject,a=jg(function(){var n=Ug(t.resolve);Gg(e,function(o){Vg(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var qg=Qe,Wg=Oe,zg=bi,Qg=qi.CONSTRUCTOR;qg({target:"Promise",stat:!0,forced:Qg},{reject:function(e){var t=zg.f(this);return Wg(t.reject,void 0,e),t.promise}});var Kg=pt,Jg=ft,Xg=bi,Md=function(i,e){if(Kg(i),Jg(e)&&e.constructor===i)return e;var t=Xg.f(i),s=t.resolve;return s(e),t.promise},Zg=Qe,eS=Ut,tS=Ic,iS=Si,sS=qi.CONSTRUCTOR,rS=Md,aS=eS("Promise"),nS=!sS;Zg({target:"Promise",stat:!0,forced:tS},{resolve:function(e){return rS(nS&&this===aS?iS:this,e)}});var oS=Qe,Ia=Si,lS=je,dS=Ut,uS=ge,cS=fd,jo=Md,hS=Ia&&Ia.prototype,fS=!!Ia&&lS(function(){hS.finally.call({then:function(){}},function(){})});oS({target:"Promise",proto:!0,real:!0,forced:fS},{finally:function(i){var e=cS(this,dS("Promise")),t=uS(i);return this.then(t?function(s){return jo(e,i()).then(function(){return s})}:i,t?function(s){return jo(e,i()).then(function(){throw s})}:i)}});var pS=Ut,dn=pS,vS=dn,mS=vS("Promise","finally"),gS=mS,SS=gS,bS=SS,yS=bS,un=Vs(yS),Se;(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"})(Se||(Se={}));var ze=(i,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Se.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:H(t)}return i};const Go=(i,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class he{constructor(e){this.transitionStarted$=new D,this.transitionEnded$=new D,this.transitionUpdated$=new D,this.forceChanged$=new D,this.stateChangeStarted$=F(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=F(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||R(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 TS=i=>{switch(i){case b.MPEG: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 H(i)}};var U;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const ES=5,$S=5,AS=500,Yo=7e3;class wS{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new he(U.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!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==U.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case U.PLAYING:case U.PAUSED:case U.READY:break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PLAYING:{switch(s){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PAUSED:{switch(s){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}default:H(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(TS(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(F(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new D;e.add(r.pipe(rt(AS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-a)>ES)&&r.next(o),a=o})),e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<$S&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:H(n)}}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=F(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===U.READY&&this.videoState.setState(U.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.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 d=s[e];P(d);const c=Tu(Object.keys(d));P(c);const h=d[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const d=s[e];P(d),r=d.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 d=s[e];P(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const d=s[e];P(d),r=d.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const d=s[e];P(d),r=ze(d.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:I.VIDEO_PIPELINE,message:d,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:l}=this.params.meta;return R(u)&&(o.metadata.title=u),R(l)&&(o.metadata.subtitle=l),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Eu(Yo).subscribe(()=>a(`timeout(${Yo})`)))});un(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:I.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const cn=i=>{i.removeAttribute("src"),i.load()},kS=i=>{try{i.pause(),i.playbackRate=0,cn(i),i.remove()}catch(e){console.error(e)}};class PS{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Da=window.WeakMap?new WeakMap:new PS,jt=i=>{let e=i.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),i.appendChild(e)),Da.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Gt=i=>{const e=Da.get(i);Da.delete(i),e?cn(i):kS(i)},dt=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),l=new re;return r&&l.add(r.subscribe(d=>{const c=i.getState();s(d,c)&&i.setState(d)},a)),s(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),u&&i.setState(d.to)},a)),l},zi=(i,e,t)=>dt(e,()=>i.loop,s=>{R(s)&&(i.loop=s)},{onError:t}),Yt=(i,e,t,s)=>dt(e,()=>({muted:i.muted,volume:i.volume}),r=>{R(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}),yi=(i,e,t,s)=>dt(e,()=>i.playbackRate,r=>{R(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),RS=i=>["__",i.language,i.label].join("|"),_S=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class At{constructor(){this.available$=new D,this.current$=new y(void 0),this.error$=new D,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:I.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(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{R(a)&&this.setInternal(a)},{equal:(a,n)=>R(a)&&R(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{R(a)&&this.setExternal(a)},{equal:(a,n)=>R(a)&&R(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(dt(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(dt(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(x(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(F(x(e,"addtrack"),x(e,"removetrack"),He(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),pe((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(F(x(e,"change"),He(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),pe()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(x(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,l,d,c,h;const f=(l=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&l!==void 0?l:null;f&&f.length&&(this.applyCueSettings((c=(d=o.target)===null||d===void 0?void 0:d.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(x(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;R(t.align)&&(r.align=t.align),R(t.position)&&(r.position=t.position),R(t.size)&&(r.size=t.size),R(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(At.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:RS(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(K(e)||!_S(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class hn{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Bd=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qo=i=>{const e=Bd(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},CS=i=>{const e=Bd(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},IS=3;var DS=(i,e,t=IS)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const qt=i=>{const e=A=>x(i,A).pipe(_s(void 0)),s=F(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>x(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),pe()),r=F(x(i,"progress"),x(i,"timeupdate")).pipe($(()=>DS(i.buffered,i.currentTime))),n=Na().browser===yl.Safari?Ve({play:e("play").pipe(_e()),playing:e("playing")}).pipe(_s(void 0)):e("playing"),o=x(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=x(i,"ratechange").pipe($(()=>i.playbackRate)),l=x(i,"error").pipe(fe(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:I.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),d=x(i,"timeupdate").pipe($(()=>i.currentTime)),c=new D,h=.3;let f;d.subscribe(A=>{i.loop&&R(f)&&R(A)&&f>=i.duration-h&&A<=h&&c.next(f),f=A});const m=x(i,"enterpictureinpicture"),v=x(i,"leavepictureinpicture"),g=new y(CS(i));m.subscribe(()=>g.next(!0)),v.subscribe(()=>g.next(!1));const S=new y(qo(i));return x(i,"fullscreenchange").pipe($(()=>qo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(fe(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:x(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Js=i=>{switch(i){case"mobile":return Le.Q_144P;case"lowest":return Le.Q_240P;case"low":return Le.Q_360P;case"sd":case"medium":return Le.Q_480P;case"hd":case"high":return Le.Q_720P;case"fullhd":case"full":return Le.Q_1080P;case"quadhd":case"quad":return Le.Q_1440P;case"ultrahd":case"ultra":return Le.Q_2160P}},LS=Qe,xS=qs,OS=Ka,MS=Qa;LS({target:"Array",proto:!0},{at:function(e){var t=xS(this),s=OS(t),r=MS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var BS=dn,NS=BS("Array","at"),FS=NS,VS=FS,US=VS,HS=US,lt=Vs(HS);let fn=!1,ut={};const jS=i=>{fn=i},GS=()=>{ut={}},YS=i=>{i(ut)},vs=(i,e)=>{var t;fn&&(ut.meta=(t=ut.meta)!==null&&t!==void 0?t:{},ut.meta[i]=e)};class tt{constructor(e){this.name=e}next(e){var t,s;if(!fn)return;ut.series=(t=ut.series)!==null&&t!==void 0?t:{};const r=(s=ut.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ut.series[this.name]=r}}var xt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(xt||(xt={}));const qS=new tt("best_bitrate"),WS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class zS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const QS='Assertion "ABR Tracks is empty array" failed',Xs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{var h,f,m,v,g;$u(i,QS);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&Mt(E),w=s.considerPlaybackRate&&R(o)?o:1,k=i.filter(N=>!Bt(N.quality)).sort((N,C)=>hi(N.quality,C.quality)?-1:1),q=(f=lt(k,-1))===null||f===void 0?void 0:f.quality,W=(m=lt(k,0))===null||m===void 0?void 0:m.quality,J=K(r)||R(r.min)&&R(r.max)&&$s(r.max,r.min)||R(r.min)&&W&&hi(r.min,W)||R(r.max)&&q&&$s(r.max,q),G=w*WS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),X={},B=k.filter(N=>(A?$s(N.quality,A):!0)?(R(t)&&isFinite(t)&&R(N.bitrate)?t-a>=N.bitrate*G:!0)?s.lazyQualitySwitch&&R(s.minBufferToSwitchUp)&&u&&!Bt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&hi(N.quality,u.quality)?(X[N.quality]=xt.Buffer,!1):!!d&&ua(N.quality,d)?(X[N.quality]=xt.DroppedFramesLimit,!1):J||(K(r.max)||Cs(N.quality,r.max))&&(K(r.min)||ua(N.quality,r.min))?!0:(X[N.quality]=xt.FitsQualityLimits,!1):(X[N.quality]=xt.FitsThroughput,!1):(X[N.quality]=xt.FitsContainer,!1))[0];B&&B.bitrate&&qS.next(B.bitrate);const L=(v=B!=null?B:k[Math.ceil((k.length-1)/2)])!==null&&v!==void 0?v:i[0];L.quality!==((g=l==null?void 0:l.last)===null||g===void 0?void 0:g.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as y,Subject as D,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as K,fromEvent as x,assertNever as H,merge as F,tap as Oi,map as $,observableFrom as He,filterChanged as pe,assertNonNullable as P,debounce as rt,getHighestQuality as Tu,timeout as Eu,getCurrentBrowser as Na,CurrentClientBrowser as yd,combine as Ve,once as Re,mapTo as Rs,filter as fe,VideoQuality as Le,now as de,assertNotEmptyArray as $u,videoSizeToQuality as Mt,isInvariantQuality as Bt,isHigher as fi,isLower as $s,isHigherOrEqual as ua,isLowerOrEqual as Is,interval as Ii,videoQualityToHeight as Au,abortable as Ie,getExponentialDelay as As,throttle as wu,Observable as Fa,observeElementSize as ku,isIOS as Pu,CurrentClientDevice as _u,safeStorage as hr,fillWithDefault as Ru,Logger as Iu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as FT,Subject as VT,Subscription as UT,ValueSubject as HT,VideoQuality as jT}from"@vkontakte/videoplayer-shared/es2015.esm.js";const Cu="2.0.103-dev.af88f935.0";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_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var Ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var ye;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ye||(ye={}));var ca;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ca||(ca={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var bt;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(bt||(bt={}));function te(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 Ce(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,v){a.push([h,f,m,v])>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 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 Du=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 Lu{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ye.NOT_AVAILABLE),this.errorEvent$=new D,this.realCastState$=new y(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=_((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||Du("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.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(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(x(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return H(r.sessionState)}})).add(F(x(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Oi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),He([s.getCastState()])).pipe(pe(),$(xu),Oi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(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;(K(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===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.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:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const xu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return H(i)}};var fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Vs(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}},Ou=je,Us=!Ou(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Td=Us,Ed=Function.prototype,ha=Ed.call,Mu=Td&&Ed.bind.bind(ha,ha),Ge=Td?Mu:function(i){return function(){return ha.apply(i,arguments)}},$d=Ge,Bu=$d({}.toString),Nu=$d("".slice),Vi=function(i){return Nu(Bu(i),8,-1)},Fu=Ge,Vu=je,Uu=Vi,pr=Object,Hu=Fu("".split),ju=Vu(function(){return!pr("z").propertyIsEnumerable(0)})?function(i){return Uu(i)=="String"?Hu(i,""):pr(i)}:pr,Ui=function(i){return i==null},Gu=Ui,Yu=TypeError,Va=function(i){if(Gu(i))throw Yu("Can't call method on "+i);return i},qu=ju,Wu=Va,Hi=function(i){return qu(Wu(i))},Si={},is=function(i){return i&&i.Math==Math&&i},Ee=is(typeof globalThis=="object"&&globalThis)||is(typeof window=="object"&&window)||is(typeof self=="object"&&self)||is(typeof fr=="object"&&fr)||function(){return this}()||fr||Function("return this")(),fa=typeof document=="object"&&document.all,zu=typeof fa=="undefined"&&fa!==void 0,Ad={all:fa,IS_HTMLDDA:zu},wd=Ad,Qu=wd.all,ge=wd.IS_HTMLDDA?function(i){return typeof i=="function"||i===Qu}:function(i){return typeof i=="function"},Ku=Ee,Ju=ge,Rn=Ku.WeakMap,Xu=Ju(Rn)&&/native code/.test(String(Rn)),In=ge,kd=Ad,Zu=kd.all,ft=kd.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:In(i)||i===Zu}:function(i){return typeof i=="object"?i!==null:In(i)},ec=je,$t=!ec(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Vt={},tc=Ee,Cn=ft,pa=tc.document,ic=Cn(pa)&&Cn(pa.createElement),Ua=function(i){return ic?pa.createElement(i):{}},sc=$t,rc=je,ac=Ua,Pd=!sc&&!rc(function(){return Object.defineProperty(ac("div"),"a",{get:function(){return 7}}).a!=7}),nc=$t,oc=je,_d=nc&&oc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),dc=ft,lc=String,uc=TypeError,pt=function(i){if(dc(i))return i;throw uc(lc(i)+" is not an object")},cc=Us,ss=Function.prototype.call,Oe=cc?ss.bind(ss):function(){return ss.apply(ss,arguments)},Ha={},vr=Ha,mr=Ee,hc=ge,Dn=function(i){return hc(i)?i:void 0},Ut=function(i,e){return arguments.length<2?Dn(vr[i])||Dn(mr[i]):vr[i]&&vr[i][e]||mr[i]&&mr[i][e]},fc=Ge,Hs=fc({}.isPrototypeOf),js=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Rd=Ee,gr=js,Ln=Rd.process,xn=Rd.Deno,On=Ln&&Ln.versions||xn&&xn.version,Mn=On&&On.v8,ze,Cs;Mn&&(ze=Mn.split("."),Cs=ze[0]>0&&ze[0]<4?1:+(ze[0]+ze[1]));!Cs&&gr&&(ze=gr.match(/Edge\/(\d+)/),(!ze||ze[1]>=74)&&(ze=gr.match(/Chrome\/(\d+)/),ze&&(Cs=+ze[1])));var Id=Cs,Bn=Id,pc=je,vc=Ee,mc=vc.String,Cd=!!Object.getOwnPropertySymbols&&!pc(function(){var i=Symbol();return!mc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Bn&&Bn<41}),gc=Cd,Dd=gc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Sc=Ut,bc=ge,yc=Hs,Tc=Dd,Ec=Object,Ld=Tc?function(i){return typeof i=="symbol"}:function(i){var e=Sc("Symbol");return bc(e)&&yc(e.prototype,Ec(i))},$c=String,Gs=function(i){try{return $c(i)}catch(e){return"Object"}},Ac=ge,wc=Gs,kc=TypeError,Ht=function(i){if(Ac(i))return i;throw kc(wc(i)+" is not a function")},Pc=Ht,_c=Ui,Ys=function(i,e){var t=i[e];return _c(t)?void 0:Pc(t)},Sr=Oe,br=ge,yr=ft,Rc=TypeError,Ic=function(i,e){var t,s;if(e==="string"&&br(t=i.toString)&&!yr(s=Sr(t,i))||br(t=i.valueOf)&&!yr(s=Sr(t,i))||e!=="string"&&br(t=i.toString)&&!yr(s=Sr(t,i)))return s;throw Rc("Can't convert object to primitive value")},xd={exports:{}},Cc=!0,Nn=Ee,Dc=Object.defineProperty,Lc=function(i,e){try{Dc(Nn,i,{value:e,configurable:!0,writable:!0})}catch(t){Nn[i]=e}return e},xc=Ee,Oc=Lc,Fn="__core-js_shared__",Mc=xc[Fn]||Oc(Fn,{}),ja=Mc,Vn=ja;(xd.exports=function(i,e){return Vn[i]||(Vn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Od=xd.exports,Bc=Va,Nc=Object,qs=function(i){return Nc(Bc(i))},Fc=Ge,Vc=qs,Uc=Fc({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return Uc(Vc(e),t)},Hc=Ge,jc=0,Gc=Math.random(),Yc=Hc(1 .toString),Md=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Yc(++jc+Gc,36)},qc=Ee,Wc=Od,Un=nt,zc=Md,Qc=Cd,Kc=Dd,li=qc.Symbol,Tr=Wc("wks"),Jc=Kc?li.for||li:li&&li.withoutSetter||zc,Pe=function(i){return Un(Tr,i)||(Tr[i]=Qc&&Un(li,i)?li[i]:Jc("Symbol."+i)),Tr[i]},Xc=Oe,Hn=ft,jn=Ld,Zc=Ys,eh=Ic,th=Pe,ih=TypeError,sh=th("toPrimitive"),rh=function(i,e){if(!Hn(i)||jn(i))return i;var t=Zc(i,sh),s;if(t){if(e===void 0&&(e="default"),s=Xc(t,i,e),!Hn(s)||jn(s))return s;throw ih("Can't convert object to primitive value")}return e===void 0&&(e="number"),eh(i,e)},ah=rh,nh=Ld,Ga=function(i){var e=ah(i,"string");return nh(e)?e:e+""},oh=$t,dh=Pd,lh=_d,rs=pt,Gn=Ga,uh=TypeError,Er=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,$r="enumerable",Ar="configurable",wr="writable";Vt.f=oh?lh?function(e,t,s){if(rs(e),t=Gn(t),rs(s),typeof e=="function"&&t==="prototype"&&"value"in s&&wr in s&&!s[wr]){var r=ch(e,t);r&&r[wr]&&(e[t]=s.value,s={configurable:Ar in s?s[Ar]:r[Ar],enumerable:$r in s?s[$r]:r[$r],writable:!1})}return Er(e,t,s)}:Er:function(e,t,s){if(rs(e),t=Gn(t),rs(s),dh)try{return Er(e,t,s)}catch(r){}if("get"in s||"set"in s)throw uh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ws=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},hh=$t,fh=Vt,ph=Ws,ji=hh?function(i,e,t){return fh.f(i,e,ph(1,t))}:function(i,e,t){return i[e]=t,i},vh=Od,mh=Md,Yn=vh("keys"),Ya=function(i){return Yn[i]||(Yn[i]=mh(i))},qa={},gh=Xu,Bd=Ee,Sh=ft,bh=ji,kr=nt,Pr=ja,yh=Ya,Th=qa,qn="Object already initialized",va=Bd.TypeError,Eh=Bd.WeakMap,Ds,Mi,Ls,$h=function(i){return Ls(i)?Mi(i):Ds(i,{})},Ah=function(i){return function(e){var t;if(!Sh(e)||(t=Mi(e)).type!==i)throw va("Incompatible receiver, "+i+" required");return t}};if(gh||Pr.state){var Ze=Pr.state||(Pr.state=new Eh);Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ds=function(i,e){if(Ze.has(i))throw va(qn);return e.facade=i,Ze.set(i,e),e},Mi=function(i){return Ze.get(i)||{}},Ls=function(i){return Ze.has(i)}}else{var ei=yh("state");Th[ei]=!0,Ds=function(i,e){if(kr(i,ei))throw va(qn);return e.facade=i,bh(i,ei,e),e},Mi=function(i){return kr(i,ei)?i[ei]:{}},Ls=function(i){return kr(i,ei)}}var Nd={set:Ds,get:Mi,has:Ls,enforce:$h,getterFor:Ah},wh=Us,Fd=Function.prototype,Wn=Fd.apply,zn=Fd.call,Vd=typeof Reflect=="object"&&Reflect.apply||(wh?zn.bind(Wn):function(){return zn.apply(Wn,arguments)}),kh=Vi,Ph=Ge,Ud=function(i){if(kh(i)==="Function")return Ph(i)},Wa={},Hd={},jd={}.propertyIsEnumerable,Gd=Object.getOwnPropertyDescriptor,_h=Gd&&!jd.call({1:2},1);Hd.f=_h?function(e){var t=Gd(this,e);return!!t&&t.enumerable}:jd;var Rh=$t,Ih=Oe,Ch=Hd,Dh=Ws,Lh=Hi,xh=Ga,Oh=nt,Mh=Pd,Qn=Object.getOwnPropertyDescriptor;Wa.f=Rh?Qn:function(e,t){if(e=Lh(e),t=xh(t),Mh)try{return Qn(e,t)}catch(s){}if(Oh(e,t))return Dh(!Ih(Ch.f,e,t),e[t])};var Bh=je,Nh=ge,Fh=/#|\.prototype\./,Gi=function(i,e){var t=Uh[Vh(i)];return t==jh?!0:t==Hh?!1:Nh(e)?Bh(e):!!e},Vh=Gi.normalize=function(i){return String(i).replace(Fh,".").toLowerCase()},Uh=Gi.data={},Hh=Gi.NATIVE="N",jh=Gi.POLYFILL="P",Yd=Gi,Kn=Ud,Gh=Ht,Yh=Us,qh=Kn(Kn.bind),zs=function(i,e){return Gh(i),e===void 0?i:Yh?qh(i,e):function(){return i.apply(e,arguments)}},as=Ee,Wh=Vd,zh=Ud,Qh=ge,Kh=Wa.f,Jh=Yd,ti=Ha,Xh=zs,ii=ji,Jn=nt,Zh=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 Wh(i,this,arguments)};return e.prototype=i.prototype,e},Ke=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?ti:ti[t]||ii(ti,t,{})[t],u=o.prototype,d,l,c,h,f,m,v,g,S;for(h in e)d=Jh(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Jn(n,h),m=o[h],l&&(i.dontCallGetSet?(S=Kh(n,h),v=S&&S.value):v=n[h]),f=l&&v?v:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?g=Xh(f,as):i.wrap&&l?g=Zh(f):a&&Qh(f)?g=zh(f):g=f,(i.sham||f&&f.sham||m&&m.sham)&&ii(g,"sham",!0),ii(o,h,g),a&&(c=t+"Prototype",Jn(ti,c)||ii(ti,c,{}),ii(ti[c],h,f),i.real&&u&&(d||!u[h])&&ii(u,h,f)))},ma=$t,ef=nt,qd=Function.prototype,tf=ma&&Object.getOwnPropertyDescriptor,za=ef(qd,"name"),sf=za&&function(){}.name==="something",rf=za&&(!ma||ma&&tf(qd,"name").configurable),af={EXISTS:za,PROPER:sf,CONFIGURABLE:rf},Wd={},nf=Math.ceil,of=Math.floor,df=Math.trunc||function(e){var t=+e;return(t>0?of:nf)(t)},lf=df,Qa=function(i){var e=+i;return e!==e||e===0?0:lf(e)},uf=Qa,cf=Math.max,hf=Math.min,ff=function(i,e){var t=uf(i);return t<0?cf(t+e,0):hf(t,e)},pf=Qa,vf=Math.min,mf=function(i){return i>0?vf(pf(i),9007199254740991):0},gf=mf,Ka=function(i){return gf(i.length)},Sf=Hi,bf=ff,yf=Ka,Xn=function(i){return function(e,t,s){var r=Sf(e),a=yf(r),n=bf(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}},Tf={includes:Xn(!0),indexOf:Xn(!1)},Ef=Ge,_r=nt,$f=Hi,Af=Tf.indexOf,wf=qa,Zn=Ef([].push),kf=function(i,e){var t=$f(i),s=0,r=[],a;for(a in t)!_r(wf,a)&&_r(t,a)&&Zn(r,a);for(;e.length>s;)_r(t,a=e[s++])&&(~Af(r,a)||Zn(r,a));return r},zd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Pf=kf,_f=zd,Rf=Object.keys||function(e){return Pf(e,_f)},If=$t,Cf=_d,Df=Vt,Lf=pt,xf=Hi,Of=Rf;Wd.f=If&&!Cf?Object.defineProperties:function(e,t){Lf(e);for(var s=xf(t),r=Of(t),a=r.length,n=0,o;a>n;)Df.f(e,o=r[n++],s[o]);return e};var Mf=Ut,Qd=Mf("document","documentElement"),Bf=pt,Nf=Wd,eo=zd,Ff=qa,Vf=Qd,Uf=Ua,Hf=Ya,to=">",io="<",ga="prototype",Sa="script",Kd=Hf("IE_PROTO"),Rr=function(){},Jd=function(i){return io+Sa+to+i+io+"/"+Sa+to},so=function(i){i.write(Jd("")),i.close();var e=i.parentWindow.Object;return i=null,e},jf=function(){var i=Uf("iframe"),e="java"+Sa+":",t;return i.style.display="none",Vf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Jd("document.F=Object")),t.close(),t.F},ns,ws=function(){try{ns=new ActiveXObject("htmlfile")}catch(e){}ws=typeof document!="undefined"?document.domain&&ns?so(ns):jf():so(ns);for(var i=eo.length;i--;)delete ws[ga][eo[i]];return ws()};Ff[Kd]=!0;var Xd=Object.create||function(e,t){var s;return e!==null?(Rr[ga]=Bf(e),s=new Rr,Rr[ga]=null,s[Kd]=e):s=ws(),t===void 0?s:Nf.f(s,t)},Gf=je,Yf=!Gf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),qf=nt,Wf=ge,zf=qs,Qf=Ya,Kf=Yf,ro=Qf("IE_PROTO"),ba=Object,Jf=ba.prototype,Zd=Kf?ba.getPrototypeOf:function(i){var e=zf(i);if(qf(e,ro))return e[ro];var t=e.constructor;return Wf(t)&&e instanceof t?t.prototype:e instanceof ba?Jf:null},Xf=ji,Ja=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Xf(i,e,t),i},Zf=je,ep=ge,tp=ft,ip=Xd,ao=Zd,sp=Ja,rp=Pe,ya=rp("iterator"),el=!1,ct,Ir,Cr;[].keys&&(Cr=[].keys(),"next"in Cr?(Ir=ao(ao(Cr)),Ir!==Object.prototype&&(ct=Ir)):el=!0);var ap=!tp(ct)||Zf(function(){var i={};return ct[ya].call(i)!==i});ap?ct={}:ct=ip(ct);ep(ct[ya])||sp(ct,ya,function(){return this});var tl={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:el},np=Pe,op=np("toStringTag"),il={};il[op]="z";var Xa=String(il)==="[object z]",dp=Xa,lp=ge,ks=Vi,up=Pe,cp=up("toStringTag"),hp=Object,fp=ks(function(){return arguments}())=="Arguments",pp=function(i,e){try{return i[e]}catch(t){}},Yi=dp?ks:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=pp(e=hp(i),cp))=="string"?t:fp?ks(e):(s=ks(e))=="Object"&&lp(e.callee)?"Arguments":s},vp=Xa,mp=Yi,gp=vp?{}.toString:function(){return"[object "+mp(this)+"]"},Sp=Xa,bp=Vt.f,yp=ji,Tp=nt,Ep=gp,$p=Pe,no=$p("toStringTag"),Za=function(i,e,t,s){if(i){var r=t?i:i.prototype;Tp(r,no)||bp(r,no,{configurable:!0,value:e}),s&&!Sp&&yp(r,"toString",Ep)}},Ap=tl.IteratorPrototype,wp=Xd,kp=Ws,Pp=Za,_p=Si,Rp=function(){return this},Ip=function(i,e,t,s){var r=e+" Iterator";return i.prototype=wp(Ap,{next:kp(+!s,t)}),Pp(i,r,!1,!0),_p[r]=Rp,i},Cp=Ke,Dp=Oe,sl=af,Lp=Ip,xp=Zd,Op=Za,oo=Ja,Mp=Pe,lo=Si,rl=tl,Bp=sl.PROPER;sl.CONFIGURABLE;rl.IteratorPrototype;var os=rl.BUGGY_SAFARI_ITERATORS,Dr=Mp("iterator"),uo="keys",ds="values",co="entries",Np=function(){return this},Fp=function(i,e,t,s,r,a,n){Lp(t,e,s);var o=function(S){if(S===r&&h)return h;if(!os&&S in l)return l[S];switch(S){case uo:return function(){return new t(this,S)};case ds:return function(){return new t(this,S)};case co:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[Dr]||l["@@iterator"]||r&&l[r],h=!os&&c||o(r),f=e=="Array"&&l.entries||c,m,v,g;if(f&&(m=xp(f.call(new i)),m!==Object.prototype&&m.next&&(Op(m,u,!0,!0),lo[u]=Np)),Bp&&r==ds&&c&&c.name!==ds&&(d=!0,h=function(){return Dp(c,this)}),r)if(v={values:o(ds),keys:a?h:o(uo),entries:o(co)},n)for(g in v)(os||d||!(g in l))&&oo(l,g,v[g]);else Cp({target:e,proto:!0,forced:os||d},v);return n&&l[Dr]!==h&&oo(l,Dr,h,{name:r}),lo[e]=h,v},Vp=function(i,e){return{value:i,done:e}},Up=Hi,ho=Si,al=Nd;Vt.f;var Hp=Fp,ls=Vp,nl="Array Iterator",jp=al.set,Gp=al.getterFor(nl);Hp(Array,"Array",function(i,e){jp(this,{type:nl,target:Up(i),index:0,kind:e})},function(){var i=Gp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ls(void 0,!0)):t=="keys"?ls(s,!1):t=="values"?ls(e[s],!1):ls([s,e[s]],!1)},"values");ho.Arguments=ho.Array;var Yp=Pe,qp=Si,Wp=Yp("iterator"),zp=Array.prototype,Qp=function(i){return i!==void 0&&(qp.Array===i||zp[Wp]===i)},Kp=Yi,fo=Ys,Jp=Ui,Xp=Si,Zp=Pe,ev=Zp("iterator"),ol=function(i){if(!Jp(i))return fo(i,ev)||fo(i,"@@iterator")||Xp[Kp(i)]},tv=Oe,iv=Ht,sv=pt,rv=Gs,av=ol,nv=TypeError,ov=function(i,e){var t=arguments.length<2?av(i):e;if(iv(t))return sv(tv(t,i));throw nv(rv(i)+" is not iterable")},dv=Oe,po=pt,lv=Ys,uv=function(i,e,t){var s,r;po(i);try{if(s=lv(i,"return"),!s){if(e==="throw")throw t;return t}s=dv(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return po(s),t},cv=zs,hv=Oe,fv=pt,pv=Gs,vv=Qp,mv=Ka,vo=Hs,gv=ov,Sv=ol,mo=uv,bv=TypeError,Ps=function(i,e){this.stopped=i,this.result=e},go=Ps.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=cv(e,s),d,l,c,h,f,m,v,g=function(E){return d&&mo(d,"normal",E),new Ps(!0,E)},S=function(E){return r?(fv(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)d=i.iterator;else if(n)d=i;else{if(l=Sv(i),!l)throw bv(pv(i)+" is not iterable");if(vv(l)){for(c=0,h=mv(i);h>c;c++)if(f=S(i[c]),f&&vo(go,f))return f;return new Ps(!1)}d=gv(i,l)}for(m=a?i.next:d.next;!(v=hv(m,d)).done;){try{f=S(v.value)}catch(E){mo(d,"throw",E)}if(typeof f=="object"&&f&&vo(go,f))return f}return new Ps(!1)},yv=Ga,Tv=Vt,Ev=Ws,$v=function(i,e,t){var s=yv(e);s in i?Tv.f(i,s,Ev(0,t)):i[s]=t},Av=Ke,wv=en,kv=$v;Av({target:"Object",stat:!0},{fromEntries:function(e){var t={};return wv(e,function(s,r){kv(t,s,r)},{AS_ENTRIES:!0}),t}});var Pv=Ha,_v=Pv.Object.fromEntries,Rv={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},Iv=Rv,Cv=Ee,Dv=Yi,Lv=ji,So=Si,xv=Pe,bo=xv("toStringTag");for(var Lr in Iv){var yo=Cv[Lr],xr=yo&&yo.prototype;xr&&Dv(xr)!==bo&&Lv(xr,bo,Lr),So[Lr]=So.Array}var Ov=_v,Mv=Ov,Bv=Mv,Nv=Bv,xs=Vs(Nv),Fv=Vi,Qs=typeof process!="undefined"&&Fv(process)=="process",Vv=Vt,Uv=function(i,e,t){return Vv.f(i,e,t)},Hv=Ut,jv=Uv,Gv=Pe,Yv=$t,To=Gv("species"),qv=function(i){var e=Hv(i);Yv&&e&&!e[To]&&jv(e,To,{configurable:!0,get:function(){return this}})},Wv=Hs,zv=TypeError,Qv=function(i,e){if(Wv(e,i))return i;throw zv("Incorrect invocation")},Kv=Ge,Jv=ge,Ta=ja,Xv=Kv(Function.toString);Jv(Ta.inspectSource)||(Ta.inspectSource=function(i){return Xv(i)});var dl=Ta.inspectSource,Zv=Ge,em=je,ll=ge,tm=Yi,im=Ut,sm=dl,ul=function(){},rm=[],cl=im("Reflect","construct"),tn=/^\s*(?:class|function)\b/,am=Zv(tn.exec),nm=!tn.exec(ul),Pi=function(e){if(!ll(e))return!1;try{return cl(ul,rm,e),!0}catch(t){return!1}},hl=function(e){if(!ll(e))return!1;switch(tm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nm||!!am(tn,sm(e))}catch(t){return!0}};hl.sham=!0;var om=!cl||em(function(){var i;return Pi(Pi.call)||!Pi(Object)||!Pi(function(){i=!0})||i})?hl:Pi,dm=om,lm=Gs,um=TypeError,cm=function(i){if(dm(i))return i;throw um(lm(i)+" is not a constructor")},Eo=pt,hm=cm,fm=Ui,pm=Pe,vm=pm("species"),fl=function(i,e){var t=Eo(i).constructor,s;return t===void 0||fm(s=Eo(t)[vm])?e:hm(s)},mm=Ge,gm=mm([].slice),Sm=TypeError,bm=function(i,e){if(i<e)throw Sm("Not enough arguments");return i},ym=js,pl=/(?:ipad|iphone|ipod).*applewebkit/i.test(ym),xe=Ee,Tm=Vd,Em=zs,$o=ge,$m=nt,vl=je,Ao=Qd,Am=gm,wo=Ua,wm=bm,km=pl,Pm=Qs,Ea=xe.setImmediate,$a=xe.clearImmediate,_m=xe.process,Or=xe.Dispatch,Rm=xe.Function,ko=xe.MessageChannel,Im=xe.String,Mr=0,Ci={},Po="onreadystatechange",Bi,It,Br,Nr;vl(function(){Bi=xe.location});var sn=function(i){if($m(Ci,i)){var e=Ci[i];delete Ci[i],e()}},Fr=function(i){return function(){sn(i)}},_o=function(i){sn(i.data)},Ro=function(i){xe.postMessage(Im(i),Bi.protocol+"//"+Bi.host)};(!Ea||!$a)&&(Ea=function(e){wm(arguments.length,1);var t=$o(e)?e:Rm(e),s=Am(arguments,1);return Ci[++Mr]=function(){Tm(t,void 0,s)},It(Mr),Mr},$a=function(e){delete Ci[e]},Pm?It=function(i){_m.nextTick(Fr(i))}:Or&&Or.now?It=function(i){Or.now(Fr(i))}:ko&&!km?(Br=new ko,Nr=Br.port2,Br.port1.onmessage=_o,It=Em(Nr.postMessage,Nr)):xe.addEventListener&&$o(xe.postMessage)&&!xe.importScripts&&Bi&&Bi.protocol!=="file:"&&!vl(Ro)?(It=Ro,xe.addEventListener("message",_o,!1)):Po in wo("script")?It=function(i){Ao.appendChild(wo("script"))[Po]=function(){Ao.removeChild(this),sn(i)}}:It=function(i){setTimeout(Fr(i),0)});var ml={set:Ea,clear:$a},gl=function(){this.head=null,this.tail=null};gl.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 Sl=gl,Cm=js,Dm=/ipad|iphone|ipod/i.test(Cm)&&typeof Pebble!="undefined",Lm=js,xm=/web0s(?!.*chrome)/i.test(Lm),Nt=Ee,Io=zs,Om=Wa.f,Vr=ml.set,Mm=Sl,Bm=pl,Nm=Dm,Fm=xm,Ur=Qs,Co=Nt.MutationObserver||Nt.WebKitMutationObserver,Do=Nt.document,Lo=Nt.process,us=Nt.Promise,xo=Om(Nt,"queueMicrotask"),Aa=xo&&xo.value,si,Hr,jr,cs,Oo;if(!Aa){var hs=new Mm,fs=function(){var i,e;for(Ur&&(i=Lo.domain)&&i.exit();e=hs.get();)try{e()}catch(t){throw hs.head&&si(),t}i&&i.enter()};!Bm&&!Ur&&!Fm&&Co&&Do?(Hr=!0,jr=Do.createTextNode(""),new Co(fs).observe(jr,{characterData:!0}),si=function(){jr.data=Hr=!Hr}):!Nm&&us&&us.resolve?(cs=us.resolve(void 0),cs.constructor=us,Oo=Io(cs.then,cs),si=function(){Oo(fs)}):Ur?si=function(){Lo.nextTick(fs)}:(Vr=Io(Vr,Nt),si=function(){Vr(fs)}),Aa=function(i){hs.head||si(),hs.add(i)}}var Vm=Aa,Um=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}}},Hm=Ee,bi=Hm.Promise,bl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",jm=bl,Gm=Qs,Ym=!jm&&!Gm&&typeof window=="object"&&typeof document=="object",qm=Ee,Di=bi,Wm=ge,zm=Yd,Qm=dl,Km=Pe,Jm=Ym,Xm=bl,Gr=Id,Mo=Di&&Di.prototype,Zm=Km("species"),wa=!1,yl=Wm(qm.PromiseRejectionEvent),eg=zm("Promise",function(){var i=Qm(Di),e=i!==String(Di);if(!e&&Gr===66||!(Mo.catch&&Mo.finally))return!0;if(!Gr||Gr<51||!/native code/.test(i)){var t=new Di(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Zm]=s,wa=t.then(function(){})instanceof s,!wa)return!0}return!e&&(Jm||Xm)&&!yl}),qi={CONSTRUCTOR:eg,REJECTION_EVENT:yl,SUBCLASSING:wa},yi={},Bo=Ht,tg=TypeError,ig=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw tg("Bad Promise constructor");e=s,t=r}),this.resolve=Bo(e),this.reject=Bo(t)};yi.f=function(i){return new ig(i)};var sg=Ke,Os=Qs,Et=Ee,Wi=Oe,rg=Ja,ag=Za,ng=qv,og=Ht,ka=ge,dg=ft,lg=Qv,ug=fl,Tl=ml.set,an=Vm,cg=Um,hg=rn,fg=Sl,El=Nd,Pa=bi,nn=qi,$l=yi,Ks="Promise",Al=nn.CONSTRUCTOR,pg=nn.REJECTION_EVENT;nn.SUBCLASSING;var Yr=El.getterFor(Ks),vg=El.set,mg=Pa&&Pa.prototype,ui=Pa,qr=mg,wl=Et.TypeError,_a=Et.document,on=Et.process,Ra=$l.f,gg=Ra,Sg=!!(_a&&_a.createEvent&&Et.dispatchEvent),kl="unhandledrejection",bg="rejectionhandled",No=0,Pl=1,yg=2,dn=1,_l=2,ps,Fo,Tg,Rl=function(i){var e;return dg(i)&&ka(e=i.then)?e:!1},Il=function(i,e){var t=e.value,s=e.state==Pl,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===_l&&$g(e),e.rejection=dn),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(wl("Promise-chain cycle")):(d=Rl(u))?Wi(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Cl=function(i,e){i.notified||(i.notified=!0,an(function(){for(var t=i.reactions,s;s=t.get();)Il(s,i);i.notified=!1,e&&!i.rejection&&Eg(i)}))},Dl=function(i,e,t){var s,r;Sg?(s=_a.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Et.dispatchEvent(s)):s={promise:e,reason:t},!pg&&(r=Et["on"+i])?r(s):i===kl&&cg("Unhandled promise rejection",t)},Eg=function(i){Wi(Tl,Et,function(){var e=i.facade,t=i.value,s=Vo(i),r;if(s&&(r=hg(function(){Os?on.emit("unhandledRejection",t,e):Dl(kl,e,t)}),i.rejection=Os||Vo(i)?_l:dn,r.error))throw r.value})},Vo=function(i){return i.rejection!==dn&&!i.parent},$g=function(i){Wi(Tl,Et,function(){var e=i.facade;Os?on.emit("rejectionHandled",e):Dl(bg,e,i.value)})},ci=function(i,e,t){return function(s){i(e,s,t)}},pi=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=yg,Cl(i,!0))},Ia=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw wl("Promise can't be resolved itself");var s=Rl(e);s?an(function(){var r={done:!1};try{Wi(s,e,ci(Ia,r,i),ci(pi,r,i))}catch(a){pi(r,a,i)}}):(i.value=e,i.state=Pl,Cl(i,!1))}catch(r){pi({done:!1},r,i)}}};Al&&(ui=function(e){lg(this,qr),og(e),Wi(ps,this);var t=Yr(this);try{e(ci(Ia,t),ci(pi,t))}catch(s){pi(t,s)}},qr=ui.prototype,ps=function(e){vg(this,{type:Ks,done:!1,notified:!1,parent:!1,reactions:new fg,rejection:!1,state:No,value:void 0})},ps.prototype=rg(qr,"then",function(e,t){var s=Yr(this),r=Ra(ug(this,ui));return s.parent=!0,r.ok=ka(e)?e:!0,r.fail=ka(t)&&t,r.domain=Os?on.domain:void 0,s.state==No?s.reactions.add(r):an(function(){Il(r,s)}),r.promise}),Fo=function(){var i=new ps,e=Yr(i);this.promise=i,this.resolve=ci(Ia,e),this.reject=ci(pi,e)},$l.f=Ra=function(i){return i===ui||i===Tg?new Fo(i):gg(i)});sg({global:!0,constructor:!0,wrap:!0,forced:Al},{Promise:ui});ag(ui,Ks,!1,!0);ng(Ks);var Ag=Pe,Ll=Ag("iterator"),xl=!1;try{var wg=0,Uo={next:function(){return{done:!!wg++}},return:function(){xl=!0}};Uo[Ll]=function(){return this},Array.from(Uo,function(){throw 2})}catch(i){}var kg=function(i,e){if(!e&&!xl)return!1;var t=!1;try{var s={};s[Ll]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Pg=bi,_g=kg,Rg=qi.CONSTRUCTOR,Ol=Rg||!_g(function(i){Pg.all(i).then(void 0,function(){})}),Ig=Ke,Cg=Oe,Dg=Ht,Lg=yi,xg=rn,Og=en,Mg=Ol;Ig({target:"Promise",stat:!0,forced:Mg},{all:function(e){var t=this,s=Lg.f(t),r=s.resolve,a=s.reject,n=xg(function(){var o=Dg(t.resolve),u=[],d=0,l=1;Og(e,function(c){var h=d++,f=!1;l++,Cg(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 Bg=Ke,Ng=qi.CONSTRUCTOR,Ho=bi;Ho&&Ho.prototype;Bg({target:"Promise",proto:!0,forced:Ng,real:!0},{catch:function(i){return this.then(void 0,i)}});var Fg=Ke,Vg=Oe,Ug=Ht,Hg=yi,jg=rn,Gg=en,Yg=Ol;Fg({target:"Promise",stat:!0,forced:Yg},{race:function(e){var t=this,s=Hg.f(t),r=s.reject,a=jg(function(){var n=Ug(t.resolve);Gg(e,function(o){Vg(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var qg=Ke,Wg=Oe,zg=yi,Qg=qi.CONSTRUCTOR;qg({target:"Promise",stat:!0,forced:Qg},{reject:function(e){var t=zg.f(this);return Wg(t.reject,void 0,e),t.promise}});var Kg=pt,Jg=ft,Xg=yi,Ml=function(i,e){if(Kg(i),Jg(e)&&e.constructor===i)return e;var t=Xg.f(i),s=t.resolve;return s(e),t.promise},Zg=Ke,eS=Ut,tS=Cc,iS=bi,sS=qi.CONSTRUCTOR,rS=Ml,aS=eS("Promise"),nS=!sS;Zg({target:"Promise",stat:!0,forced:tS},{resolve:function(e){return rS(nS&&this===aS?iS:this,e)}});var oS=Ke,Ca=bi,dS=je,lS=Ut,uS=ge,cS=fl,jo=Ml,hS=Ca&&Ca.prototype,fS=!!Ca&&dS(function(){hS.finally.call({then:function(){}},function(){})});oS({target:"Promise",proto:!0,real:!0,forced:fS},{finally:function(i){var e=cS(this,lS("Promise")),t=uS(i);return this.then(t?function(s){return jo(e,i()).then(function(){return s})}:i,t?function(s){return jo(e,i()).then(function(){throw s})}:i)}});var pS=Ut,ln=pS,vS=ln,mS=vS("Promise","finally"),gS=mS,SS=gS,bS=SS,yS=bS,un=Vs(yS),Se;(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"})(Se||(Se={}));var Qe=(i,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Se.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:H(t)}return i};const Go=(i,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class he{constructor(e){this.transitionStarted$=new D,this.transitionEnded$=new D,this.transitionUpdated$=new D,this.forceChanged$=new D,this.stateChangeStarted$=F(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=F(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||_(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 TS=i=>{switch(i){case b.MPEG: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 H(i)}};var U;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const ES=5,$S=5,AS=500,Yo=7e3;class wS{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new he(U.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!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==U.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case U.PLAYING:case U.PAUSED:case U.READY:break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PLAYING:{switch(s){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}case p.PAUSED:{switch(s){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:H(s)}break}default:H(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(TS(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(F(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new D;e.add(r.pipe(rt(AS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-a)>ES)&&r.next(o),a=o})),e.add(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<$S&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:H(n)}}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(x(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=F(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===U.READY&&this.videoState.setState(U.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.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=Tu(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=Qe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}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:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(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===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Eu(Yo).subscribe(()=>a(`timeout(${Yo})`)))});un(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const cn=i=>{i.removeAttribute("src"),i.load()},kS=i=>{try{i.pause(),i.playbackRate=0,cn(i),i.remove()}catch(e){console.error(e)}};class PS{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Da=window.WeakMap?new WeakMap:new PS,jt=i=>{let e=i.querySelector("video");const t=!!e;return e?cn(e):(e=document.createElement("video"),i.appendChild(e)),Da.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Gt=i=>{const e=Da.get(i);Da.delete(i),e?cn(i):kS(i)},lt=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new re;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},zi=(i,e,t)=>lt(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),Yt=(i,e,t,s)=>lt(e,()=>({muted:i.muted,volume:i.volume}),r=>{_(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}),Ti=(i,e,t,s)=>lt(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),_S=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 At{constructor(){this.available$=new D,this.current$=new y(void 0),this.error$=new D,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.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(lt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(lt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(lt(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(lt(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(x(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(F(x(e,"addtrack"),x(e,"removetrack"),He(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),pe((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(F(x(e,"change"),He(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),pe()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(x(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,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(x(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(At.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:_S(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(K(e)||!RS(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class hn{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Bl=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qo=i=>{const e=Bl(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},IS=i=>{const e=Bl(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},CS=3;var DS=(i,e,t=CS)=>{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 qt=i=>{const e=A=>x(i,A).pipe(Rs(void 0)),s=F(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>x(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),pe()),r=F(x(i,"progress"),x(i,"timeupdate")).pipe($(()=>DS(i.buffered,i.currentTime))),n=Na().browser===yd.Safari?Ve({play:e("play").pipe(Re()),playing:e("playing")}).pipe(Rs(void 0)):e("playing"),o=x(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=x(i,"ratechange").pipe($(()=>i.playbackRate)),d=x(i,"error").pipe(fe(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),l=x(i,"timeupdate").pipe($(()=>i.currentTime)),c=new D,h=.3;let f;l.subscribe(A=>{i.loop&&_(f)&&_(A)&&f>=i.duration-h&&A<=h&&c.next(f),f=A});const m=x(i,"enterpictureinpicture"),v=x(i,"leavepictureinpicture"),g=new y(IS(i));m.subscribe(()=>g.next(!0)),v.subscribe(()=>g.next(!1));const S=new y(qo(i));return x(i,"fullscreenchange").pipe($(()=>qo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(fe(()=>!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$:x(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Js=i=>{switch(i){case"mobile":return Le.Q_144P;case"lowest":return Le.Q_240P;case"low":return Le.Q_360P;case"sd":case"medium":return Le.Q_480P;case"hd":case"high":return Le.Q_720P;case"fullhd":case"full":return Le.Q_1080P;case"quadhd":case"quad":return Le.Q_1440P;case"ultrahd":case"ultra":return Le.Q_2160P}},LS=Ke,xS=qs,OS=Ka,MS=Qa;LS({target:"Array",proto:!0},{at:function(e){var t=xS(this),s=OS(t),r=MS(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var BS=ln,NS=BS("Array","at"),FS=NS,VS=FS,US=VS,HS=US,dt=Vs(HS);let fn=!1,ut={};const jS=i=>{fn=i},GS=()=>{ut={}},YS=i=>{i(ut)},vs=(i,e)=>{var t;fn&&(ut.meta=(t=ut.meta)!==null&&t!==void 0?t:{},ut.meta[i]=e)};class tt{constructor(e){this.name=e}next(e){var t,s;if(!fn)return;ut.series=(t=ut.series)!==null&&t!==void 0?t:{};const r=(s=ut.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),ut.series[this.name]=r}}var xt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(xt||(xt={}));const qS=new tt("best_bitrate"),WS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class zS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=de()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const QS='Assertion "ABR Tracks is empty array" failed',Xs=(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,v,g;$u(i,QS);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&Mt(E),w=s.considerPlaybackRate&&_(o)?o:1,k=i.filter(N=>!Bt(N.quality)).sort((N,I)=>fi(N.quality,I.quality)?-1:1),q=(f=dt(k,-1))===null||f===void 0?void 0:f.quality,W=(m=dt(k,0))===null||m===void 0?void 0:m.quality,J=K(r)||_(r.min)&&_(r.max)&&$s(r.max,r.min)||_(r.min)&&W&&fi(r.min,W)||_(r.max)&&q&&$s(r.max,q),G=w*WS(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),X={},B=k.filter(N=>(A?$s(N.quality,A):!0)?(_(t)&&isFinite(t)&&_(N.bitrate)?t-a>=N.bitrate*G:!0)?s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!Bt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&fi(N.quality,u.quality)?(X[N.quality]=xt.Buffer,!1):!!l&&ua(N.quality,l)?(X[N.quality]=xt.DroppedFramesLimit,!1):J||(K(r.max)||Is(N.quality,r.max))&&(K(r.min)||ua(N.quality,r.min))?!0:(X[N.quality]=xt.FitsQualityLimits,!1):(X[N.quality]=xt.FitsThroughput,!1):(X[N.quality]=xt.FitsContainer,!1))[0];B&&B.bitrate&&qS.next(B.bitrate);const L=(v=B!=null?B:k[Math.ceil((k.length-1)/2)])!==null&&v!==void 0?v:i[0];L.quality!==((g=d==null?void 0:d.last)===null||g===void 0?void 0:g.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(N=>`{ id: ${N.id}, quality: ${N.quality}, bitrate: ${N.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(s!=null?s:{}).map(([N,
|
|
12
|
+
${Object.entries(s!=null?s:{}).map(([N,I])=>`${N}: ${I}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
@@ -21,20 +21,20 @@ import{ValueSubject as y,Subject as D,Subscription as re,isNonNullable as R,Erro
|
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
22
|
bitrateFactor: ${G},
|
|
23
23
|
minBufferToSwitchUp: ${s.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
24
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
25
25
|
limitsAreInvalid: ${J},
|
|
26
26
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(X).map(([N,
|
|
30
|
+
${Object.entries(X).map(([N,I])=>`${N}: ${I}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
33
|
[best track] ${B==null?void 0:B.quality}
|
|
34
34
|
[selected track] ${L==null?void 0:L.quality}
|
|
35
|
-
`});const ae=L&&
|
|
35
|
+
`});const ae=L&&d&&d.history[L.id]&&de()-d.history[L.id]<=s.trackCooldown&&(!d.last||L.id!==d.last.id);if(L!=null&&L.id&&d&&!ae&&d.recordSelection(L),ae&&(d!=null&&d.last)){const N=d.last;return d==null||d.recordSwitch(N),c({message:`
|
|
36
36
|
[last selected] ${N==null?void 0:N.quality}
|
|
37
|
-
`}),N}return l==null||l.recordSwitch(L),L};var at=i=>new URL(i).hostname;const Wo=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 Wt=i=>te(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Wo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return Wo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return le()}function Nd(i){return we()-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 l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function KS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Rs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,l=0,d,c,h=!1,f="arraybuffer",m=7e3,v=2e3,g=()=>{if(u)return;P(d);const B=Nd(d);let L;if(B<v){L=v-B,setTimeout(g,L);return}v*=2,v>m&&(v=m),n&&n.abort(),n=new r,q()};const S=B=>(a=B,ee),E=B=>(c=B,ee),A=()=>(f="json",ee),w=()=>{if(!u){if(--l>=0){g(),s&&s();return}u=!0,c&&c(),t&&t()}},k=B=>(h=B,ee),q=()=>{d=we(),n=new r,n.open("get",i);let B=0,L,ae=0;const N=()=>(P(d),Math.max(d,Math.max(L||0,ae||0)));if(a&&n.addEventListener("progress",C=>{const Z=we();a.updateChunk&&C.loaded>B&&(a.updateChunk(N(),C.loaded-B),B=C.loaded,L=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const Z=n.response.byteLength-B;Z&&a.updateChunk&&a.updateChunk(N(),Z)}n.responseType==="json"&&!Object.values(n.response).length?w():(c&&c(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const C=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=we(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),ee},ee={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:B=>(l=B,ee),withRetryInterval:(B,L)=>(R(B)&&(v=B),R(L)&&(m=L),ee),withTimeout:B=>(o=B,ee),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return ee}const JS=100,XS=2e3,ZS=500;let eb=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-ZS;if(t-e>XS){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>JS&&(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 tb{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Rs(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ms=1e4,Wr=3,ib=6e4,sb=10,rb=1,ab=500;class nb{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 eb(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||R(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=()=>{KS(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 tb(Wr,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,l=null,d=!1;const c=()=>{const w=a&&(!d||d===this.rep);return w||t("Not running!"),w},h=(w,k,q)=>{u&&u.abort(),u=Rs(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Wr).withFinally(()=>{u=null}).send()},f=(w,k,q)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},v=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const q=we()-1e4;let W=0;for(let G=0;G<this.bufferStates.length;G++){const X=this.bufferStates[G];w=Math.min(w,X.buf),X.ts<q&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${w} drop=${W} jitter=${this.sourceJitter}`);let J=w-rb;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?m(1.15):J>1?m(1.1):J>.3?m(1.05):m(1)}},S=w=>{let k;const q=()=>k&&k.start?k.start.length:0,W=C=>k.start[C]/1e3,J=C=>k.dur[C]/1e3,G=C=>k.fragIndex+C,X=(C,Z)=>({chunkIdx:G(C),startTS:W(C),dur:J(C),discontinuity:Z}),ee=()=>{let C=0;if(k&&k.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,de=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=Z;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let be=k.dur.length-1;for(;be>=0&&(ve-=k.dur[be],!(ve<=0));--be);C=Math.min(be,k.dur.length-1-de),C=Math.max(C,0)}return X(C,!0)},B=C=>{const Z=q();if(!(Z<=0)){if(R(C)){for(let de=0;de<Z;de++)if(W(de)>C)return X(de)}return ee()}},L=C=>{const Z=q(),de=C?C.chunkIdx+1:0,ve=de-k.fragIndex;if(!(Z<=0)){if(!C||ve<0||ve-Z>sb)return t(`Resync: offset=${ve} bChunks=${Z} chunk=`+JSON.stringify(C)),ee();if(!(ve>=Z))return X(de-k.fragIndex,!1)}},ae=(C,Z,de)=>{l&&l.abort(),l=Rs(this.urlResolver.resolve(C,!0,this.lowLatency),Z,de,()=>this._retryCallback()).withTimeout(ms).withRetryCount(Wr).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(C,Z)=>{ae(w,de=>{if(!c())return;k=de;const ve=!!k.lowLatency;ve!==this.lowLatency&&v(ve);let be=0;for(let Ke=0;Ke<k.dur.length;++Ke)be+=k.dur[Ke];be>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,C(B(Z))},()=>this._handleNetworkError())},nextChunk:L}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:w=>{const{videoElement:k,logger:q}=this.params;let W=S(e.jidxUrl),J,G,X,ee,B=0,L,ae,N;const C=()=>{L&&(clearTimeout(L),L=void 0);const Q=Math.max(ab,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=B+Q,Re=we(),De=Math.min(1e4,$e-Re);B=Re;const Qt=()=>{l||c()&&W.seek(()=>{c()&&(B=we(),Z(),C())})};De>0?L=window.setTimeout(()=>{this.paused?C():Qt()},De):Qt()},Z=()=>{let Q;for(;Q=W.nextChunk(ee);)ee=Q,Ti(Q);const $e=W.nextChunk(X);if($e){if(X&&$e.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?C():(E(),this._initPlayerWith(e));return}Ke($e)}else C()},de=(Q,$e)=>{if(!c()||!this.sourceBuffer)return;let Re,De,Qt;const Ei=ot=>{window.setTimeout(()=>{c()&&de(Q,$e)},ot)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),Ei(100);else{const ot=we(),Me=k.currentTime;!this.paused&&k.buffered.length>1&&ae===Me&&ot-N>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),ae!==Me&&(ae=Me,N=ot);const Kt=this._getBufferSizeSec();if(Kt>30)q(`Buffered ${Kt} seconds; delaying appendBuffer`),Ei(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Kt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch($i){if($i.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Qt=this.sourceBuffer.buffered.length,Qt!==0&&(Re=this.sourceBuffer.buffered.start(0),De=Me,De-Re>4&&this.sourceBuffer.remove(Re,De-3)),Ei(1e3);else throw $i}}},ve=()=>{G&&J&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(X)]),de(G,function(){G=null,Z()}))},be=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Ke=Q=>{c()&&f(be(Q),($e,Re)=>{if(c()){if(Re/=1e3,G=$e,X=Q,n=Q.startTS,Re){const De=Math.min(10,Q.dur/Re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}ve()}},()=>this._handleNetworkError())},Ti=Q=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(Q),!1)))},zt=Q=>{c()&&(e.cachedHeader=Q,de(Q,()=>{J=!0,ve()}))};a=!0,W.seek(Q=>{if(c()){if(B=we(),!Q){C();return}ee=Q,!K(w)||Q.startTS>w?Ke(Q):(X=Q,Z())}},w),e.cachedHeader?zt(e.cachedHeader):h(e.headerUrl,zt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},d}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),R(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 R(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=we();if(this.chunkRateEstimator.addInterval(h,m,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:g}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nd(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&l(),f},notifySwitch:c=>{const h=we();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Rs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Wt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ib))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Fd{constructor(){this.onDroopedVideoFramesLimit$=new D,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new D,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Bt(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&&hi(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(x(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ci(this.droppedFramesChecker.checkTime).pipe(fe(()=>this.playing),fe(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(rt(this.droppedFramesChecker.checkTime)),s=F(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>$s(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var j;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const ob=[j.PAUSED,j.PLAYING,j.READY],lb=[j.PAUSED,j.PLAYING,j.READY];class db{constructor(e){this.subscription=new re,this.videoState=new he(j.STOPPED),this.representations$=new y([]),this.textTracksManager=new At,this.droppedFramesManager=new Fd,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new hn,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const l=r.isBuffering;this.params.output.isBuffering$.next(l);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:I.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const l=r.manifest,d=[];for(const c of l){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Js(c.name))!==null&&n!==void 0?n:Mt(c.video),m=c.bitrate/1e3,v=Object.assign({},c.video);if(!f)continue;const g={id:h,quality:f,bitrate:m,size:v};d.push({track:g,representation:c})}this.representations$.next(d),this.params.output.availableVideoTracks$.next(d.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const l=r.quality,d=(u=this.representations$.getValue().find(({representation:c})=>c===l))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(l.headerUrl,this.params.source.url).hostname),R(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:l,duration:d}=r;this.params.dependencies.throughputEstimator.addRawSpeed(l,d);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(a)return;const l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(lb.includes(r)&&(l||d)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&ob.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(ze(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(n===p.PAUSED)this.videoState.setState(j.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(j.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(j.PAUSED)})}return;case j.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(j.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(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(ze(this.params.source.url,c))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:I.WTF,message:"DashLiveProvider internal logic error",thrown:r})};F(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=jt(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(at(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=qt(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($(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)===j.READY&&this.videoState.setState(j.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ve({zeroTime:this.zeroTime$.pipe(fe(R)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(zi(this.video,this.params.desiredState.isLooped,t)).add(Yt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(yi(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&&Au(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.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 j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(F(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,He(["init"])).pipe(rt(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),Gt(this.video)}createLiveDashPlayer(){const e=new nb({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),l=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&R(u)?u:Xs(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}),c=d==null?void 0:d.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(h||c!==f)&&this.setVideoTrack(d),m&&this.setAutoQuality(l),h||m||c!==f){const v=(n=o.find(({track:g})=>g.id===c))===null||n===void 0?void 0:n.representation;P(v,"Representations missing"),this.dash.startPlay(v,l)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ze(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Te;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Te||(Te={}));var et;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(et||(et={}));var Ms;(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"})(Ms||(Ms={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));var V;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(V||(V={}));var vi;(function(i){i.MP4="mp4",i.WEBM="webm"})(vi||(vi={}));var Bs;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Bs||(Bs={}));var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(oe||(oe={}));var Li=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Vd extends Qo{constructor(){super(),this.listeners||Qo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Ud=class{constructor(){Object.defineProperty(this,"signal",{value:new Vd,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&&(Ud.prototype[Symbol.toStringTag]="AbortController",Vd.prototype[Symbol.toStringTag]="AbortSignal");function Hd(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 ub(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Hd({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);const h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,l)=>{const d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}const Zs=Hd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jd=Zs?ub({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ni=Zs?jd.fetch:window.fetch;Zs?jd.Request:window.Request;const pi=Zs?Ud:window.AbortController;var La=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const cb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},hb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=hb?cb:window.requestIdleCallback;var zr,Qr;const fb=16;let Gd=!1;try{Gd=Na().browser===yl.Safari&&parseInt((Qr=(zr=navigator.userAgent.match(/Version\/(\d+)/))===null||zr===void 0?void 0:zr[1])!==null&&Qr!==void 0?Qr:"",10)<=fb}catch(i){console.error(i)}class pb{constructor(e){this.bufferFull$=new D,this.error$=new D,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:I.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return te(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 te(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 te(this,void 0,void 0,function*(){return new Promise(t=>{let s;Gd&&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:I.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:H(t)}}}var Jo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ye{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.size32=s<=e.buffer.byteLength?s: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[]}scanForBoxes(e){return this.boxParser.parse(e)}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 Yd extends Ye{}class vb extends Ye{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class mb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class gb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Sb extends Ye{constructor(e,t){super(e,t),this.data=this.content}}class vt extends Ye{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class qd extends vt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}class bb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class yb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Ot;(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"})(Ot||(Ot={}));class Tb extends vt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Ot.MONOSCOPIC;break;case 1:this.stereoMode=Ot.TOP_BOTTOM;break;case 2:this.stereoMode=Ot.LEFT_RIGHT;break;case 3:this.stereoMode=Ot.STEREO_CUSTOM;break;case 4:this.stereoMode=Ot.RIGHT_LEFT;break}this.cursor+=1}}class Eb extends vt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class $b extends vt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ab extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class wb extends vt{constructor(e,t){super(e,t),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 kb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Pb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Rb extends vt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class _b extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Cb extends vt{constructor(e,t){super(e,t),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 Ib extends vt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Db extends vt{constructor(e,t){super(e,t),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 s=0;s<this.sampleCount;s++)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())}}var ue;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UnknownBox="unknown"})(ue||(ue={}));const Lb={[ue.FtypBox]:vb,[ue.MoovBox]:mb,[ue.MoofBox]:gb,[ue.MdatBox]:Sb,[ue.SidxBox]:qd,[ue.TrakBox]:bb,[ue.MdiaBox]:Ab,[ue.MfhdBox]:Rb,[ue.TkhdBox]:wb,[ue.TrafBox]:_b,[ue.TfhdBox]:Cb,[ue.TfdtBox]:Ib,[ue.TrunBox]:Db,[ue.MinfBox]:kb,[ue.Sv3dBox]:yb,[ue.St3dBox]:Tb,[ue.PrhdBox]:Eb,[ue.ProjBox]:Pb,[ue.EquiBox]:$b,[ue.UnknownBox]:Yd};class Ft{constructor(e={}){this.options=Object.assign({offset:0},e)}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;){const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(t.push(n),!n.size)break;s+=n.size}return t}createBox(e,t){const s=Lb[e];return s?new s(t,new Ft):new Yd(t,new Ft)}}class pn{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const xb=new TextDecoder("ascii"),Ob=i=>xb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Mb=i=>{const e=new qd(i,new Ft);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:V.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Bb=i=>{const t=new Ft().parse(i),s=new pn(t),r=s.findAll("mdat"),a=s.findAll("moof");if(!(r.length&&a.length))return null;const n=a[0],o=r[r.length-1],u=n.source.byteOffset,d=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(i.buffer,u,d)},Nb=(i,e)=>{const s=new Ft().parse(i),a=new pn(s).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun");let l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Fb=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Bs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Ft().parse(i),r=new pn(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Vb={validateData:Ob,parseInit:Fb,getIndexRange:()=>{},parseSegments:Mb,parseFeedableSegmentChunk:Bb,getSegmentEndTime:Nb};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var _;(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"})(_||(_={}));const Xo={[T.EBML]:{type:_.Master},[T.EBMLVersion]:{type:_.UnsignedInteger},[T.EBMLReadVersion]:{type:_.UnsignedInteger},[T.EBMLMaxIDLength]:{type:_.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[T.DocType]:{type:_.String},[T.DocTypeVersion]:{type:_.UnsignedInteger},[T.DocTypeReadVersion]:{type:_.UnsignedInteger},[T.Void]:{type:_.Binary},[T.Segment]:{type:_.Master},[T.SeekHead]:{type:_.Master},[T.Seek]:{type:_.Master},[T.SeekID]:{type:_.Binary},[T.SeekPosition]:{type:_.UnsignedInteger},[T.Info]:{type:_.Master},[T.TimestampScale]:{type:_.UnsignedInteger},[T.Duration]:{type:_.Float},[T.Tracks]:{type:_.Master},[T.TrackEntry]:{type:_.Master},[T.Video]:{type:_.Master},[T.Projection]:{type:_.Master},[T.ProjectionType]:{type:_.UnsignedInteger},[T.ProjectionPrivate]:{type:_.Master},[T.Chapters]:{type:_.Master},[T.Cluster]:{type:_.Master},[T.Timestamp]:{type:_.UnsignedInteger},[T.SilentTracks]:{type:_.Master},[T.SilentTrackNumber]:{type:_.UnsignedInteger},[T.Position]:{type:_.UnsignedInteger},[T.PrevSize]:{type:_.UnsignedInteger},[T.SimpleBlock]:{type:_.Binary},[T.BlockGroup]:{type:_.Master},[T.EncryptedBlock]:{type:_.Binary},[T.Attachments]:{type:_.Master},[T.Tags]:{type:_.Master},[T.Cues]:{type:_.Master},[T.CuePoint]:{type:_.Master},[T.CueTime]:{type:_.UnsignedInteger},[T.CueTrackPositions]:{type:_.Master},[T.CueTrack]:{type:_.UnsignedInteger},[T.CueClusterPosition]:{type:_.UnsignedInteger},[T.CueRelativePosition]:{type:_.UnsignedInteger},[T.CueDuration]:{type:_.UnsignedInteger},[T.CueBlockNumber]:{type:_.UnsignedInteger},[T.CueCodecState]:{type:_.UnsignedInteger},[T.CueReference]:{type:_.Master},[T.CueRefTime]:{type:_.UnsignedInteger}},Wd=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=Ns(i,t),r=s in Xo,a=r?Xo[s].type:_.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,d=Ns(u),c=l*Math.pow(2,(o-1)*8)+d,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Ns=(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},it=(i,e)=>{switch(e){case _.SignedInteger:return i.getInt8(0);case _.UnsignedInteger:return Ns(i);case _.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(i);case _.UTF8:return new TextDecoder("utf-8").decode(i);case _.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case _.Master:return i;case _.Binary:return i;default:H(e)}},mi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Wd(s);if(!e(r))return;r.type===_.Master&&mi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Ub=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Wd(i);return mi(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=it(o,n):a===T.DocType?t=it(o,n):a===T.DocTypeReadVersion&&(s=it(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},zd=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Hb=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],jb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,l,d=!1;const c=0;return mi(i,({tag:h,type:f,value:m,valueSize:v})=>{if(h===T.SeekID){const g=it(m,f);l=Ns(g)}else h!==T.SeekPosition&&(l=void 0);return h===T.Segment?(e=m.byteOffset,t=m.byteOffset+v):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=it(m,f):h===T.Duration?r=it(m,f):h===T.SeekPosition&&l===T.Cues?u=it(m,f):h===T.Tracks?mi(m,({tag:g,type:S,value:E})=>g===T.ProjectionType?(d=it(E,S)===1,!1):!0):a&&n&&zd.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:d,stereoMode:c,projectionType:Bs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Yb=(i,e)=>{let t=!1,s=!1;const r=o=>R(o.time)&&R(o.position),a=[];let n;return mi(i,({tag:o,type:u,value:l})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=it(l,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=it(l,u));break;default:t&&zd.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:l,position:d}=o,c=a[u+1];return{status:V.NONE,time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},qb=i=>{let e=0,t=!1;try{mi(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Hb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Wb={validateData:Ub,parseInit:jb,getIndexRange:Gb,parseSegments:Yb,parseFeedableSegmentChunk:qb};var zb=ft,Qb=Vi,Kb=Pe,Jb=Kb("match"),Xb=function(i){var e;return zb(i)&&((e=i[Jb])!==void 0?!!e:Qb(i)=="RegExp")},Zb=Yi,ey=String,ty=function(i){if(Zb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return ey(i)},iy=pt,sy=function(){var i=iy(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},ry=Oe,ay=nt,ny=Hs,oy=sy,Zo=RegExp.prototype,ly=function(i){var e=i.flags;return e===void 0&&!("flags"in Zo)&&!ay(i,"flags")&&ny(Zo,i)?ry(oy,i):e},vn=Ge,dy=qs,uy=Math.floor,Kr=vn("".charAt),cy=vn("".replace),Jr=vn("".slice),hy=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fy=/\$([$&'`]|\d{1,2})/g,py=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=fy;return r!==void 0&&(r=dy(r),u=hy),cy(a,u,function(l,d){var c;switch(Kr(d,0)){case"$":return"$";case"&":return i;case"`":return Jr(e,0,t);case"'":return Jr(e,n);case"<":c=r[Jr(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var f=uy(h/10);return f===0?l:f<=o?s[f-1]===void 0?Kr(d,1):s[f-1]+Kr(d,1):l}c=s[h-1]}return c===void 0?"":c})},vy=Qe,my=Oe,mn=Ge,el=Va,gy=ge,Sy=Ui,by=Xb,ri=ty,yy=Ys,Ty=ly,Ey=py,$y=Pe,Ay=$y("replace"),wy=TypeError,Qd=mn("".indexOf),ky=mn("".replace),tl=mn("".slice),Py=Math.max,il=function(i,e,t){return t>i.length?-1:e===""?t:Qd(i,e,t)};vy({target:"String",proto:!0},{replaceAll:function(e,t){var s=el(this),r,a,n,o,u,l,d,c,h,f=0,m=0,v="";if(!Sy(e)){if(r=by(e),r&&(a=ri(el(Ty(e))),!~Qd(a,"g")))throw wy("`.replaceAll` does not allow non-global regexes");if(n=yy(e,Ay),n)return my(n,e,s,t);if(r)return ky(ri(s),e,t)}for(o=ri(s),u=ri(e),l=gy(t),l||(t=ri(t)),d=u.length,c=Py(1,d),f=il(o,u,0);f!==-1;)h=l?ri(t(u,f,o)):Ey(u,o,f,[],void 0,t),v+=tl(o,m,f)+h,m=f+d,f=il(o,u,f+c);return m<o.length&&(v+=tl(o,m)),v}});var Ry=dn,_y=Ry("String","replaceAll"),Cy=_y,Iy=Cy,Dy=Iy,Ly=Dy,sl=Vs(Ly);const xy=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},rl=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ni=(i,e)=>{let t=i;t=sl(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=sl(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Oy=(i,e)=>{var t,s,r,a,n,o,u,l,d,c,h,f,m,v,g,S,E,A,w,k,q,W,J,G,X,ee,B,L,ae,N,C,Z,de,ve,be,Ke,Ti,zt,Q,$e,Re,De;const Ei=new DOMParser().parseFromString(i,"application/xml"),ot={video:[],audio:[],text:[]},Me=Ei.children[0],Kt=Me.getElementsByTagName("Period")[0],$i=(r=(s=(t=Me.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",iu=Kt.children,su=Me.getAttribute("type")==="dynamic",bn=Me.getAttribute("availabilityStartTime"),ru=bn?new Date(bn).getTime():void 0;let wt;const yn=Me.getAttribute("mediaPresentationDuration"),Tn=Kt.getAttribute("duration"),er=Me.getElementsByTagName("vk:Attrs")[0],En=er==null?void 0:er.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(yn)wt=rl(yn);else if(Tn){const Be=rl(Tn);R(Be)&&(wt=Be)}else En&&(wt=parseInt(En,10));let au=0;const tr=(n=(a=Me.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],nu=tr.includes(Ms.WEBM_AS_IN_FFMPEG)||tr.includes(Ms.WEBM_AS_IN_SPEC)?vi.WEBM:vi.MP4;for(const Be of iu){const Qi=Be.getAttribute("mimeType"),ou=Be.getAttribute("codecs"),$n=(o=Be.getAttribute("contentType"))!==null&&o!==void 0?o:Qi==null?void 0:Qi.split("/")[0],lu=(l=(u=Be.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&l!==void 0?l:[],An=Be.querySelectorAll("Representation"),du=Be.querySelector("SegmentTemplate");if($n===Te.TEXT){for(const me of An){const mt=me.getAttribute("id")||"",Ki=Be.getAttribute("lang"),Jt=Be.getAttribute("label"),ir=(h=(c=(d=me.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",sr=new URL(ir||$i,e).toString(),Ji=mt.includes("_auto");ot[Te.TEXT].push({id:mt,lang:Ki,label:Jt,isAuto:Ji,kind:Te.TEXT,url:sr})}continue}for(const me of An){const mt=(f=me.getAttribute("mimeType"))!==null&&f!==void 0?f:Qi,Ki=(v=(m=me.getAttribute("codecs"))!==null&&m!==void 0?m:ou)!==null&&v!==void 0?v:"",Jt=(S=(g=me.getAttribute("contentType"))!==null&&g!==void 0?g:mt==null?void 0:mt.split("/")[0])!==null&&S!==void 0?S:$n,ir=(A=(E=Be.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],sr=parseInt((w=me.getAttribute("width"))!==null&&w!==void 0?w:"",10),Ji=parseInt((k=me.getAttribute("height"))!==null&&k!==void 0?k:"",10),wn=parseInt((q=me.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,kn=(W=me.getAttribute("frameRate"))!==null&&W!==void 0?W:"",uu=(J=me.getAttribute("quality"))!==null&&J!==void 0?J:void 0,cu=kn?xy(kn):void 0,hu=(G=me.getAttribute("id"))!==null&&G!==void 0?G:(au++).toString(10),fu=Jt==="video"?`${Ji}p`:Jt==="audio"?`${wn}Kbps`:Ki,pu=`${hu}@${fu}`,vu=(B=(ee=(X=me.querySelector("BaseURL"))===null||X===void 0?void 0:X.textContent)===null||ee===void 0?void 0:ee.trim())!==null&&B!==void 0?B:"",Pn=new URL(vu||$i,e).toString(),mu=[...tr,...lu,...ir];let rr;const gu=me.querySelector("SegmentBase"),kt=(L=me.querySelector("SegmentTemplate"))!==null&&L!==void 0?L:du;if(gu){const Pt=(N=(ae=me.querySelector("SegmentBase Initialization"))===null||ae===void 0?void 0:ae.getAttribute("range"))!==null&&N!==void 0?N:"",[Rt,nr]=Pt.split("-").map(Xt=>parseInt(Xt,10)),gt={from:Rt,to:nr},Ai=(C=me.querySelector("SegmentBase"))===null||C===void 0?void 0:C.getAttribute("indexRange"),[or,Xi]=Ai?Ai.split("-").map(Xt=>parseInt(Xt,10)):[],wi=Ai?{from:or,to:Xi}:void 0;rr={type:Ue.BYTE_RANGE,url:Pn,initRange:gt,indexRange:wi}}else if(kt){const Pt={representationId:(Z=me.getAttribute("id"))!==null&&Z!==void 0?Z:void 0,bandwidth:(de=me.getAttribute("bandwidth"))!==null&&de!==void 0?de:void 0},Rt=parseInt((ve=kt.getAttribute("timescale"))!==null&&ve!==void 0?ve:"",10),nr=(be=kt.getAttribute("initialization"))!==null&&be!==void 0?be:"",gt=kt.getAttribute("media"),Ai=(Ti=parseInt((Ke=kt.getAttribute("startNumber"))!==null&&Ke!==void 0?Ke:"",10))!==null&&Ti!==void 0?Ti:1,or=ni(nr,Pt);if(!gt)throw new ReferenceError("No media attribute in SegmentTemplate");const Xi=(zt=kt.querySelectorAll("SegmentTimeline S"))!==null&&zt!==void 0?zt:[],wi=[];let Xt=0,lr="",dr=0;if(Xi.length){let Zi=Ai,qe=0;for(const Zt of Xi){const Je=parseInt((Q=Zt.getAttribute("d"))!==null&&Q!==void 0?Q:"",10),_t=parseInt(($e=Zt.getAttribute("r"))!==null&&$e!==void 0?$e:"",10)||0,es=parseInt((Re=Zt.getAttribute("t"))!==null&&Re!==void 0?Re:"",10);qe=Number.isFinite(es)?es:qe;const ur=Je/Rt*1e3,cr=qe/Rt*1e3;for(let ts=0;ts<_t+1;ts++){const bu=ni(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zi.toString(10),segmentTime:(qe+ts*Je).toString(10)})),Rn=(cr!=null?cr:0)+ts*ur,yu=Rn+ur;Zi++,wi.push({time:{from:Rn,to:yu},url:bu})}qe+=(_t+1)*Je,Xt+=(_t+1)*ur}dr=qe/Rt*1e3,lr=ni(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zi.toString(10),segmentTime:qe.toString(10)}))}else if(R(wt)){const qe=parseInt((De=kt.getAttribute("duration"))!==null&&De!==void 0?De:"",10)/Rt*1e3,Zt=Math.ceil(wt/qe);let Je=0;for(let _t=1;_t<Zt;_t++){const es=ni(gt,Object.assign(Object.assign({},Pt),{segmentNumber:_t.toString(10),segmentTime:Je.toString(10)}));wi.push({time:{from:Je,to:Je+qe},url:es}),Je+=qe}dr=Je,lr=ni(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zt.toString(10),segmentTime:Je.toString(10)}))}const Su={time:{from:dr,to:1/0},url:lr};rr={type:Ue.TEMPLATE,baseUrl:Pn,segmentTemplateUrl:gt,initUrl:or,totalSegmentsDurationMs:Xt,segments:wi,nextSegmentBeyondManifest:Su,timescale:Rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Jt||!mt)continue;const ar={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Jt];ar&&ot[ar].push({id:pu,kind:ar,segmentReference:rr,profiles:mu,duration:wt,bitrate:wn,mime:mt,codecs:Ki,width:sr,height:Ji,fps:cu,quality:uu})}}return{dynamic:su,liveAvailabilityStartTime:ru,duration:wt,container:nu,representations:ot}},My=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Js(a):void 0)!==null&&n!==void 0?n:Mt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},By=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ny=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=lt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:lt(i,-1)},Fy=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),al=i=>"url"in i,ai=i=>i.type===Ue.TEMPLATE,xa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class nl{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:d}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new D,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new pi,this.destroyAbortController=new pi,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=Ce(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 pb(this.sourceBuffer),this.subscription.add(x(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:I.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(x(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),m=this.segments.get(h.id),v=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 M(void 0);this.searchGaps(m,h),yield yield M(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v)})}.bind(this)),this.switchTo=Ce(this.destroyAbortController.signal,function(c){return Ie(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);P(h,`No such representation ${c}`);let f=this.segments.get(c),m=this.initData.get(c);if(K(m)||K(f)?yield yield M(this.loadInit(h,"high",!1)):m instanceof Promise&&(yield yield M(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 M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const v=this.getCurrentPosition();R(v)&&(this.isLive||(f.forEach(g=>g.status=V.NONE),this.pruneBuffer(v,1/0,!0)),this.maintain(v))})}.bind(this)),this.seekLive=Ce(this.destroyAbortController.signal,function(c){var h;return Ie(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield M(void 0);for(const E of this.representations.keys()){const A=c.find(q=>q.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!ai(w.segmentReference))return yield M(void 0);const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const v=this.segments.get(f);P(v,"No segments for starting representation");const g=this.initData.get(f);if(P(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return yield M(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield M(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(v,m),yield yield M(this.sourceBufferTaskQueue.append(g,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(d!=null&&d.dynamic),this.container=s,s){case vi.MP4:this.containerParser=Vb;break;case vi.WEBM:this.containerParser=Wb;break;default:H(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 pi,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(l=>e>=l.time.from&&e<l.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=Li(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const l=Li(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{const d=lt(o,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===V.FED&&!o.length&&Li(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=lt(s,-1);u&&u.status===V.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;R(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||!ai(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:V.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],l=(a=(r=lt(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,d=o==null?void 0:o.findIndex(c=>Math.floor(l)>=Math.floor(c.time.from)&&Math.floor(l)<=Math.floor(c.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(d+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!ai(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=ni(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||o.push({status:V.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 v=h<=s&&f>=s,g=h>s||v||m===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===V.NONE||c===V.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!La(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==Ue.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===V.NONE||h.status===V.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){t.segmentReference.type===Ue.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return te(this,void 0,void 0,function*(){e.status=V.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ce(o,function(){return Ie(this,arguments,function*(){const d=As(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const c=new DataView(d);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=V.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),xa(d)||this.failedDownloads++}})}loadByteRangeSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=V.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 Ce(n,function(){return Ie(this,arguments,function*(){const u=As(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),xa(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ai(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:lt(e,0).byte.from,to:lt(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(u,l)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ai(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:l,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){return te(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(l);d!=null&&d.byteLength&&(u.status=V.PARTIALLY_FED,o.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,l=e.byteLength;for(const d of this.activeSegments){const{segment:c}=d,h=u===Ue.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:l;if(d.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const v=h?c.byte.from-s:0,g=h?c.byte.to-s:e.byteLength,S=v<r,E=g<=r;if(c.status===V.DOWNLOADING&&S&&E){c.status=V.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+v,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(d.loadedBytes=Math.min(f,r-v),d.loadedBytes>d.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+v+d.feedingBytes,d.loadedBytes-d.feedingBytes),w=d.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(c.status=V.PARTIALLY_FED,d.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)d.fedBytes+=w.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=V.FED,al(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===V.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=V.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===V.PARTIALLY_FED||e.status===V.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=V.NONE),e.status=V.PARTIALLY_EJECTED):e.status=V.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ko(()=>un(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return te(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Ce(this.destroyAbortController.signal,function(){return Ie(this,arguments,function*(){const o=As(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=>te(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&ai(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:I.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return te(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=l=>{var d;a=Math.min(a,l.time.from),n=Math.max(n,l.time.to);const c=al(l)?(d=l.size)!==null&&d!==void 0?d:0:l.byte.to-l.byte.from;r+=c};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===V.FED&&u(d)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const l of this.segments.values())for(const d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;d.status===V.FED&&u(d)}}if(o=isFinite(a)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){const d=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===V.NONE&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(c)){a=d,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const c of d)c.time.from>e+l&&c.status===V.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:I.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==V.FED&&a!==V.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);u||(l.length===1||this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status=V.PARTIALLY_EJECTED:r.status=V.NONE)}}}var Oa=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Vy=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ca.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},ci;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(ci||(ci={}));class Uy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new pi,this.subscription=new re,this.fetchManifest=Ce(this.abortAllController.signal,function(r){return Ie(this,arguments,function*(){let a=r;this.requestQuic&&(a=Oa(a));const n=yield yield M(Ni(a,{signal:this.abortAllController.signal}).catch(Pi));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Ce(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?ci.HEADER:ci.PARAM,range:n,onProgress:o,priority:u="auto",signal:l,measureThroughput:d=!0,isLowLatency:c=!1}={}){var h,f;return Ie(this,arguments,function*(){let m=r;const v=new Headers;if(n)switch(a){case ci.HEADER:{v.append("Range",`bytes=${n.from}-${n.to}`);break}case ci.PARAM:{const L=new URL(m,location.href);L.searchParams.append("bytes",`${n.from}-${n.to}`),m=L.toString();break}default:H(a)}this.requestQuic&&(m=Oa(m));let g=this.abortAllController.signal,S;if(l){const L=new pi;if(S=F(x(this.abortAllController.signal,"abort"),x(l,"abort")).subscribe(()=>{try{L.abort()}catch(ae){Pi(ae)}}),this.abortAllController.signal.aborted||l.aborted)try{L.abort()}catch(ae){Pi(ae)}g=L.signal}const E=le(),A=yield yield M(Ni(m,{priority:u,headers:v,signal:g}).catch(Pi)),w=le();if(!A)return S==null||S.unsubscribe(),yield M(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`)));if(this.onHeadersReceived(A.headers),!o&&!d)return S==null||S.unsubscribe(),yield M(A.arrayBuffer());const[k,q]=A.body.tee(),W=k.getReader();d&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,c));let J=0,G=new Uint8Array(0),X=!1;const ee=L=>{S==null||S.unsubscribe(),X=!0,Pi(L)},B=Ce(g,function({done:L,value:ae}){return Ie(this,arguments,function*(){if(J===0&&this.lastRequestFirstBytes$.next(le()-E),g.aborted)return S==null||S.unsubscribe(),yield M(void 0);if(!L&&ae){const N=new Uint8Array(G.length+ae.length);N.set(G),N.set(ae,G.length),G=N,J+=ae.byteLength,o==null||o(new DataView(G.buffer),J),yield yield M(W==null?void 0:W.read().then(B,ee))}})}.bind(this));return yield yield M(W==null?void 0:W.read().then(B,ee)),S==null||S.unsubscribe(),yield M(X?null:G.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Ce(this.abortAllController.signal,function(r,a,n){var o;return Ie(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(null);const{from:u,to:l}=r.initRange;let d=u,c=l,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=l+1===f,h&&(d=Math.min(f,u),c=Math.max(m,l))),d=Math.min(d,0);const v=yield yield M(this.fetch(r.url,{range:{from:d,to:c},priority:n,measureThroughput:!1}));if(!v)return yield M(null);const g=new DataView(v,u-d,l-d+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(v,E.from-d,E.to-E.from+1);else{const k=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!k)return yield M(null);A=new DataView(k)}const w=a.parseSegments(A,S,E);return yield M({init:S,dataView:new DataView(v),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=Ce(this.abortAllController.signal,function(r,a){return Ie(this,arguments,function*(){if(r.type!==Ue.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(l=>Object.assign(Object.assign({},l),{status:V.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}=Vy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return te(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:H(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Pi=i=>{if(!xa(i))throw i},oi=1e3,Fs=(i,e,t)=>t*e+(1-t)*i,Kd=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Hy=(i,e,t,s)=>{let r=0,a=t;const n=Kd(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 gn{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 y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${s}`),this.smoothedSeries$=new tt(`smoothed_${s}`),this.reportedSeries$=new tt(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(K(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class jy extends gn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Fs(this.slow,e,this.params.emaAlphaSlow),this.fast=Fs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Gy extends gn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Fs(this.emaSmoothed,e,this.params.emaAlpha);const s=Hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Yy extends gn{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?Fs(this.smoothed,e,this.params.emaAlpha):e}}class Ma{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new jy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Gy({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 Yy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const qy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},It=()=>window.ManagedMediaSource||window.MediaSource,Jd=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Wy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},zy=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,ol=["timeupdate","progress","play","seeked","stalled","waiting"];var Fe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Fe||(Fe={}));let Qy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new he(Fe.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.error$=new D,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new D,this.gapWatchdogStarted=!1,this.destroyController=new pi,this.initManifest=Ce(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){this.element=t,this.manifestUrlString=ze(s,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Fe.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Fe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:I.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Ce(this.destroyController.signal,function(){var t;return Ie(this,arguments,function*(){const s=yield yield M(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(null);let r;try{r=Oy(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:I.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield M(null);const a=({kind:n,mime:o,codecs:u})=>{var l,d,c,h;return!!(!((d=(l=this.element)===null||l===void 0?void 0:l.canPlayType)===null||d===void 0)&&d.call(l,o)&&(!((h=(c=It())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Te.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield M(Object.assign(Object.assign({},r),{representations:xs(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Ce(this.destroyController.signal,function(t,s,r){var a;return Ie(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Fe.REPRESENTATIOS_READY);const n=v=>{this.representationSubscription.add(x(v,"error").pipe(fe(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:I.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?zy():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Jd())if(r){const v=document.createElement("source");n(v),v.type="application/x-mpegurl",v.src=r.url,this.element.appendChild(v)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new nl(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],R(s)&&(this.audioBufferManager=new nl(Te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ci(oi).subscribe(v=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=Go(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=ze(this.manifestUrlString,S+oi,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(F(...ol.filter(v=>v!=="waiting").map(v=>x(this.element,v))).pipe($(v=>this.element?Li(this.element.buffered,this.element.currentTime*1e3):0),pe(),fe(v=>!!v),Oi(v=>{var g;(g=this.stallWatchdogSubscription)===null||g===void 0||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(fe(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=g-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),qy(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let A=0;if(g){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(q=>{var W,J;return(J=(W=q.getLiveSegmentsToLoadState(this.manifest))===null||W===void 0?void 0:W.to)!==null&&J!==void 0?J:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let v=0;this.representationSubscription.add(Ve({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wu(oi)).subscribe(({liveLoadBufferLength:g,bufferLength:S})=>te(this,void 0,void 0,function*(){if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=Go(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,J=this.isActiveLowLatency?S:g;let G=et.None;if(this.isActiveLowLatency?G=et.ActiveLowLatency:J<k+W&&J>=k?G=et.LiveWithTargetOffset:A!==0&&J<k&&(G=et.LiveForwardBuffering),isFinite(g)&&(v=g>v?g:v),G===et.LiveForwardBuffering||G===et.LiveWithTargetOffset){const X=v-(k+q),ee=this.normolizeLiveOffset(Math.trunc(A+X/E)),B=Math.abs(ee-A);let L;!g||B<=this.tuning.dashCmafLive.offsetCalculationError?L=A:ee>0&&B>this.tuning.dashCmafLive.offsetCalculationError?L=ee:L=0,this.manifestUrlString=ze(this.manifestUrlString,L,Se.DASH_CMAF_OFFSET_P)}G!==et.None&&G!==et.ActiveLowLatency&&(v=0,this.updateLive())})))}const l=F(...this.bufferManagers.map(v=>v.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(v=>v.fullyBuffered$.getValue()))),d=F(...this.bufferManagers.map(v=>v.onLastSegment$)).pipe($(()=>this.bufferManagers.some(v=>v.onLastSegment$.getValue())));this.representationSubscription.add(F(this.forceEnded$,Ve({allBuffersFull:l,someBufferEnded:d}).pipe(fe(({allBuffersFull:v,someBufferEnded:g})=>v&&g))).subscribe(()=>{var v;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(v=this.source)===null||v===void 0||v.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:I.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(F(...this.bufferManagers.map(v=>v.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(v=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",v)})));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(v,g)=>{var S;return Math.max(v,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),m=this.manifest.representations.video.reduce(h,c);(f||m)&&(this.source.duration=Math.max(f,m)/1e3),this.audioBufferManager&&R(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Fe.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=Ci(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:I.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Uy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ma.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return te(this,void 0,void 0,function*(){P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=ze(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,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(Fe.RUNNING),this.subscription.add(F(...ol.map(e=>x(this.element,e)),x(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(x(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(x(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&La(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=oi,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=Ci(oi).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:I.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return te(this,void 0,void 0,function*(){const s={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.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),La(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Fe.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}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return te(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Ky{constructor(e,t){this.fov=e,this.orientation=t}}class Jy{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 Xy=`#define GLSLIFY 1
|
|
37
|
+
`}),N}return d==null||d.recordSwitch(L),L};var at=i=>new URL(i).hostname,j;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const Wo=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 Wt=i=>te(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Wo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return Wo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return de()}function Nl(i){return we()-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 KS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function _s(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,v=2e3,g=()=>{if(u)return;P(l);const B=Nl(l);let L;if(B<v){L=v-B,setTimeout(g,L);return}v*=2,v>m&&(v=m),n&&n.abort(),n=new r,q()};const S=B=>(a=B,ee),E=B=>(c=B,ee),A=()=>(f="json",ee),w=()=>{if(!u){if(--d>=0){g(),s&&s();return}u=!0,c&&c(),t&&t()}},k=B=>(h=B,ee),q=()=>{l=we(),n=new r,n.open("get",i);let B=0,L,ae=0;const N=()=>(P(l),Math.max(l,Math.max(L||0,ae||0)));if(a&&n.addEventListener("progress",I=>{const Z=we();a.updateChunk&&I.loaded>B&&(a.updateChunk(N(),I.loaded-B),B=I.loaded,L=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const Z=n.response.byteLength-B;Z&&a.updateChunk&&a.updateChunk(N(),Z)}n.responseType==="json"&&!Object.values(n.response).length?w():(c&&c(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=we(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),ee},ee={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:B=>(d=B,ee),withRetryInterval:(B,L)=>(_(B)&&(v=B),_(L)&&(m=L),ee),withTimeout:B=>(o=B,ee),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return ee}const JS=100,XS=2e3,ZS=500;let eb=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-ZS;if(t-e>XS){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>JS&&(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 tb{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=_s(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ms=1e4,Wr=3,ib=6e4,sb=10,rb=1,ab=500;class nb{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 eb(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(){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():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||_(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=()=>{KS(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 tb(Wr,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 w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,k,q)=>{u&&u.abort(),u=_s(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Wr).withFinally(()=>{u=null}).send()},f=(w,k,q)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},v=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const q=we()-1e4;let W=0;for(let G=0;G<this.bufferStates.length;G++){const X=this.bufferStates[G];w=Math.min(w,X.buf),X.ts<q&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${w} drop=${W} jitter=${this.sourceJitter}`);let J=w-rb;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?m(1.15):J>1?m(1.1):J>.3?m(1.05):m(1)}},S=w=>{let k;const q=()=>k&&k.start?k.start.length:0,W=I=>k.start[I]/1e3,J=I=>k.dur[I]/1e3,G=I=>k.fragIndex+I,X=(I,Z)=>({chunkIdx:G(I),startTS:W(I),dur:J(I),discontinuity:Z}),ee=()=>{let I=0;if(k&&k.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=Z;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let be=k.dur.length-1;for(;be>=0&&(ve-=k.dur[be],!(ve<=0));--be);I=Math.min(be,k.dur.length-1-le),I=Math.max(I,0)}return X(I,!0)},B=I=>{const Z=q();if(!(Z<=0)){if(_(I)){for(let le=0;le<Z;le++)if(W(le)>I)return X(le)}return ee()}},L=I=>{const Z=q(),le=I?I.chunkIdx+1:0,ve=le-k.fragIndex;if(!(Z<=0)){if(!I||ve<0||ve-Z>sb)return t(`Resync: offset=${ve} bChunks=${Z} chunk=`+JSON.stringify(I)),ee();if(!(ve>=Z))return X(le-k.fragIndex,!1)}},ae=(I,Z,le)=>{d&&d.abort(),d=_s(this.urlResolver.resolve(I,!0,this.lowLatency),Z,le,()=>this._retryCallback()).withTimeout(ms).withRetryCount(Wr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,Z)=>{ae(w,le=>{if(!c())return;k=le;const ve=!!k.lowLatency;ve!==this.lowLatency&&v(ve);let be=0;for(let Je=0;Je<k.dur.length;++Je)be+=k.dur[Je];be>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,I(B(Z))},()=>this._handleNetworkError())},nextChunk:L}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:k,logger:q}=this.params;let W=S(e.jidxUrl),J,G,X,ee,B=0,L,ae,N;const I=()=>{L&&(clearTimeout(L),L=void 0);const Q=Math.max(ab,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=B+Q,_e=we(),De=Math.min(1e4,$e-_e);B=_e;const Qt=()=>{d||c()&&W.seek(()=>{c()&&(B=we(),Z(),I())})};De>0?L=window.setTimeout(()=>{this.paused?I():Qt()},De):Qt()},Z=()=>{let Q;for(;Q=W.nextChunk(ee);)ee=Q,Ei(Q);const $e=W.nextChunk(X);if($e){if(X&&$e.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?I():(E(),this._initPlayerWith(e));return}Je($e)}else I()},le=(Q,$e)=>{if(!c()||!this.sourceBuffer)return;let _e,De,Qt;const $i=ot=>{window.setTimeout(()=>{c()&&le(Q,$e)},ot)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),$i(100);else{const ot=we(),Me=k.currentTime;!this.paused&&k.buffered.length>1&&ae===Me&&ot-N>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),ae!==Me&&(ae=Me,N=ot);const Kt=this._getBufferSizeSec();if(Kt>30)q(`Buffered ${Kt} seconds; delaying appendBuffer`),$i(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Kt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(Ai){if(Ai.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Qt=this.sourceBuffer.buffered.length,Qt!==0&&(_e=this.sourceBuffer.buffered.start(0),De=Me,De-_e>4&&this.sourceBuffer.remove(_e,De-3)),$i(1e3);else throw Ai}}},ve=()=>{G&&J&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(X)]),le(G,function(){G=null,Z()}))},be=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Je=Q=>{c()&&f(be(Q),($e,_e)=>{if(c()){if(_e/=1e3,G=$e,X=Q,n=Q.startTS,_e){const De=Math.min(10,Q.dur/_e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}ve()}},()=>this._handleNetworkError())},Ei=Q=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(Q),!1)))},zt=Q=>{c()&&(e.cachedHeader=Q,le(Q,()=>{J=!0,ve()}))};a=!0,W.seek(Q=>{if(c()){if(B=we(),!Q){I();return}ee=Q,!K(w)||Q.startTS>w?Je(Q):(X=Q,Z())}},w),e.cachedHeader?zt(e.cachedHeader):h(e.headerUrl,zt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(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 _(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=we();if(this.chunkRateEstimator.addInterval(h,m,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:g}),!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&&Nl(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=we();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=_s(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){const{videoElement:e}=this.params;Wt(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(j.PAUSED))})}_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):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ib))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Fl{constructor(){this.onDroopedVideoFramesLimit$=new D,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new D,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Bt(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&&fi(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(x(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ii(this.droppedFramesChecker.checkTime).pipe(fe(()=>this.playing),fe(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(rt(this.droppedFramesChecker.checkTime)),s=F(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>$s(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 ob=[j.PAUSED,j.PLAYING,j.READY],db=[j.PAUSED,j.PLAYING,j.READY];class lb{constructor(e){this.subscription=new re,this.videoState=new he(j.STOPPED),this.representations$=new y([]),this.textTracksManager=new At,this.droppedFramesManager=new Fl,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new hn,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:C.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=Js(c.name))!==null&&n!==void 0?n:Mt(c.video),m=c.bitrate/1e3,v=Object.assign({},c.video);if(!f)continue;const g={id:h,quality:f,bitrate:m,size:v};l.push({track:g,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)===j.MANIFEST_READY&&this.videoState.setState(j.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),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(db.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&ob.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(Qe(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(n===p.PAUSED)this.videoState.setState(j.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play()}return;case j.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Qe(this.params.source.url,c))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};F(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=jt(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(at(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=qt(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($(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)===j.READY&&this.videoState.setState(j.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ve({zeroTime:this.zeroTime$.pipe(fe(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(zi(this.video,this.params.desiredState.isLooped,t)).add(Yt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Ti(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&&Au(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.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 j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(F(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,He(["init"])).pipe(rt(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),Gt(this.video)}createLiveDashPlayer(){const e=new nb({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),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&&_(u)?u:Xs(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}),c=l==null?void 0:l.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),m&&this.setAutoQuality(d),h||m||c!==f){const v=(n=o.find(({track:g})=>g.id===c))===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.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Qe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Te;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Te||(Te={}));var et;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(et||(et={}));var Ms;(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"})(Ms||(Ms={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));var V;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(V||(V={}));var mi;(function(i){i.MP4="mp4",i.WEBM="webm"})(mi||(mi={}));var Bs;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Bs||(Bs={}));var oe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(oe||(oe={}));var Li=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class Qo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Vl extends Qo{constructor(){super(),this.listeners||Qo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Ul=class{constructor(){Object.defineProperty(this,"signal",{value:new Vl,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&&(Ul.prototype[Symbol.toStringTag]="AbortController",Vl.prototype[Symbol.toStringTag]="AbortSignal");function Hl(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 ub(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Hl({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 Zs=Hl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jl=Zs?ub({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ni=Zs?jl.fetch:window.fetch;Zs?jl.Request:window.Request;const vi=Zs?Ul:window.AbortController;var La=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const cb=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},hb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ko=hb?cb:window.requestIdleCallback;var zr,Qr;const fb=16;let Gl=!1;try{Gl=Na().browser===yd.Safari&&parseInt((Qr=(zr=navigator.userAgent.match(/Version\/(\d+)/))===null||zr===void 0?void 0:zr[1])!==null&&Qr!==void 0?Qr:"",10)<=fb}catch(i){console.error(i)}class pb{constructor(e){this.bufferFull$=new D,this.error$=new D,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return te(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 te(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 te(this,void 0,void 0,function*(){return new Promise(t=>{let s;Gl&&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:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:H(t)}}}var Jo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ye{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.size32=s<=e.buffer.byteLength?s: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[]}scanForBoxes(e){return this.boxParser.parse(e)}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 Yl extends Ye{}class vb extends Ye{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class mb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class gb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Sb extends Ye{constructor(e,t){super(e,t),this.data=this.content}}class vt extends Ye{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class ql extends vt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class bb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class yb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Ot;(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"})(Ot||(Ot={}));class Tb extends vt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Ot.MONOSCOPIC;break;case 1:this.stereoMode=Ot.TOP_BOTTOM;break;case 2:this.stereoMode=Ot.LEFT_RIGHT;break;case 3:this.stereoMode=Ot.STEREO_CUSTOM;break;case 4:this.stereoMode=Ot.RIGHT_LEFT;break}this.cursor+=1}}class Eb extends vt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class $b extends vt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ab extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class wb extends vt{constructor(e,t){super(e,t),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 kb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Pb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class _b extends vt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class Rb extends Ye{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ib extends vt{constructor(e,t){super(e,t),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 Cb extends vt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Db extends vt{constructor(e,t){super(e,t),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 s=0;s<this.sampleCount;s++)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())}}var ue;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UnknownBox="unknown"})(ue||(ue={}));const Lb={[ue.FtypBox]:vb,[ue.MoovBox]:mb,[ue.MoofBox]:gb,[ue.MdatBox]:Sb,[ue.SidxBox]:ql,[ue.TrakBox]:bb,[ue.MdiaBox]:Ab,[ue.MfhdBox]:_b,[ue.TkhdBox]:wb,[ue.TrafBox]:Rb,[ue.TfhdBox]:Ib,[ue.TfdtBox]:Cb,[ue.TrunBox]:Db,[ue.MinfBox]:kb,[ue.Sv3dBox]:yb,[ue.St3dBox]:Tb,[ue.PrhdBox]:Eb,[ue.ProjBox]:Pb,[ue.EquiBox]:$b,[ue.UnknownBox]:Yl};class Ft{constructor(e={}){this.options=Object.assign({offset:0},e)}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;){const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(t.push(n),!n.size)break;s+=n.size}return t}createBox(e,t){const s=Lb[e];return s?new s(t,new Ft):new Yl(t,new Ft)}}class pn{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const xb=new TextDecoder("ascii"),Ob=i=>xb.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Mb=i=>{const e=new ql(i,new Ft);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:V.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Bb=i=>{const t=new Ft().parse(i),s=new pn(t),r=s.findAll("mdat"),a=s.findAll("moof");if(!(r.length&&a.length))return null;const n=a[0],o=r[r.length-1],u=n.source.byteOffset,l=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(i.buffer,u,l)},Nb=(i,e)=>{const s=new Ft().parse(i),a=new pn(s).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun");let d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,h)=>c+h,0):d=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Fb=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Bs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Ft().parse(i),r=new pn(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Vb={validateData:Ob,parseInit:Fb,getIndexRange:()=>{},parseSegments:Mb,parseFeedableSegmentChunk:Bb,getSegmentEndTime:Nb};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var R;(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"})(R||(R={}));const Xo={[T.EBML]:{type:R.Master},[T.EBMLVersion]:{type:R.UnsignedInteger},[T.EBMLReadVersion]:{type:R.UnsignedInteger},[T.EBMLMaxIDLength]:{type:R.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[T.DocType]:{type:R.String},[T.DocTypeVersion]:{type:R.UnsignedInteger},[T.DocTypeReadVersion]:{type:R.UnsignedInteger},[T.Void]:{type:R.Binary},[T.Segment]:{type:R.Master},[T.SeekHead]:{type:R.Master},[T.Seek]:{type:R.Master},[T.SeekID]:{type:R.Binary},[T.SeekPosition]:{type:R.UnsignedInteger},[T.Info]:{type:R.Master},[T.TimestampScale]:{type:R.UnsignedInteger},[T.Duration]:{type:R.Float},[T.Tracks]:{type:R.Master},[T.TrackEntry]:{type:R.Master},[T.Video]:{type:R.Master},[T.Projection]:{type:R.Master},[T.ProjectionType]:{type:R.UnsignedInteger},[T.ProjectionPrivate]:{type:R.Master},[T.Chapters]:{type:R.Master},[T.Cluster]:{type:R.Master},[T.Timestamp]:{type:R.UnsignedInteger},[T.SilentTracks]:{type:R.Master},[T.SilentTrackNumber]:{type:R.UnsignedInteger},[T.Position]:{type:R.UnsignedInteger},[T.PrevSize]:{type:R.UnsignedInteger},[T.SimpleBlock]:{type:R.Binary},[T.BlockGroup]:{type:R.Master},[T.EncryptedBlock]:{type:R.Binary},[T.Attachments]:{type:R.Master},[T.Tags]:{type:R.Master},[T.Cues]:{type:R.Master},[T.CuePoint]:{type:R.Master},[T.CueTime]:{type:R.UnsignedInteger},[T.CueTrackPositions]:{type:R.Master},[T.CueTrack]:{type:R.UnsignedInteger},[T.CueClusterPosition]:{type:R.UnsignedInteger},[T.CueRelativePosition]:{type:R.UnsignedInteger},[T.CueDuration]:{type:R.UnsignedInteger},[T.CueBlockNumber]:{type:R.UnsignedInteger},[T.CueCodecState]:{type:R.UnsignedInteger},[T.CueReference]:{type:R.Master},[T.CueRefTime]:{type:R.UnsignedInteger}},Wl=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=Ns(i,t),r=s in Xo,a=r?Xo[s].type:R.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=Ns(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}},Ns=(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},it=(i,e)=>{switch(e){case R.SignedInteger:return i.getInt8(0);case R.UnsignedInteger:return Ns(i);case R.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(i);case R.UTF8:return new TextDecoder("utf-8").decode(i);case R.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case R.Master:return i;case R.Binary:return i;default:H(e)}},gi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Wl(s);if(!e(r))return;r.type===R.Master&&gi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Ub=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Wl(i);return gi(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=it(o,n):a===T.DocType?t=it(o,n):a===T.DocTypeReadVersion&&(s=it(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},zl=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Hb=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],jb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return gi(i,({tag:h,type:f,value:m,valueSize:v})=>{if(h===T.SeekID){const g=it(m,f);d=Ns(g)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=m.byteOffset,t=m.byteOffset+v):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=it(m,f):h===T.Duration?r=it(m,f):h===T.SeekPosition&&d===T.Cues?u=it(m,f):h===T.Tracks?gi(m,({tag:g,type:S,value:E})=>g===T.ProjectionType?(l=it(E,S)===1,!1):!0):a&&n&&zl.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:Bs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Yb=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return gi(i,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=it(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=it(d,u));break;default:t&&zl.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:V.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{gi(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Hb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Wb={validateData:Ub,parseInit:jb,getIndexRange:Gb,parseSegments:Yb,parseFeedableSegmentChunk:qb};var zb=ft,Qb=Vi,Kb=Pe,Jb=Kb("match"),Xb=function(i){var e;return zb(i)&&((e=i[Jb])!==void 0?!!e:Qb(i)=="RegExp")},Zb=Yi,ey=String,ty=function(i){if(Zb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return ey(i)},iy=pt,sy=function(){var i=iy(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},ry=Oe,ay=nt,ny=Hs,oy=sy,Zo=RegExp.prototype,dy=function(i){var e=i.flags;return e===void 0&&!("flags"in Zo)&&!ay(i,"flags")&&ny(Zo,i)?ry(oy,i):e},vn=Ge,ly=qs,uy=Math.floor,Kr=vn("".charAt),cy=vn("".replace),Jr=vn("".slice),hy=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fy=/\$([$&'`]|\d{1,2})/g,py=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=fy;return r!==void 0&&(r=ly(r),u=hy),cy(a,u,function(d,l){var c;switch(Kr(l,0)){case"$":return"$";case"&":return i;case"`":return Jr(e,0,t);case"'":return Jr(e,n);case"<":c=r[Jr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=uy(h/10);return f===0?d:f<=o?s[f-1]===void 0?Kr(l,1):s[f-1]+Kr(l,1):d}c=s[h-1]}return c===void 0?"":c})},vy=Ke,my=Oe,mn=Ge,ed=Va,gy=ge,Sy=Ui,by=Xb,ri=ty,yy=Ys,Ty=dy,Ey=py,$y=Pe,Ay=$y("replace"),wy=TypeError,Ql=mn("".indexOf),ky=mn("".replace),td=mn("".slice),Py=Math.max,id=function(i,e,t){return t>i.length?-1:e===""?t:Ql(i,e,t)};vy({target:"String",proto:!0},{replaceAll:function(e,t){var s=ed(this),r,a,n,o,u,d,l,c,h,f=0,m=0,v="";if(!Sy(e)){if(r=by(e),r&&(a=ri(ed(Ty(e))),!~Ql(a,"g")))throw wy("`.replaceAll` does not allow non-global regexes");if(n=yy(e,Ay),n)return my(n,e,s,t);if(r)return ky(ri(s),e,t)}for(o=ri(s),u=ri(e),d=gy(t),d||(t=ri(t)),l=u.length,c=Py(1,l),f=id(o,u,0);f!==-1;)h=d?ri(t(u,f,o)):Ey(u,o,f,[],void 0,t),v+=td(o,m,f)+h,m=f+l,f=id(o,u,f+c);return m<o.length&&(v+=td(o,m)),v}});var _y=ln,Ry=_y("String","replaceAll"),Iy=Ry,Cy=Iy,Dy=Cy,Ly=Dy,sd=Vs(Ly);const xy=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},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},oi=(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)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Oy=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,m,v,g,S,E,A,w,k,q,W,J,G,X,ee,B,L,ae,N,I,Z,le,ve,be,Je,Ei,zt,Q,$e,_e,De;const $i=new DOMParser().parseFromString(i,"application/xml"),ot={video:[],audio:[],text:[]},Me=$i.children[0],Kt=Me.getElementsByTagName("Period")[0],Ai=(r=(s=(t=Me.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",iu=Kt.children,su=Me.getAttribute("type")==="dynamic",bn=Me.getAttribute("availabilityStartTime"),ru=bn?new Date(bn).getTime():void 0;let wt;const yn=Me.getAttribute("mediaPresentationDuration"),Tn=Kt.getAttribute("duration"),er=Me.getElementsByTagName("vk:Attrs")[0],En=er==null?void 0:er.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(yn)wt=rd(yn);else if(Tn){const Be=rd(Tn);_(Be)&&(wt=Be)}else En&&(wt=parseInt(En,10));let au=0;const tr=(n=(a=Me.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],nu=tr.includes(Ms.WEBM_AS_IN_FFMPEG)||tr.includes(Ms.WEBM_AS_IN_SPEC)?mi.WEBM:mi.MP4;for(const Be of iu){const Qi=Be.getAttribute("mimeType"),ou=Be.getAttribute("codecs"),$n=(o=Be.getAttribute("contentType"))!==null&&o!==void 0?o:Qi==null?void 0:Qi.split("/")[0],du=(d=(u=Be.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&d!==void 0?d:[],An=Be.querySelectorAll("Representation"),lu=Be.querySelector("SegmentTemplate");if($n===Te.TEXT){for(const me of An){const mt=me.getAttribute("id")||"",Ki=Be.getAttribute("lang"),Jt=Be.getAttribute("label"),ir=(h=(c=(l=me.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",sr=new URL(ir||Ai,e).toString(),Ji=mt.includes("_auto");ot[Te.TEXT].push({id:mt,lang:Ki,label:Jt,isAuto:Ji,kind:Te.TEXT,url:sr})}continue}for(const me of An){const mt=(f=me.getAttribute("mimeType"))!==null&&f!==void 0?f:Qi,Ki=(v=(m=me.getAttribute("codecs"))!==null&&m!==void 0?m:ou)!==null&&v!==void 0?v:"",Jt=(S=(g=me.getAttribute("contentType"))!==null&&g!==void 0?g:mt==null?void 0:mt.split("/")[0])!==null&&S!==void 0?S:$n,ir=(A=(E=Be.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],sr=parseInt((w=me.getAttribute("width"))!==null&&w!==void 0?w:"",10),Ji=parseInt((k=me.getAttribute("height"))!==null&&k!==void 0?k:"",10),wn=parseInt((q=me.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,kn=(W=me.getAttribute("frameRate"))!==null&&W!==void 0?W:"",uu=(J=me.getAttribute("quality"))!==null&&J!==void 0?J:void 0,cu=kn?xy(kn):void 0,hu=(G=me.getAttribute("id"))!==null&&G!==void 0?G:(au++).toString(10),fu=Jt==="video"?`${Ji}p`:Jt==="audio"?`${wn}Kbps`:Ki,pu=`${hu}@${fu}`,vu=(B=(ee=(X=me.querySelector("BaseURL"))===null||X===void 0?void 0:X.textContent)===null||ee===void 0?void 0:ee.trim())!==null&&B!==void 0?B:"",Pn=new URL(vu||Ai,e).toString(),mu=[...tr,...du,...ir];let rr;const gu=me.querySelector("SegmentBase"),kt=(L=me.querySelector("SegmentTemplate"))!==null&&L!==void 0?L:lu;if(gu){const Pt=(N=(ae=me.querySelector("SegmentBase Initialization"))===null||ae===void 0?void 0:ae.getAttribute("range"))!==null&&N!==void 0?N:"",[_t,nr]=Pt.split("-").map(Xt=>parseInt(Xt,10)),gt={from:_t,to:nr},wi=(I=me.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[or,Xi]=wi?wi.split("-").map(Xt=>parseInt(Xt,10)):[],ki=wi?{from:or,to:Xi}:void 0;rr={type:Ue.BYTE_RANGE,url:Pn,initRange:gt,indexRange:ki}}else if(kt){const Pt={representationId:(Z=me.getAttribute("id"))!==null&&Z!==void 0?Z:void 0,bandwidth:(le=me.getAttribute("bandwidth"))!==null&&le!==void 0?le:void 0},_t=parseInt((ve=kt.getAttribute("timescale"))!==null&&ve!==void 0?ve:"",10),nr=(be=kt.getAttribute("initialization"))!==null&&be!==void 0?be:"",gt=kt.getAttribute("media"),wi=(Ei=parseInt((Je=kt.getAttribute("startNumber"))!==null&&Je!==void 0?Je:"",10))!==null&&Ei!==void 0?Ei:1,or=oi(nr,Pt);if(!gt)throw new ReferenceError("No media attribute in SegmentTemplate");const Xi=(zt=kt.querySelectorAll("SegmentTimeline S"))!==null&&zt!==void 0?zt:[],ki=[];let Xt=0,dr="",lr=0;if(Xi.length){let Zi=wi,qe=0;for(const Zt of Xi){const Xe=parseInt((Q=Zt.getAttribute("d"))!==null&&Q!==void 0?Q:"",10),Rt=parseInt(($e=Zt.getAttribute("r"))!==null&&$e!==void 0?$e:"",10)||0,es=parseInt((_e=Zt.getAttribute("t"))!==null&&_e!==void 0?_e:"",10);qe=Number.isFinite(es)?es:qe;const ur=Xe/_t*1e3,cr=qe/_t*1e3;for(let ts=0;ts<Rt+1;ts++){const bu=oi(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zi.toString(10),segmentTime:(qe+ts*Xe).toString(10)})),_n=(cr!=null?cr:0)+ts*ur,yu=_n+ur;Zi++,ki.push({time:{from:_n,to:yu},url:bu})}qe+=(Rt+1)*Xe,Xt+=(Rt+1)*ur}lr=qe/_t*1e3,dr=oi(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zi.toString(10),segmentTime:qe.toString(10)}))}else if(_(wt)){const qe=parseInt((De=kt.getAttribute("duration"))!==null&&De!==void 0?De:"",10)/_t*1e3,Zt=Math.ceil(wt/qe);let Xe=0;for(let Rt=1;Rt<Zt;Rt++){const es=oi(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Rt.toString(10),segmentTime:Xe.toString(10)}));ki.push({time:{from:Xe,to:Xe+qe},url:es}),Xe+=qe}lr=Xe,dr=oi(gt,Object.assign(Object.assign({},Pt),{segmentNumber:Zt.toString(10),segmentTime:Xe.toString(10)}))}const Su={time:{from:lr,to:1/0},url:dr};rr={type:Ue.TEMPLATE,baseUrl:Pn,segmentTemplateUrl:gt,initUrl:or,totalSegmentsDurationMs:Xt,segments:ki,nextSegmentBeyondManifest:Su,timescale:_t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Jt||!mt)continue;const ar={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Jt];ar&&ot[ar].push({id:pu,kind:ar,segmentReference:rr,profiles:mu,duration:wt,bitrate:wn,mime:mt,codecs:Ki,width:sr,height:Ji,fps:cu,quality:uu})}}return{dynamic:su,liveAvailabilityStartTime:ru,duration:wt,container:nu,representations:ot}},My=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Js(a):void 0)!==null&&n!==void 0?n:Mt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},By=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ny=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=dt(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:dt(i,-1)},Fy=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),ad=i=>"url"in i,ai=i=>i.type===Ue.TEMPLATE,xa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class nd{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.currentSegmentLength$=new y(0),this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new D,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new vi,this.destroyAbortController=new vi,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=Ie(this.destroyAbortController.signal,function(c){return Ce(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 pb(this.sourceBuffer),this.subscription.add(x(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(x(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield M(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),m=this.segments.get(h.id),v=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 M(void 0);this.searchGaps(m,h),yield yield M(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v)})}.bind(this)),this.switchTo=Ie(this.destroyAbortController.signal,function(c){return Ce(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield M(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(K(m)||K(f)?yield yield M(this.loadInit(h,"high",!1)):m instanceof Promise&&(yield yield M(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 M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const v=this.getCurrentPosition();_(v)&&(this.isLive||(f.forEach(g=>g.status=V.NONE),this.pruneBuffer(v,1/0,!0)),this.maintain(v))})}.bind(this)),this.seekLive=Ie(this.destroyAbortController.signal,function(c){var h;return Ce(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield M(void 0);for(const E of this.representations.keys()){const A=c.find(q=>q.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!ai(w.segmentReference))return yield M(void 0);const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const v=this.segments.get(f);P(v,"No segments for starting representation");const g=this.initData.get(f);if(P(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return yield M(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield M(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(v,m),yield yield M(this.sourceBufferTaskQueue.append(g,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 mi.MP4:this.containerParser=Vb;break;case mi.WEBM:this.containerParser=Wb;break;default:H(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 vi,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var t,s;if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer)||this.isSeekingLive)return;const r=this.representations.get(this.downloadingRepresentationId),a=this.segments.get(this.downloadingRepresentationId);if(P(r,`No such representation ${this.downloadingRepresentationId}`),!a)return;const n=a.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((t=n==null?void 0:n.time.to)!==null&&t!==void 0?t:0)-((s=n==null?void 0:n.time.from)!==null&&s!==void 0?s:0));let o=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Li(this.sourceBuffer.buffered,e),f=n?n.time.to+100:-1/0;n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+100&&(o=f)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Li(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(a,r.segmentReference.type,o),d.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if(d.includes(n))c="high";else{const h=dt(d,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(d,r,c)}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status===V.FED&&!d.length&&Li(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const l=dt(a,-1);l&&l.status===V.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(n===l))}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;_(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||!ai(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:V.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=dt(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(!ai(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=oi(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:V.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 v=h<=s&&f>=s,g=h>s||v||m===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===V.NONE||c===V.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!La(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==Ue.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===V.NONE||h.status===V.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){t.segmentReference.type===Ue.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return te(this,void 0,void 0,function*(){e.status=V.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ie(o,function(){return Ce(this,arguments,function*(){const l=As(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(c=>setTimeout(c,l)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=V.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),xa(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,s="auto"){return te(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=V.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 Ie(n,function(){return Ce(this,arguments,function*(){const u=As(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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){this.abortActiveSegments(e),xa(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ai(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:dt(e,0).byte.from,to:dt(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:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ai(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){return te(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=V.PARTIALLY_FED,o.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===Ue.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 v=h?c.byte.from-s:0,g=h?c.byte.to-s:e.byteLength,S=v<r,E=g<=r;if(c.status===V.DOWNLOADING&&S&&E){c.status=V.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+v,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(l.loadedBytes=Math.min(f,r-v),l.loadedBytes>l.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+v+l.feedingBytes,l.loadedBytes-l.feedingBytes),w=l.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(c.status=V.PARTIALLY_FED,l.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)l.fedBytes+=w.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=V.FED,ad(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===V.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=V.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===V.PARTIALLY_FED||e.status===V.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=V.NONE),e.status=V.PARTIALLY_EJECTED):e.status=V.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ko(()=>un(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return te(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Ie(this.destroyAbortController.signal,function(){return Ce(this,arguments,function*(){const o=As(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=>te(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&&ai(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:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return te(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=ad(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===V.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===V.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===V.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===V.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ko(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==V.FED&&a!==V.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||this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status=V.PARTIALLY_EJECTED:r.status=V.NONE)}}}var Oa=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Vy=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ca.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},hi;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(hi||(hi={}));class Uy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new vi,this.subscription=new re,this.fetchManifest=Ie(this.abortAllController.signal,function(r){return Ce(this,arguments,function*(){let a=r;this.requestQuic&&(a=Oa(a));const n=yield yield M(Ni(a,{signal:this.abortAllController.signal}).catch(_i));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=Ie(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?hi.HEADER:hi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return Ce(this,arguments,function*(){let m=r;const v=new Headers;if(n)switch(a){case hi.HEADER:{v.append("Range",`bytes=${n.from}-${n.to}`);break}case hi.PARAM:{const L=new URL(m,location.href);L.searchParams.append("bytes",`${n.from}-${n.to}`),m=L.toString();break}default:H(a)}this.requestQuic&&(m=Oa(m));let g=this.abortAllController.signal,S;if(d){const L=new vi;if(S=F(x(this.abortAllController.signal,"abort"),x(d,"abort")).subscribe(()=>{try{L.abort()}catch(ae){_i(ae)}}),this.abortAllController.signal.aborted||d.aborted)try{L.abort()}catch(ae){_i(ae)}g=L.signal}const E=de(),A=yield yield M(Ni(m,{priority:u,headers:v,signal:g}).catch(_i)),w=de();if(!A)return S==null||S.unsubscribe(),yield M(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),yield M(Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`)));if(this.onHeadersReceived(A.headers),!o&&!l)return S==null||S.unsubscribe(),yield M(A.arrayBuffer());const[k,q]=A.body.tee(),W=k.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,c));let J=0,G=new Uint8Array(0),X=!1;const ee=L=>{S==null||S.unsubscribe(),X=!0,_i(L)},B=Ie(g,function({done:L,value:ae}){return Ce(this,arguments,function*(){if(J===0&&this.lastRequestFirstBytes$.next(de()-E),g.aborted)return S==null||S.unsubscribe(),yield M(void 0);if(!L&&ae){const N=new Uint8Array(G.length+ae.length);N.set(G),N.set(ae,G.length),G=N,J+=ae.byteLength,o==null||o(new DataView(G.buffer),J),yield yield M(W==null?void 0:W.read().then(B,ee))}})}.bind(this));return yield yield M(W==null?void 0:W.read().then(B,ee)),S==null||S.unsubscribe(),yield M(X?null:G.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=Ie(this.abortAllController.signal,function(r,a,n){var o;return Ce(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(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 v=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!v)return yield M(null);const g=new DataView(v,u-l,d-l+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(v,E.from-l,E.to-E.from+1);else{const k=yield yield M(this.fetch(r.url,{range:E,priority:n,measureThroughput:!1}));if(!k)return yield M(null);A=new DataView(k)}const w=a.parseSegments(A,S,E);return yield M({init:S,dataView:new DataView(v),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=Ie(this.abortAllController.signal,function(r,a){return Ce(this,arguments,function*(){if(r.type!==Ue.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:V.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}=Vy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return te(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:H(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _i=i=>{if(!xa(i))throw i},di=1e3,Fs=(i,e,t)=>t*e+(1-t)*i,Kl=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Hy=(i,e,t,s)=>{let r=0,a=t;const n=Kl(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 gn{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 y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${s}`),this.smoothedSeries$=new tt(`smoothed_${s}`),this.reportedSeries$=new tt(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(K(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class jy extends gn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Fs(this.slow,e,this.params.emaAlphaSlow),this.fast=Fs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Gy extends gn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Kl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Fs(this.emaSmoothed,e,this.params.emaAlpha);const s=Hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Yy extends gn{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?Fs(this.smoothed,e,this.params.emaAlpha):e}}class Ma{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new jy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Gy({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 Yy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const qy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Ct=()=>window.ManagedMediaSource||window.MediaSource,Jl=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Wy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},zy=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,od=["timeupdate","progress","play","seeked","stalled","waiting"];var Fe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Fe||(Fe={}));let Qy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new he(Fe.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.currentVideoSegmentLength$=new y(0),this.currentAudioSegmentLength$=new y(0),this.error$=new D,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new D,this.gapWatchdogStarted=!1,this.destroyController=new vi,this.initManifest=Ie(this.destroyController.signal,function(t,s,r){var a;return Ce(this,arguments,function*(){this.element=t,this.manifestUrlString=Qe(s,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Fe.MANIFEST_READY),this.manifest=yield yield M(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Fe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=Ie(this.destroyController.signal,function(){var t;return Ce(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:C.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!s)return yield M(null);let r;try{r=Oy(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:C.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=Ct())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Te.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield M(Object.assign(Object.assign({},r),{representations:xs(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=Ie(this.destroyController.signal,function(t,s,r){var a;return Ce(this,arguments,function*(){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Fe.REPRESENTATIOS_READY);const n=v=>{this.representationSubscription.add(x(v,"error").pipe(fe(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:C.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?zy():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Jl())if(r){const v=document.createElement("source");n(v),v.type="application/x-mpegurl",v.src=r.url,this.element.appendChild(v)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new nd(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new nd(Te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ii(di).subscribe(v=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=Go(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=Qe(this.manifestUrlString,S+di,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(F(...od.filter(v=>v!=="waiting").map(v=>x(this.element,v))).pipe($(v=>this.element?Li(this.element.buffered,this.element.currentTime*1e3):0),pe(),fe(v=>!!v),Oi(v=>{var g;(g=this.stallWatchdogSubscription)===null||g===void 0||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(fe(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=g-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),qy(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let A=0;if(g){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(q=>{var W,J;return(J=(W=q.getLiveSegmentsToLoadState(this.manifest))===null||W===void 0?void 0:W.to)!==null&&J!==void 0?J:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let v=0;this.representationSubscription.add(Ve({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wu(di)).subscribe(({liveLoadBufferLength:g,bufferLength:S})=>te(this,void 0,void 0,function*(){if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=Go(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,J=this.isActiveLowLatency?S:g;let G=et.None;if(this.isActiveLowLatency?G=et.ActiveLowLatency:J<k+W&&J>=k?G=et.LiveWithTargetOffset:A!==0&&J<k&&(G=et.LiveForwardBuffering),isFinite(g)&&(v=g>v?g:v),G===et.LiveForwardBuffering||G===et.LiveWithTargetOffset){const X=v-(k+q),ee=this.normolizeLiveOffset(Math.trunc(A+X/E)),B=Math.abs(ee-A);let L;!g||B<=this.tuning.dashCmafLive.offsetCalculationError?L=A:ee>0&&B>this.tuning.dashCmafLive.offsetCalculationError?L=ee:L=0,this.manifestUrlString=Qe(this.manifestUrlString,L,Se.DASH_CMAF_OFFSET_P)}G!==et.None&&G!==et.ActiveLowLatency&&(v=0,this.updateLive())})))}const d=F(...this.bufferManagers.map(v=>v.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(v=>v.fullyBuffered$.getValue()))),l=F(...this.bufferManagers.map(v=>v.onLastSegment$)).pipe($(()=>this.bufferManagers.some(v=>v.onLastSegment$.getValue())));this.representationSubscription.add(F(this.forceEnded$,Ve({allBuffersFull:d,someBufferEnded:l}).pipe(fe(({allBuffersFull:v,someBufferEnded:g})=>v&&g))).subscribe(()=>{var v;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(v=this.source)===null||v===void 0||v.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(F(...this.bufferManagers.map(v=>v.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield yield M(new Promise(v=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",v)})));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(v,g)=>{var S;return Math.max(v,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),m=this.manifest.representations.video.reduce(h,c);(f||m)&&(this.source.duration=Math.max(f,m)/1e3),this.audioBufferManager&&_(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Fe.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=Ii(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Uy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ma.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,a;return te(this,void 0,void 0,function*(){P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=Qe(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,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(Fe.RUNNING),this.subscription.add(F(...od.map(e=>x(this.element,e)),x(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(x(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(x(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&La(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=di,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=Ii(di).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:C.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return te(this,void 0,void 0,function*(){const s={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.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),La(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Fe.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}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return te(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Ky{constructor(e,t){this.fov=e,this.orientation=t}}class Jy{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 Xy=`#define GLSLIFY 1
|
|
38
38
|
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,Zy=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
@@ -42,5 +42,5 @@ precision highp float;
|
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class eT{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 Ky(this.params.fov,this.params.orientation),this.cameraRotationManager=new Jy(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(Xy,this.gl.VERTEX_SHADER),s=this.createShader(Zy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,l=e+s,d=t+r,c=e-s,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}const Ba=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},tT=(i,e)=>new Fa(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ba()))},Object.assign(Object.assign({},s),e));r.observe(i);const a=x(document,"visibilitychange").pipe($(n=>!document.hidden||Ba())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}});class Xd{constructor(e){this.subscription=new re,this.videoState=new he(oe.STOPPED),this.elementSize$=new y(void 0),this.elementVisible$=new y(!0),this.textTracksManager=new At,this.droppedFramesManager=new Fd,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new zS,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==oe.STOPPED&&n!==p.STOPPED){const d=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-d,u.forcePrecise)}if(n===p.STOPPED){a!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case oe.STOPPED:this.videoState.startTransitionTo(oe.READY),this.prepare();return;case oe.READY:n===p.PAUSED?(this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new eT(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=jt(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(at(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=qt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:I.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($(l=>l.map(({track:d})=>d)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(fe(R),_e()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zi(this.video,t.isLooped,r)),this.subscription.add(Yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(yi(this.video,t.playbackRate,s.playbackRateState$,r)),a(ku(this.video),this.elementSize$),a(tT(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var d;if(l===Fe.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((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=By(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of m){const E=My(S);if(E){c.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&Ny(f,m,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(c);for(const S of v){const E=Fy(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();P(g),this.player.initRepresentations(g.id,(d=this.audioRepresentations.get(g.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else l===Fe.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},r));const n=l=>e.error$.next({id:"RepresentationSwitch",category:I.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(F(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,x(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==Fe.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let v=c.id;!this.elementVisible$.getValue()&&f&&(v=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=Mt(S),A=Mt(c);if(E&&A)return Cs(E,A)&&Cs(E,m)}).map(S=>S.id)[0]),this.player.switchRepresentation(Te.VIDEO,v).catch(n);const g=this.audioRepresentations.get(c.id);g&&this.player.switchRepresentation(Te.AUDIO,g.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),$(l=>{var d;return l&&((d=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===l))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&(!((d=this.params.tuning.spherical)===null||d===void 0)&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:l})=>l===p.READY),pe());this.subscription.add(F(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(F(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),l=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,d=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===l))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Li(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!u&&(r=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),g=Xs(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:d:d!=null?d:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Wt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.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),Gt(this.video)}}class iT extends Xd{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 sT extends Xd{constructor(e){super(e),this.liveOffset=new hn}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ve({interval:Ci(oi),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===oe.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ve({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===oe.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const Ze={};var z;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const Ri=(i,e)=>new Fa(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class rT{constructor(e){this.subscription=new re,this.videoState=new he(z.INITIALIZING),this.textTracksManager=new At,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!==z.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case z.PLAYING:this.pause();break;default:H(t)}break;default:H(s)}},this.video=jt(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(at(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),Gt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:I.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);un(import("hls.js").then(r=>{e||(Ze.Hls=r.default,Ze.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(Ze.Hls,"hls.js not loaded"),this.hls=new Ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){P(Ze.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=l=>{t.error$.next({id:"HlsJsProvider",category:I.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=qt(this.video),a=(l,d)=>this.subscription.add(l.subscribe(d,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(zi(this.video,e.isLooped,s)),this.subscription.add(Yt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(yi(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(Ri(this.hls,Ze.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:I.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)===null||d===void 0?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),a(Ri(this.hls,Ze.Events.MANIFEST_PARSED).pipe($(({levels:l})=>l.reduce((d,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:v,height:g}=c,S=(f=Js((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Mt({width:v,height:g});if(!S)return d;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:m.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:v,height:g},fps:E};return this.trackLevels.set(m,{track:A,level:c}),d.push(A),d},[]))),t.availableVideoTracks$),a(Ri(this.hls,Ze.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){const d=[];for(const c of l.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,v="internal";d.push({id:h,url:f,language:m,type:v})}e.internalTextTracks.startTransitionTo(d)}}),a(Ri(this.hls,Ze.Events.LEVEL_LOADING).pipe($(({url:l})=>at(l))),t.hostname$),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:s}));const n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))===null||d===void 0?void 0:d.track},o=Ri(this.hls,Ze.Events.LEVEL_SWITCHED).pipe($(({level:l})=>n(this.hls.levels[l])));o.pipe(fe(R)).subscribe(t.currentVideoTrack$,s),this.subscription.add(dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var d;if(K(l))return;const c=(d=this.trackLevels.get(l.id))===null||d===void 0?void 0:d.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=F(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return te(this,void 0,void 0,function*(){this.videoState.startTransitionTo(z.PLAYING),(yield Wt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:t})))||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(z.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(z.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const ll="X-Playback-Duration";var dl=i=>te(void 0,void 0,void 0,function*(){var e;const t=yield Ni(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(ll)?parseInt(t.headers.get(ll),10):void 0});const aT=i=>{let e=null;if(i.QUALITY&&(e=Js(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Mt({width:t,height:s})}return e!=null?e:null},nT=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){const c=xs(l[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=aT(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let g;if(c.RESOLUTION){const[E,A]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(g={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:m,size:g,fps:v})}if(d){const c=xs(d[1].split(",").map(v=>v.split("=")).map(([v,g])=>[v,g.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,m=c.NAME;h&&f&&n.push({type:"internal",id:f,label:m,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},oT=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Xr=0;const Sn=(i,e=i,t)=>te(void 0,void 0,void 0,function*(){const r=yield(yield Ni(i)).text();Xr+=1;try{const{qualityManifests:a,textTracks:n}=nT(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(Xr<=t.manifestRetryMaxCount)return yield oT(As(Xr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Sn(i,e,t)}return{qualityManifests:[],textTracks:[]}});var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class lT{constructor(e){var t;this.subscription=new re,this.videoState=new he(ie.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.liveOffset=new hn,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u||l){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=jt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Le.INVARIANT,url:this.params.source.url},Sn(ze(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:I.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(at(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:I.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=qt(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(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(yi(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&R(l.to)){const c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(at(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,l;const d=(l=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||l===void 0?void 0:l.getTime();this.manifestStartTime$.next(d||void 0)},s)),this.subscription.add(Ve({startTime:this.manifestStartTime$.pipe(fe(R)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Gt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[l,"mq"],[d,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=ze(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),dl(u).then(l=>{var d;if(!K(l))this.maxSeekBackTime$.next(l);else{const c=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(K(c)||!isFinite(c))try{Ni(u).then(h=>h.text()).then(h=>{var f;const m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(m){const v=new URL(m,u).toString();dl(v).then(g=>{K(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ne||(ne={}));class dT{constructor(e){this.subscription=new re,this.videoState=new he(ne.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===Y.Requested&&this.seek(d.position),s){case ne.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return H(s)}},this.params=e,this.video=jt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Le.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(at(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Sn(ze(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),l=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",d=this.manifests$.getValue();if(!d.length)return;const c=o?"master":l;return o&&!u&&n.startTransitionTo(this.masterManifest),d.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:I.WTF,message:"HlsProvider internal logic error",thrown:o})},r=qt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(zi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(yi(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&R(d.to)){const h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const f=this.manifests$.getValue().find(m=>m.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(at(f.url));const m=this.params.desiredState.playbackRate.getState(),v=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(m!==v){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(m),g.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from===ne.CHANGING_MANIFEST&&this.videoState.setState(l.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!Pu()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(F(x(o,"addtrack"),x(o,"removetrack"),x(o,"change"),He(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Gt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[l,d]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(l||""));d&&l&&n.searchParams.set(d,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ce||(ce={}));class uT{constructor(e){this.subscription=new re,this.videoState=new he(ce.STOPPED),this.trackUrls={},this.textTracksManager=new At,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!==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),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.autoVideoTrackLimits.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(l&&a!==ce.READY&&!d){this.handleQualityLimitTransition(l.to.max);return}if(a===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(d){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[d.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),a){case ce.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=jt(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:I.WTF,message:"MpegProvider internal logic error",thrown:o})},r=qt(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(zi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(yi(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const l=this.params.desiredState.videoTrack.getTransition();if(l&&R(l.to)){this.params.desiredState.videoTrack.setState(l.to),this.params.output.currentVideoTrack$.next(this.trackUrls[l.to.id].track);const d=this.params.desiredState.playbackRate.getState(),c=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(d!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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),Gt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Oa(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(at(s))}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(s=Object.values(this.trackUrls).find(c=>!Bt(c.track.quality)&&Cs(c.track.quality,e)))===null||s===void 0?void 0:s.track,l=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,d=(a=this.trackUrls[l!=null?l:"0"])===null||a===void 0?void 0:a.track;if(u&&d&&ua(d.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Bt(f.track.quality)&&hi(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(l=>l.track);n=Xs(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const ul=["stun:videostun.mycdn.me:80"],cT=1e3,hT=3,Zr=()=>null;class fT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return te(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 te(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:ul}]};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 te(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 te(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:I.WTF,message:e.message})}onPeerConnectionStream(e){return te(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 te(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),cT)}normalizeOptions(e={}){const t={stunServerList:ul,maxRetryNumber:hT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class pT{constructor(e){this.videoState=new he(se.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:s===p.PAUSED?(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=jt(e.container),this.liveStreamClient=new fT(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),Gt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:I.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};F(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=qt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Yt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},s)).add(F(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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(at(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:Le.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:I.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class cl{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ke;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(ke||(ke={}));var yt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(yt||(yt={}));var ea,ta,ia,sa,gs,ra,Ss,aa,bs,na,ys,oa,Ts,la,Es,da;const Zd=Na().device===Ru.Android,Tt=document.createElement("video"),vT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mT='video/mp4; codecs="hev1.1.6.L93.B0"',eu='video/webm; codecs="vp09.00.10.08"',tu='video/webm; codecs="av01.0.00M.08"',gT='audio/mp4; codecs="mp4a.40.2"',ST='audio/webm; codecs="opus"',Dt={mms:Jd(),mse:Wy(),hls:!!(!((ea=Tt.canPlayType)===null||ea===void 0)&&ea.call(Tt,"application/x-mpegurl")||!((ta=Tt.canPlayType)===null||ta===void 0)&&ta.call(Tt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ne={mp4:!!(!((ia=Tt.canPlayType)===null||ia===void 0)&&ia.call(Tt,"video/mp4")),webm:!!(!((sa=Tt.canPlayType)===null||sa===void 0)&&sa.call(Tt,"video/webm")),cmaf:!0},st={h264:!!(!((ra=(gs=It())===null||gs===void 0?void 0:gs.isTypeSupported)===null||ra===void 0)&&ra.call(gs,vT)),h265:!!(!((aa=(Ss=It())===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||aa===void 0)&&aa.call(Ss,mT)),vp9:!!(!((na=(bs=It())===null||bs===void 0?void 0:bs.isTypeSupported)===null||na===void 0)&&na.call(bs,eu)),av1:!!(!((oa=(ys=It())===null||ys===void 0?void 0:ys.isTypeSupported)===null||oa===void 0)&&oa.call(ys,tu)),aac:!!(!((la=(Ts=It())===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||la===void 0)&&la.call(Ts,gT)),opus:!!(!((da=(Es=It())===null||Es===void 0?void 0:Es.isTypeSupported)===null||da===void 0)&&da.call(Es,ST))},_i=(st.h264||st.h265)&&st.aac;let Lt;const bT=()=>te(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:tu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:eu})}))]);Lt={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}});try{bT()}catch(i){console.error(i)}const Fi=Dt.hls&&Ne.mp4,yT=()=>Object.keys(st).filter(i=>st[i]),TT=(i,e=!1,t=!1)=>{const s=Dt.mse||Dt.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&Ne.mp4&&_i;case b.DASH_WEBM:return s&&Ne.webm&&st.vp9&&st.opus;case b.DASH_WEBM_AV1:return s&&Ne.webm&&st.av1&&st.opus;case b.DASH_LIVE:return Dt.mse&&Ne.mp4&&_i;case b.DASH_LIVE_CMAF:return s&&Ne.mp4&&_i&&Ne.cmaf;case b.DASH_ONDEMAND:return s&&Ne.mp4&&_i;case b.HLS:case b.HLS_ONDEMAND:return Fi||e&&Dt.mse&&Ne.mp4&&_i;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return Fi;case b.MPEG:return Ne.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Dt.webrtc&&Dt.ws&&st.h264&&(Ne.mp4||Ne.webm);default:return H(r)}})},St=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case yt.VP9:return[e,t];case yt.AV1:return[t,e];case yt.NONE:return[];case yt.SMOOTH:return Lt?Lt[t].smooth?[t,e]:Lt[e].smooth?[e,t]:[t,e]:[e,t];case yt.POWER_EFFICIENT:return Lt?Lt[t].powerEfficient?[t,e]:Lt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(i)}return[e,t]},ET=({webmCodec:i,androidPreferredFormat:e})=>{if(Zd)switch(e){case ke.MPEG:return[b.MPEG,...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case ke.HLS:return[b.HLS,b.HLS_ONDEMAND,...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case ke.DASH:return[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case ke.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...St(i),b.HLS,b.HLS_ONDEMAND];case ke.DASH_ANY_WEBM:return[...St(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case ke.DASH_SEP:return[b.DASH_SEP,b.MPEG,...St(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:H(e)}return Fi?[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},$T=({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(Zd)switch(i){case ke.DASH:case ke.DASH_ANY_MPEG:case ke.DASH_ANY_WEBM:case ke.DASH_SEP:{o=a;break}case ke.HLS:case ke.MPEG:{o=n;break}default:H(i)}else Fi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},hl=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 AT=i=>new Fa(e=>{const t=new re,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:l,to:d})=>`${l}-${d}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:l})=>l!==void 0)),n=new D;let o=0,u="unknown";return t.add(s.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const wT={chunkDuration:5e3,maxParallelRequests:5};class kT{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new D,this.noAvailableProvidersError$=new D,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new D,warning$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=TT([...$T(this.params.tuning),...ET(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>R(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new cl(a);const n=[...hl(!0),...hl(!1)];this.chromecastFormatsIterator=new cl(n.filter(o=>R(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return H(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_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new iT(Object.assign(Object.assign({},n),{source:o,sourceHls:u}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new sT(Object.assign(Object.assign({},n),{source:o}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Fi||!this.params.tuning.useHlsJs?new dT(Object.assign(Object.assign({},n),{source:o})):new rT(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 lT(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 uT(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new db(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},wT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new pT({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 H(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 wS({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()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 xs(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,s=0;return e.add(F(this.providerOutput.error$,AT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:I.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(fe(({to:a})=>a===p.PLAYING),_e()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===I.NETWORK,o=r.category===I.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=s<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ae.SCREEN)}})),e}}const PT=5e3,fl="one_video_throughput",pl="one_video_rtt",ht=window.navigator.connection,vl=()=>{const i=ht==null?void 0:ht.downlink;if(R(i)&&i!==10)return i*1e3},ml=()=>{const i=ht==null?void 0:ht.rtt;if(R(i)&&i!==3e3)return i},gl=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class xi{constructor(e){var t,s;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=xi.load(fl)||(e.useBrowserEstimation?vl():void 0)||PT,a=(s=(t=xi.load(pl))!==null&&t!==void 0?t:e.useBrowserEstimation?ml():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(gl(r,a,e.rttPenaltyRequestSize)),this.throughput=Ma.getSmoothedValue(r,-1,e),this.rtt=Ma.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vl();u&&this.throughput.next(u);const l=ml();R(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add(x(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hr.set(fl,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hr.set(pl,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ve({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>gl(n,o,e.rttPenaltyRequestSize)),fe(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=le();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(x(e,"progress").pipe(_e()).subscribe(a=>{t=a.loaded,s=le()}));break;case 1:case 0:r.add(x(e,"loadstart").subscribe(()=>{t=0,s=le()}));break}r.add(x(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,l=o-s;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=d=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=({done:d,value:c})=>te(this,void 0,void 0,function*(){if(d)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=le()}o=le()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());yield s==null?void 0:s.read().then(l,u)}});this.concurrentDownloads.add(e),s==null||s.read().then(l,u)}addRawSpeed(e,t,s=1,r=!1){if(xi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=hr.get(e);if(R(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Sl={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Le.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Le.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:yt.VP9,androidPreferredFormat:ke.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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},RT=i=>{var e;return Object.assign(Object.assign({},_u(i,Sl)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Sl.configName]})};var bl=({seekState:i,position$:e})=>F(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),fe(R)),e.pipe(fe(()=>i.getState().state===Y.None))),_T=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const CT=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(fe(r=>r.length>0),_e()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class OT{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Cu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:Y.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 y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(bt.NONE),chromecastState$:new y(ye.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.events={inited$:new D,ready$:new D,started$:new D,playing$:new D,paused$:new D,stopped$:new D,willStart$:new D,willResume$:new D,willPause$:new D,willStop$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:YS},this.initLogs(),this.tuning=RT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Lu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new xi(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}>`})),l=`Player.${String(s)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:I.WTF,message:d,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new kT({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;window.clearTimeout(this.hasLiveOffsetByPausedTimer),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&&!Ba()?x(document,"visibilitychange").pipe(_e()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ye.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()===ye.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();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),_e()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;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;return CT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return R(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e===p.STOPPED),_e()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:Y.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:I.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,u)=>Bt(o)?1:Bt(u)?-1:hi(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(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).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($(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(Ve({hasLiveOffsetByPaused:F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),pe(),$(n=>n===p.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ve({atLiveEdge:Ve({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:u})=>{const l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),pe(),Oi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ve({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe($(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),pe(),Oi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),pe()).subscribe(this.info.volume$)).add(bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(F(e.providerOutput.endedEvent$.pipe(_s(!0)),e.providerOutput.seekedEvent$.pipe(_s(!1))).pipe(pe()).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($(n=>({id:n?`No${n}`:"NoProviders",category:I.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(_e(),$(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),$(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),$(()=>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 y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n===p.PLAYING),_e()).subscribe(()=>s.next(!1)));let r=0;const a=F(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),pe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(F(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const l=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:l==null?void 0:l.videoWidth,height:l==null?void 0:l.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(F(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=this.chromecastInitializer.castState$.getValue();let d;l===ye.CONNECTED?d=bt.SECOND_SCREEN:u?n?d=bt.PIP:o?d=bt.FULLSCREEN:d=bt.INLINE:d=bt.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new re;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),_e()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Xs(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(F(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(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),GS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>jS(s)),this.providerContainer.current$.subscribe(({type:s})=>vs("provider",s)),t.duration$.subscribe(s=>vs("duration",s)),t.availableVideoTracks$.pipe(fe(s=>!!s.length),_e()).subscribe(s=>vs("tracks",s)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),t.position$.subscribe(new tt("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),t.isBuffering$.subscribe(new tt("isBuffering"))].forEach(s=>this.subscription.add(s)),vs("codecs",yT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>te(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:I.DOM,message:String(r)})})});this.subscription.add(F(x(document,"visibilitychange"),x(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const MT=`@vkontakte/videoplayer-core@${Iu}`;export{ye as ChromecastState,ca as HttpConnectionType,FT as Observable,p as PlaybackState,OT as Player,MT as SDK_VERSION,VT as Subject,UT as Subscription,bt as Surface,Iu as VERSION,HT as ValueSubject,b as VideoFormat,jT as VideoQuality};
|
|
45
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class eT{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 Ky(this.params.fov,this.params.orientation),this.cameraRotationManager=new Jy(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(Xy,this.gl.VERTEX_SHADER),s=this.createShader(Zy,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}}const Ba=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},tT=(i,e)=>new Fa(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ba()))},Object.assign(Object.assign({},s),e));r.observe(i);const a=x(document,"visibilitychange").pipe($(n=>!document.hidden||Ba())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}});class Xl{constructor(e){this.subscription=new re,this.videoState=new he(oe.STOPPED),this.elementSize$=new y(void 0),this.elementVisible$=new y(!0),this.textTracksManager=new At,this.droppedFramesManager=new Fl,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new zS,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==oe.STOPPED&&n!==p.STOPPED){const 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!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case oe.STOPPED:this.videoState.startTransitionTo(oe.READY),this.prepare();return;case oe.READY:n===p.PAUSED?(this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case oe.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new eT(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=jt(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(at(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=qt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:C.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($(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(fe(_),Re()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(zi(this.video,t.isLooped,r)),this.subscription.add(Yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ti(this.video,t.playbackRate,s.playbackRateState$,r)),a(ku(this.video),this.elementSize$),a(tT(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Fe.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((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=By(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of m){const E=My(S);if(E){c.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&Ny(f,m,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(c);for(const S of v){const E=Fy(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();P(g),this.player.initRepresentations(g.id,(l=this.audioRepresentations.get(g.id))===null||l===void 0?void 0:l.id,this.params.sourceHls)}else d===Fe.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(F(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,x(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Fe.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();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let v=c.id;!this.elementVisible$.getValue()&&f&&(v=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=Mt(S),A=Mt(c);if(E&&A)return Is(E,A)&&Is(E,m)}).map(S=>S.id)[0]),this.player.switchRepresentation(Te.VIDEO,v).catch(n);const g=this.audioRepresentations.get(c.id);g&&this.player.switchRepresentation(Te.AUDIO,g.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(pe(),$(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:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===p.READY),pe());this.subscription.add(F(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(F(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Li(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(l&&!u&&(r=(s=this.audioRepresentations.get(l.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),g=Xs(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:l:l!=null?l:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Wt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(oe.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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),Gt(this.video)}}class iT extends Xl{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 sT extends Xl{constructor(e){super(e),this.liveOffset=new hn}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ve({interval:Ii(di),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===oe.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ve({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===oe.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const We={};var z;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const ni=(i,e)=>new Fa(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class rT{constructor(e){this.subscription=new re,this.videoState=new he(z.INITIALIZING),this.textTracksManager=new At,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!==z.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case z.PLAYING:this.pause();break;default:H(t)}break;default:H(s)}},this.video=jt(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(at(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),Gt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);un(import("hls.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){P(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=qt(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(zi(this.video,e.isLooped,s)),this.subscription.add(Yt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ti(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ni(this.hls,We.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.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(z.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),a(ni(this.hls,We.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:v,height:g}=c,S=(f=Js((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Mt({width:v,height:g});if(!S)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:m.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:v,height:g},fps:E};return this.trackLevels.set(m,{track:A,level:c}),l.push(A),l},[]))),t.availableVideoTracks$),a(ni(this.hls,We.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,v="internal";l.push({id:h,url:f,language:m,type:v})}e.internalTextTracks.startTransitionTo(l)}}),a(ni(this.hls,We.Events.LEVEL_LOADING).pipe($(({url:d})=>at(d))),t.hostname$),a(ni(this.hls,We.Events.FRAG_CHANGED),d=>{var l,c,h,f;const{video:m,audio:v}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((l=m==null?void 0:m.endPTS)!==null&&l!==void 0?l:0)-((c=m==null?void 0:m.startPTS)!==null&&c!==void 0?c:0))*1e3),t.currentAudioSegmentLength$.next((((h=v==null?void 0:v.endPTS)!==null&&h!==void 0?h:0)-((f=v==null?void 0:v.startPTS)!==null&&f!==void 0?f:0))*1e3)}),this.subscription.add(lt(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=ni(this.hls,We.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(fe(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(K(d))return;const c=(l=this.trackLevels.get(d.id))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=F(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return te(this,void 0,void 0,function*(){this.videoState.startTransitionTo(z.PLAYING),(yield Wt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:t})))||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(z.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(z.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const dd="X-Playback-Duration";var ld=i=>te(void 0,void 0,void 0,function*(){var e;const t=yield Ni(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(dd)?parseInt(t.headers.get(dd),10):void 0});const aT=i=>{let e=null;if(i.QUALITY&&(e=Js(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Mt({width:t,height:s})}return e!=null?e:null},nT=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
+
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){const c=xs(d[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=aT(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let g;if(c.RESOLUTION){const[E,A]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(g={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:m,size:g,fps:v})}if(l){const c=xs(l[1].split(",").map(v=>v.split("=")).map(([v,g])=>[v,g.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,m=c.NAME;h&&f&&n.push({type:"internal",id:f,label:m,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},oT=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Xr=0;const Sn=(i,e=i,t)=>te(void 0,void 0,void 0,function*(){const r=yield(yield Ni(i)).text();Xr+=1;try{const{qualityManifests:a,textTracks:n}=nT(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(Xr<=t.manifestRetryMaxCount)return yield oT(As(Xr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Sn(i,e,t)}return{qualityManifests:[],textTracks:[]}});var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class dT{constructor(e){var t;this.subscription=new re,this.videoState=new he(ie.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.liveOffset=new hn,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=jt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Le.INVARIANT,url:this.params.source.url},Sn(Qe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:C.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(at(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=qt(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(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(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&&_(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(at(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,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(Ve({startTime:this.manifestStartTime$.pipe(fe(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(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=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Gt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=Qe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),ld(u).then(d=>{var l;if(!K(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(K(c)||!isFinite(c))try{Ni(u).then(h=>h.text()).then(h=>{var f;const m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(m){const v=new URL(m,u).toString();ld(v).then(g=>{K(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ne||(ne={}));class lT{constructor(e){this.subscription=new re,this.videoState=new he(ne.STOPPED),this.textTracksManager=new At,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(s===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===Y.Requested&&this.seek(l.position),s){case ne.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return H(s)}},this.params=e,this.video=jt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Le.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(at(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Sn(Qe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=qt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(zi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&_(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(m=>m.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(at(f.url));const m=this.params.desiredState.playbackRate.getState(),v=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(m!==v){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(m),g.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===ne.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe($(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)),!Pu()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(F(x(o,"addtrack"),x(o,"removetrack"),x(o,"change"),He(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=F(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(rt(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Gt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(K(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&d&&n.searchParams.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ce||(ce={}));class uT{constructor(e){this.subscription=new re,this.videoState=new he(ce.STOPPED),this.trackUrls={},this.textTracksManager=new At,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!==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),O(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!==ce.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.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.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),a){case ce.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=jt(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:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=qt(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(zi(this.video,t.isLooped,s)),this.subscription.add(Yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&_(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const l=this.params.desiredState.playbackRate.getState(),c=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(l!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(l),h.playbackRate=l)}}this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=F(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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),Gt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Oa(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(at(s))}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(s=Object.values(this.trackUrls).find(c=>!Bt(c.track.quality)&&Is(c.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&ua(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Bt(f.track.quality)&&fi(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=Xs(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const ud=["stun:videostun.mycdn.me:80"],cT=1e3,hT=3,Zr=()=>null;class fT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return te(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 te(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:ud}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return te(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 te(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:C.WTF,message:e.message})}onPeerConnectionStream(e){return te(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 te(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),cT)}normalizeOptions(e={}){const t={stunServerList:ud,maxRetryNumber:hT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class pT{constructor(e){this.videoState=new he(se.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:s===p.PAUSED?(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=jt(e.container),this.liveStreamClient=new fT(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),Gt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};F(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=qt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Yt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},s)).add(F(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(rt(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(at(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:Le.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Wt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class cd{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 ke;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(ke||(ke={}));var yt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(yt||(yt={}));var ea,ta,ia,sa,gs,ra,Ss,aa,bs,na,ys,oa,Ts,da,Es,la;const Zl=Na().device===_u.Android,Tt=document.createElement("video"),vT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mT='video/mp4; codecs="hev1.1.6.L93.B0"',eu='video/webm; codecs="vp09.00.10.08"',tu='video/webm; codecs="av01.0.00M.08"',gT='audio/mp4; codecs="mp4a.40.2"',ST='audio/webm; codecs="opus"',Dt={mms:Jl(),mse:Wy(),hls:!!(!((ea=Tt.canPlayType)===null||ea===void 0)&&ea.call(Tt,"application/x-mpegurl")||!((ta=Tt.canPlayType)===null||ta===void 0)&&ta.call(Tt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ne={mp4:!!(!((ia=Tt.canPlayType)===null||ia===void 0)&&ia.call(Tt,"video/mp4")),webm:!!(!((sa=Tt.canPlayType)===null||sa===void 0)&&sa.call(Tt,"video/webm")),cmaf:!0},st={h264:!!(!((ra=(gs=Ct())===null||gs===void 0?void 0:gs.isTypeSupported)===null||ra===void 0)&&ra.call(gs,vT)),h265:!!(!((aa=(Ss=Ct())===null||Ss===void 0?void 0:Ss.isTypeSupported)===null||aa===void 0)&&aa.call(Ss,mT)),vp9:!!(!((na=(bs=Ct())===null||bs===void 0?void 0:bs.isTypeSupported)===null||na===void 0)&&na.call(bs,eu)),av1:!!(!((oa=(ys=Ct())===null||ys===void 0?void 0:ys.isTypeSupported)===null||oa===void 0)&&oa.call(ys,tu)),aac:!!(!((da=(Ts=Ct())===null||Ts===void 0?void 0:Ts.isTypeSupported)===null||da===void 0)&&da.call(Ts,gT)),opus:!!(!((la=(Es=Ct())===null||Es===void 0?void 0:Es.isTypeSupported)===null||la===void 0)&&la.call(Es,ST))},Ri=(st.h264||st.h265)&&st.aac;let Lt;const bT=()=>te(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:tu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:eu})}))]);Lt={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}});try{bT()}catch(i){console.error(i)}const Fi=Dt.hls&&Ne.mp4,yT=()=>Object.keys(st).filter(i=>st[i]),TT=(i,e=!1,t=!1)=>{const s=Dt.mse||Dt.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&Ne.mp4&&Ri;case b.DASH_WEBM:return s&&Ne.webm&&st.vp9&&st.opus;case b.DASH_WEBM_AV1:return s&&Ne.webm&&st.av1&&st.opus;case b.DASH_LIVE:return Dt.mse&&Ne.mp4&&Ri;case b.DASH_LIVE_CMAF:return s&&Ne.mp4&&Ri&&Ne.cmaf;case b.DASH_ONDEMAND:return s&&Ne.mp4&&Ri;case b.HLS:case b.HLS_ONDEMAND:return Fi||e&&Dt.mse&&Ne.mp4&&Ri;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return Fi;case b.MPEG:return Ne.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Dt.webrtc&&Dt.ws&&st.h264&&(Ne.mp4||Ne.webm);default:return H(r)}})},St=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case yt.VP9:return[e,t];case yt.AV1:return[t,e];case yt.NONE:return[];case yt.SMOOTH:return Lt?Lt[t].smooth?[t,e]:Lt[e].smooth?[e,t]:[t,e]:[e,t];case yt.POWER_EFFICIENT:return Lt?Lt[t].powerEfficient?[t,e]:Lt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(i)}return[e,t]},ET=({webmCodec:i,androidPreferredFormat:e})=>{if(Zl)switch(e){case ke.MPEG:return[b.MPEG,...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case ke.HLS:return[b.HLS,b.HLS_ONDEMAND,...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case ke.DASH:return[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case ke.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...St(i),b.HLS,b.HLS_ONDEMAND];case ke.DASH_ANY_WEBM:return[...St(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case ke.DASH_SEP:return[b.DASH_SEP,b.MPEG,...St(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:H(e)}return Fi?[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...St(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},$T=({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(Zl)switch(i){case ke.DASH:case ke.DASH_ANY_MPEG:case ke.DASH_ANY_WEBM:case ke.DASH_SEP:{o=a;break}case ke.HLS:case ke.MPEG:{o=n;break}default:H(i)}else Fi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},hd=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 AT=i=>new Fa(e=>{const t=new re,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:d})=>d!==void 0)),n=new D;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 wT={chunkDuration:5e3,maxParallelRequests:5};class kT{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new D,this.noAvailableProvidersError$=new D,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new D,warning$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=TT([...$T(this.params.tuning),...ET(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>_(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 cd(a);const n=[...hd(!0),...hd(!1)];this.chromecastFormatsIterator=new cd(n.filter(o=>_(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:C.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return H(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_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new iT(Object.assign(Object.assign({},n),{source:o,sourceHls:u}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new sT(Object.assign(Object.assign({},n),{source:o}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Fi||!this.params.tuning.useHlsJs?new lT(Object.assign(Object.assign({},n),{source:o})):new rT(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 dT(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 uT(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new lb(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},wT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new pT({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 H(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 wS({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()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 xs(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,s=0;return e.add(F(this.providerOutput.error$,AT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:C.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(fe(({to:a})=>a===p.PLAYING),Re()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===C.NETWORK,o=r.category===C.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ae.SCREEN)}})),e}}const PT=5e3,fd="one_video_throughput",pd="one_video_rtt",ht=window.navigator.connection,vd=()=>{const i=ht==null?void 0:ht.downlink;if(_(i)&&i!==10)return i*1e3},md=()=>{const i=ht==null?void 0:ht.rtt;if(_(i)&&i!==3e3)return i},gd=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class xi{constructor(e){var t,s;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=xi.load(fd)||(e.useBrowserEstimation?vd():void 0)||PT,a=(s=(t=xi.load(pd))!==null&&t!==void 0?t:e.useBrowserEstimation?md():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(gd(r,a,e.rttPenaltyRequestSize)),this.throughput=Ma.getSmoothedValue(r,-1,e),this.rtt=Ma.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vd();u&&this.throughput.next(u);const d=md();_(d)&&this.rtt.next(d)};ht&&"onchange"in ht&&this.subscription.add(x(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{hr.set(fd,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{hr.set(pd,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ve({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>gd(n,o,e.rttPenaltyRequestSize)),fe(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=de();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(x(e,"progress").pipe(Re()).subscribe(a=>{t=a.loaded,s=de()}));break;case 1:case 0:r.add(x(e,"loadstart").subscribe(()=>{t=0,s=de()}));break}r.add(x(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=de(),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=de(),n=0,o=de();const u=l=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>te(this,void 0,void 0,function*(){if(l)!t&&this.addRawSpeed(r,de()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(de()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=de()}o=de()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&de()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,de()-o,this.concurrentDownloads.size),n=0,o=de());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(xi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=hr.get(e);if(_(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Sd={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Le.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Le.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:yt.VP9,androidPreferredFormat:ke.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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},_T=i=>{var e;return Object.assign(Object.assign({},Ru(i,Sd)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Sd.configName]})};var bd=({seekState:i,position$:e})=>F(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),fe(_)),e.pipe(fe(()=>i.getState().state===Y.None))),RT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const IT=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(fe(r=>r.length>0),Re()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class OT{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Iu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:Y.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 y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(bt.NONE),chromecastState$:new y(ye.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0)},this.events={inited$:new D,ready$:new D,started$:new D,playing$:new D,paused$:new D,stopped$:new D,willStart$:new D,willResume$:new D,willPause$:new D,willStop$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:YS},this.initLogs(),this.tuning=_T(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Lu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new xi(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:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=RT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new kT({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;window.clearTimeout(this.hasLiveOffsetByPausedTimer),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&&!Ba()?x(document,"visibilitychange").pipe(Re()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ye.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()===ye.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();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),Re()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;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;return IT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return _(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e===p.STOPPED),Re()).subscribe(()=>{this.initedAt=de(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:Y.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,u)=>Bt(o)?1:Bt(u)?-1:fi(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.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).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($(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(Ve({hasLiveOffsetByPaused:F(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),pe(),$(n=>n===p.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ve({atLiveEdge:Ve({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:u})=>{const d=this.getActiveLiveDelay(u);return n&&Math.abs(o)<d/1e3}),pe(),Oi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ve({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe($(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),pe(),Oi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),pe()).subscribe(this.info.volume$)).add(bd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(F(e.providerOutput.endedEvent$.pipe(Rs(!0)),e.providerOutput.seekedEvent$.pipe(Rs(!1))).pipe(pe()).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($(n=>({id:n?`No${n}`:"NoProviders",category:C.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(Re(),$(n=>n!=null?n:de()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Re(),$(()=>de()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Re(),$(()=>de()-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 y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n===p.PLAYING),Re()).subscribe(()=>s.next(!1)));let r=0;const a=F(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),pe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(F(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const 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(F(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===ye.CONNECTED?l=bt.SECOND_SCREEN:u?n?l=bt.PIP:o?l=bt.FULLSCREEN:l=bt.INLINE:l=bt.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($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new re;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(s=>s.length>0),Re()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Xs(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(F(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(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),GS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>jS(s)),this.providerContainer.current$.subscribe(({type:s})=>vs("provider",s)),t.duration$.subscribe(s=>vs("duration",s)),t.availableVideoTracks$.pipe(fe(s=>!!s.length),Re()).subscribe(s=>vs("tracks",s)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),t.position$.subscribe(new tt("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),t.isBuffering$.subscribe(new tt("isBuffering"))].forEach(s=>this.subscription.add(s)),vs("codecs",yT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>te(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:C.DOM,message:String(r)})})});this.subscription.add(F(x(document,"visibilitychange"),x(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const MT=`@vkontakte/videoplayer-core@${Cu}`;export{ye as ChromecastState,ca as HttpConnectionType,FT as Observable,p as PlaybackState,OT as Player,MT as SDK_VERSION,VT as Subject,UT as Subscription,bt as Surface,Cu as VERSION,HT as ValueSubject,b as VideoFormat,jT as VideoQuality};
|