@vkontakte/videoplayer-core 2.0.98-dev.72824ff7.0 → 2.0.98-dev.97d8def3.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/es2018.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.98-dev.72824ff7.0
3
- * Thu, 15 Feb 2024 17:44:11 GMT
2
+ * @vkontakte/videoplayer-core v2.0.98-dev.97d8def3.0
3
+ * Thu, 15 Feb 2024 16:10:49 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
5
5
  */
6
- import{ValueSubject as T,Subject as C,Subscription as ue,isNonNullable as D,ErrorCategory as R,isNullable as j,fromEvent as U,assertNever as z,merge as H,tap as vs,map as _,observableFrom as Ge,filterChanged as ve,assertNonNullable as P,debounce as st,getHighestQuality as ru,timeout as au,getCurrentBrowser as hr,CurrentClientBrowser as ja,combine as Le,once as Ae,mapTo as Hi,filter as ae,now as le,assertNotEmptyArray as nu,videoSizeToQuality as si,isInvariantQuality as yi,isHigher as Vi,isLower as qs,isHigherOrEqual as Ra,isLowerOrEqual as Fo,Observable as fr,debounceFn as ou,interval as Ti,VideoQuality as at,videoQualityToHeight as du,abortable as ce,getExponentialDelay as ms,throttle as uu,isIOS as lu,CurrentClientDevice as cu,safeStorage as Fr,fillWithDefault as hu,Logger as fu}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as lb,Subject as cb,Subscription as hb,ValueSubject as fb,VideoQuality as pb}from"@vkontakte/videoplayer-shared/es2018.esm.js";const pu="2.0.98-dev.72824ff7.0";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Ue;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ue||(Ue={}));var Ce;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ce||(Ce={}));var Ss;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ss||(Ss={}));var ee;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ee||(ee={}));var Zt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(Zt||(Zt={}));var mu=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class gu{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ce.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new T(Ce.NOT_AVAILABLE),this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=D((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||mu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();j(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();j(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(U(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return z(r.sessionState)}})).add(H(U(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),Ge([i.getCastState()])).pipe(ve(),_(vu),vs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ce.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(j(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===Ce.CONNECTED?D(this.connection$.getValue())?Ce.CONNECTED:Ce.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const vu=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ce.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ce.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ce.CONNECTING;case cast.framework.CastState.CONNECTED:return Ce.CONNECTED;default:return z(s)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var zt=function(s){try{return!!s()}catch(e){return!0}},Su=zt,pr=!Su(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Uo=pr,Vo=Function.prototype,Ia=Vo.call,bu=Uo&&Vo.bind.bind(Ia,Ia),qt=Uo?bu:function(s){return function(){return Ia.apply(s,arguments)}},Ho=qt,yu=Ho({}.toString),Tu=Ho("".slice),mr=function(s){return Tu(yu(s),8,-1)},Eu=qt,$u=zt,Au=mr,Vr=Object,wu=Eu("".split),ku=$u(function(){return!Vr("z").propertyIsEnumerable(0)})?function(s){return Au(s)=="String"?wu(s,""):Vr(s)}:Vr,gr=function(s){return s==null},_u=gr,Pu=TypeError,Qa=function(s){if(_u(s))throw Pu("Can't call method on "+s);return s},Du=ku,Ru=Qa,Es=function(s){return Du(Ru(s))},Wi={},Ps=function(s){return s&&s.Math==Math&&s},St=Ps(typeof globalThis=="object"&&globalThis)||Ps(typeof window=="object"&&window)||Ps(typeof self=="object"&&self)||Ps(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),La=typeof document=="object"&&document.all,Iu=typeof La=="undefined"&&La!==void 0,Go={all:La,IS_HTMLDDA:Iu},Yo=Go,Lu=Yo.all,ct=Yo.IS_HTMLDDA?function(s){return typeof s=="function"||s===Lu}:function(s){return typeof s=="function"},xu=St,Cu=ct,gn=xu.WeakMap,Bu=Cu(gn)&&/native code/.test(String(gn)),vn=ct,zo=Go,Mu=zo.all,Ai=zo.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:vn(s)||s===Mu}:function(s){return typeof s=="object"?s!==null:vn(s)},Ou=zt,wi=!Ou(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Qi={},Nu=St,Sn=Ai,xa=Nu.document,Fu=Sn(xa)&&Sn(xa.createElement),qo=function(s){return Fu?xa.createElement(s):{}},Uu=wi,Vu=zt,Hu=qo,jo=!Uu&&!Vu(function(){return Object.defineProperty(Hu("div"),"a",{get:function(){return 7}}).a!=7}),Gu=wi,Yu=zt,Wo=Gu&&Yu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),zu=Ai,qu=String,ju=TypeError,ki=function(s){if(zu(s))return s;throw ju(qu(s)+" is not an object")},Wu=pr,Ds=Function.prototype.call,jt=Wu?Ds.bind(Ds):function(){return Ds.apply(Ds,arguments)},Ka={},Hr=Ka,Gr=St,Qu=ct,bn=function(s){return Qu(s)?s:void 0},Ja=function(s,e){return arguments.length<2?bn(Hr[s])||bn(Gr[s]):Hr[s]&&Hr[s][e]||Gr[s]&&Gr[s][e]},Ku=qt,Xa=Ku({}.isPrototypeOf),Ju=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Qo=St,Yr=Ju,yn=Qo.process,Tn=Qo.Deno,En=yn&&yn.versions||Tn&&Tn.version,$n=En&&En.v8,gt,Js;$n&&(gt=$n.split("."),Js=gt[0]>0&&gt[0]<4?1:+(gt[0]+gt[1]));!Js&&Yr&&(gt=Yr.match(/Edge\/(\d+)/),(!gt||gt[1]>=74)&&(gt=Yr.match(/Chrome\/(\d+)/),gt&&(Js=+gt[1])));var Xu=Js,An=Xu,Zu=zt,el=St,tl=el.String,Ko=!!Object.getOwnPropertySymbols&&!Zu(function(){var s=Symbol();return!tl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&An&&An<41}),il=Ko,Jo=il&&!Symbol.sham&&typeof Symbol.iterator=="symbol",sl=Ja,rl=ct,al=Xa,nl=Jo,ol=Object,Xo=nl?function(s){return typeof s=="symbol"}:function(s){var e=sl("Symbol");return rl(e)&&al(e.prototype,ol(s))},dl=String,Za=function(s){try{return dl(s)}catch(e){return"Object"}},ul=ct,ll=Za,cl=TypeError,en=function(s){if(ul(s))return s;throw cl(ll(s)+" is not a function")},hl=en,fl=gr,vr=function(s,e){var t=s[e];return fl(t)?void 0:hl(t)},zr=jt,qr=ct,jr=Ai,pl=TypeError,ml=function(s,e){var t,i;if(e==="string"&&qr(t=s.toString)&&!jr(i=zr(t,s))||qr(t=s.valueOf)&&!jr(i=zr(t,s))||e!=="string"&&qr(t=s.toString)&&!jr(i=zr(t,s)))return i;throw pl("Can't convert object to primitive value")},Zo={exports:{}},wn=St,gl=Object.defineProperty,vl=function(s,e){try{gl(wn,s,{value:e,configurable:!0,writable:!0})}catch(t){wn[s]=e}return e},Sl=St,bl=vl,kn="__core-js_shared__",yl=Sl[kn]||bl(kn,{}),ed=yl,_n=ed;(Zo.exports=function(s,e){return _n[s]||(_n[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var td=Zo.exports,Tl=Qa,El=Object,Sr=function(s){return El(Tl(s))},$l=qt,Al=Sr,wl=$l({}.hasOwnProperty),Wt=Object.hasOwn||function(e,t){return wl(Al(e),t)},kl=qt,_l=0,Pl=Math.random(),Dl=kl(1 .toString),id=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Dl(++_l+Pl,36)},Rl=St,Il=td,Pn=Wt,Ll=id,xl=Ko,Cl=Jo,Ni=Rl.Symbol,Wr=Il("wks"),Bl=Cl?Ni.for||Ni:Ni&&Ni.withoutSetter||Ll,bt=function(s){return Pn(Wr,s)||(Wr[s]=xl&&Pn(Ni,s)?Ni[s]:Bl("Symbol."+s)),Wr[s]},Ml=jt,Dn=Ai,Rn=Xo,Ol=vr,Nl=ml,Fl=bt,Ul=TypeError,Vl=Fl("toPrimitive"),Hl=function(s,e){if(!Dn(s)||Rn(s))return s;var t=Ol(s,Vl),i;if(t){if(e===void 0&&(e="default"),i=Ml(t,s,e),!Dn(i)||Rn(i))return i;throw Ul("Can't convert object to primitive value")}return e===void 0&&(e="number"),Nl(s,e)},Gl=Hl,Yl=Xo,tn=function(s){var e=Gl(s,"string");return Yl(e)?e:e+""},zl=wi,ql=jo,jl=Wo,Rs=ki,In=tn,Wl=TypeError,Qr=Object.defineProperty,Ql=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";Qi.f=zl?jl?function(e,t,i){if(Rs(e),t=In(t),Rs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=Ql(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(Rs(e),t=In(t),Rs(i),ql)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Wl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var br=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Kl=wi,Jl=Qi,Xl=br,$s=Kl?function(s,e,t){return Jl.f(s,e,Xl(1,t))}:function(s,e,t){return s[e]=t,s},Zl=td,ec=id,Ln=Zl("keys"),sn=function(s){return Ln[s]||(Ln[s]=ec(s))},rn={},tc=Bu,sd=St,ic=Ai,sc=$s,Zr=Wt,ea=ed,rc=sn,ac=rn,xn="Object already initialized",Ca=sd.TypeError,nc=sd.WeakMap,Xs,bs,Zs,oc=function(s){return Zs(s)?bs(s):Xs(s,{})},dc=function(s){return function(e){var t;if(!ic(e)||(t=bs(e)).type!==s)throw Ca("Incompatible receiver, "+s+" required");return t}};if(tc||ea.state){var Et=ea.state||(ea.state=new nc);Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Xs=function(s,e){if(Et.has(s))throw Ca(xn);return e.facade=s,Et.set(s,e),e},bs=function(s){return Et.get(s)||{}},Zs=function(s){return Et.has(s)}}else{var Ii=rc("state");ac[Ii]=!0,Xs=function(s,e){if(Zr(s,Ii))throw Ca(xn);return e.facade=s,sc(s,Ii,e),e},bs=function(s){return Zr(s,Ii)?s[Ii]:{}},Zs=function(s){return Zr(s,Ii)}}var uc={set:Xs,get:bs,has:Zs,enforce:oc,getterFor:dc},lc=pr,rd=Function.prototype,Cn=rd.apply,Bn=rd.call,cc=typeof Reflect=="object"&&Reflect.apply||(lc?Bn.bind(Cn):function(){return Bn.apply(Cn,arguments)}),hc=mr,fc=qt,ad=function(s){if(hc(s)==="Function")return fc(s)},nd={},od={},dd={}.propertyIsEnumerable,ud=Object.getOwnPropertyDescriptor,pc=ud&&!dd.call({1:2},1);od.f=pc?function(e){var t=ud(this,e);return!!t&&t.enumerable}:dd;var mc=wi,gc=jt,vc=od,Sc=br,bc=Es,yc=tn,Tc=Wt,Ec=jo,Mn=Object.getOwnPropertyDescriptor;nd.f=mc?Mn:function(e,t){if(e=bc(e),t=yc(t),Ec)try{return Mn(e,t)}catch(i){}if(Tc(e,t))return Sc(!gc(vc.f,e,t),e[t])};var $c=zt,Ac=ct,wc=/#|\.prototype\./,As=function(s,e){var t=_c[kc(s)];return t==Dc?!0:t==Pc?!1:Ac(e)?$c(e):!!e},kc=As.normalize=function(s){return String(s).replace(wc,".").toLowerCase()},_c=As.data={},Pc=As.NATIVE="N",Dc=As.POLYFILL="P",Rc=As,On=ad,Ic=en,Lc=pr,xc=On(On.bind),ld=function(s,e){return Ic(s),e===void 0?s:Lc?xc(s,e):function(){return s.apply(e,arguments)}},Is=St,Cc=cc,Bc=ad,Mc=ct,Oc=nd.f,Nc=Rc,Li=Ka,Fc=ld,xi=$s,Nn=Wt,Uc=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Cc(s,this,arguments)};return e.prototype=s.prototype,e},yr=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Is:r?Is[t]:(Is[t]||{}).prototype,o=i?Li:Li[t]||xi(Li,t,{})[t],u=o.prototype,d,l,c,h,f,m,S,b,v;for(h in e)d=Nc(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Nn(n,h),m=o[h],l&&(s.dontCallGetSet?(v=Oc(n,h),S=v&&v.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?b=Fc(f,Is):s.wrap&&l?b=Uc(f):a&&Mc(f)?b=Bc(f):b=f,(s.sham||f&&f.sham||m&&m.sham)&&xi(b,"sham",!0),xi(o,h,b),a&&(c=t+"Prototype",Nn(Li,c)||xi(Li,c,{}),xi(Li[c],h,f),s.real&&u&&(d||!u[h])&&xi(u,h,f)))},Ba=wi,Vc=Wt,cd=Function.prototype,Hc=Ba&&Object.getOwnPropertyDescriptor,an=Vc(cd,"name"),Gc=an&&function(){}.name==="something",Yc=an&&(!Ba||Ba&&Hc(cd,"name").configurable),zc={EXISTS:an,PROPER:Gc,CONFIGURABLE:Yc},hd={},qc=Math.ceil,jc=Math.floor,Wc=Math.trunc||function(e){var t=+e;return(t>0?jc:qc)(t)},Qc=Wc,nn=function(s){var e=+s;return e!==e||e===0?0:Qc(e)},Kc=nn,Jc=Math.max,Xc=Math.min,Zc=function(s,e){var t=Kc(s);return t<0?Jc(t+e,0):Xc(t,e)},eh=nn,th=Math.min,ih=function(s){return s>0?th(eh(s),9007199254740991):0},sh=ih,on=function(s){return sh(s.length)},rh=Es,ah=Zc,nh=on,Fn=function(s){return function(e,t,i){var r=rh(e),a=nh(r),n=ah(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},oh={includes:Fn(!0),indexOf:Fn(!1)},dh=qt,ta=Wt,uh=Es,lh=oh.indexOf,ch=rn,Un=dh([].push),hh=function(s,e){var t=uh(s),i=0,r=[],a;for(a in t)!ta(ch,a)&&ta(t,a)&&Un(r,a);for(;e.length>i;)ta(t,a=e[i++])&&(~lh(r,a)||Un(r,a));return r},fd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],fh=hh,ph=fd,mh=Object.keys||function(e){return fh(e,ph)},gh=wi,vh=Wo,Sh=Qi,bh=ki,yh=Es,Th=mh;hd.f=gh&&!vh?Object.defineProperties:function(e,t){bh(e);for(var i=yh(t),r=Th(t),a=r.length,n=0,o;a>n;)Sh.f(e,o=r[n++],i[o]);return e};var Eh=Ja,$h=Eh("document","documentElement"),Ah=ki,wh=hd,Vn=fd,kh=rn,_h=$h,Ph=qo,Dh=sn,Hn=">",Gn="<",Ma="prototype",Oa="script",pd=Dh("IE_PROTO"),ia=function(){},md=function(s){return Gn+Oa+Hn+s+Gn+"/"+Oa+Hn},Yn=function(s){s.write(md("")),s.close();var e=s.parentWindow.Object;return s=null,e},Rh=function(){var s=Ph("iframe"),e="java"+Oa+":",t;return s.style.display="none",_h.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Ls,js=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}js=typeof document!="undefined"?document.domain&&Ls?Yn(Ls):Rh():Yn(Ls);for(var s=Vn.length;s--;)delete js[Ma][Vn[s]];return js()};kh[pd]=!0;var gd=Object.create||function(e,t){var i;return e!==null?(ia[Ma]=Ah(e),i=new ia,ia[Ma]=null,i[pd]=e):i=js(),t===void 0?i:wh.f(i,t)},Ih=zt,Lh=!Ih(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),xh=Wt,Ch=ct,Bh=Sr,Mh=sn,Oh=Lh,zn=Mh("IE_PROTO"),Na=Object,Nh=Na.prototype,vd=Oh?Na.getPrototypeOf:function(s){var e=Bh(s);if(xh(e,zn))return e[zn];var t=e.constructor;return Ch(t)&&e instanceof t?t.prototype:e instanceof Na?Nh:null},Fh=$s,Sd=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Fh(s,e,t),s},Uh=zt,Vh=ct,Hh=Ai,Gh=gd,qn=vd,Yh=Sd,zh=bt,Fa=zh("iterator"),bd=!1,Ht,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=qn(qn(ra)),sa!==Object.prototype&&(Ht=sa)):bd=!0);var qh=!Hh(Ht)||Uh(function(){var s={};return Ht[Fa].call(s)!==s});qh?Ht={}:Ht=Gh(Ht);Vh(Ht[Fa])||Yh(Ht,Fa,function(){return this});var yd={IteratorPrototype:Ht,BUGGY_SAFARI_ITERATORS:bd},jh=bt,Wh=jh("toStringTag"),Td={};Td[Wh]="z";var dn=String(Td)==="[object z]",Qh=dn,Kh=ct,Ws=mr,Jh=bt,Xh=Jh("toStringTag"),Zh=Object,ef=Ws(function(){return arguments}())=="Arguments",tf=function(s,e){try{return s[e]}catch(t){}},Tr=Qh?Ws:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=tf(e=Zh(s),Xh))=="string"?t:ef?Ws(e):(i=Ws(e))=="Object"&&Kh(e.callee)?"Arguments":i},sf=dn,rf=Tr,af=sf?{}.toString:function(){return"[object "+rf(this)+"]"},nf=dn,of=Qi.f,df=$s,uf=Wt,lf=af,cf=bt,jn=cf("toStringTag"),Ed=function(s,e,t,i){if(s){var r=t?s:s.prototype;uf(r,jn)||of(r,jn,{configurable:!0,value:e}),i&&!nf&&df(r,"toString",lf)}},hf=yd.IteratorPrototype,ff=gd,pf=br,mf=Ed,gf=Wi,vf=function(){return this},Sf=function(s,e,t,i){var r=e+" Iterator";return s.prototype=ff(hf,{next:pf(+!i,t)}),mf(s,r,!1,!0),gf[r]=vf,s},bf=yr,yf=jt,$d=zc,Tf=Sf,Ef=vd,$f=Ed,Wn=Sd,Af=bt,Qn=Wi,Ad=yd,wf=$d.PROPER;$d.CONFIGURABLE;Ad.IteratorPrototype;var xs=Ad.BUGGY_SAFARI_ITERATORS,aa=Af("iterator"),Kn="keys",Cs="values",Jn="entries",kf=function(){return this},_f=function(s,e,t,i,r,a,n){Tf(t,e,i);var o=function(v){if(v===r&&h)return h;if(!xs&&v in l)return l[v];switch(v){case Kn:return function(){return new t(this,v)};case Cs:return function(){return new t(this,v)};case Jn:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[aa]||l["@@iterator"]||r&&l[r],h=!xs&&c||o(r),f=e=="Array"&&l.entries||c,m,S,b;if(f&&(m=Ef(f.call(new s)),m!==Object.prototype&&m.next&&($f(m,u,!0,!0),Qn[u]=kf)),wf&&r==Cs&&c&&c.name!==Cs&&(d=!0,h=function(){return yf(c,this)}),r)if(S={values:o(Cs),keys:a?h:o(Kn),entries:o(Jn)},n)for(b in S)(xs||d||!(b in l))&&Wn(l,b,S[b]);else bf({target:e,proto:!0,forced:xs||d},S);return n&&l[aa]!==h&&Wn(l,aa,h,{name:r}),Qn[e]=h,S},Pf=function(s,e){return{value:s,done:e}},Df=Es,Xn=Wi,wd=uc;Qi.f;var Rf=_f,Bs=Pf,kd="Array Iterator",If=wd.set,Lf=wd.getterFor(kd);Rf(Array,"Array",function(s,e){If(this,{type:kd,target:Df(s),index:0,kind:e})},function(){var s=Lf(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Bs(void 0,!0)):t=="keys"?Bs(i,!1):t=="values"?Bs(e[i],!1):Bs([i,e[i]],!1)},"values");Xn.Arguments=Xn.Array;var xf=bt,Cf=Wi,Bf=xf("iterator"),Mf=Array.prototype,Of=function(s){return s!==void 0&&(Cf.Array===s||Mf[Bf]===s)},Nf=Tr,Zn=vr,Ff=gr,Uf=Wi,Vf=bt,Hf=Vf("iterator"),_d=function(s){if(!Ff(s))return Zn(s,Hf)||Zn(s,"@@iterator")||Uf[Nf(s)]},Gf=jt,Yf=en,zf=ki,qf=Za,jf=_d,Wf=TypeError,Qf=function(s,e){var t=arguments.length<2?jf(s):e;if(Yf(t))return zf(Gf(t,s));throw Wf(qf(s)+" is not iterable")},Kf=jt,eo=ki,Jf=vr,Xf=function(s,e,t){var i,r;eo(s);try{if(i=Jf(s,"return"),!i){if(e==="throw")throw t;return t}i=Kf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return eo(i),t},Zf=ld,ep=jt,tp=ki,ip=Za,sp=Of,rp=on,to=Xa,ap=Qf,np=_d,io=Xf,op=TypeError,Qs=function(s,e){this.stopped=s,this.result=e},so=Qs.prototype,dp=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zf(e,i),d,l,c,h,f,m,S,b=function(y){return d&&io(d,"normal",y),new Qs(!0,y)},v=function(y){return r?(tp(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=np(s),!l)throw op(ip(s)+" is not iterable");if(sp(l)){for(c=0,h=rp(s);h>c;c++)if(f=v(s[c]),f&&to(so,f))return f;return new Qs(!1)}d=ap(s,l)}for(m=a?s.next:d.next;!(S=ep(m,d)).done;){try{f=v(S.value)}catch(y){io(d,"throw",y)}if(typeof f=="object"&&f&&to(so,f))return f}return new Qs(!1)},up=tn,lp=Qi,cp=br,hp=function(s,e,t){var i=up(e);i in s?lp.f(s,i,cp(0,t)):s[i]=t},fp=yr,pp=dp,mp=hp;fp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pp(e,function(i,r){mp(t,i,r)},{AS_ENTRIES:!0}),t}});var gp=Ka,vp=gp.Object.fromEntries,Sp={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},bp=Sp,yp=St,Tp=Tr,Ep=$s,ro=Wi,$p=bt,ao=$p("toStringTag");for(var na in bp){var no=yp[na],oa=no&&no.prototype;oa&&Tp(oa)!==ao&&Ep(oa,ao,na),ro[na]=ro.Array}var Ap=vp,wp=Ap,kp=wp,_p=kp,Ei=Wa(_p),Se;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Se||(Se={}));var He=(s,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:z(t)}return s};const er=(s,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:z(e)}};var I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class he{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||D(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pp=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return z(s)}};var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const Dp=5,Rp=5,Ip=500,oo=7e3;class Lp{constructor(e){this.subscription=new ue,this.loadMediaTimeoutSubscription=new ue,this.videoState=new he(X.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===ee.Requested&&i!==X.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case X.PLAYING:case X.PAUSED:case X.READY:break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PLAYING:{switch(i){case X.PLAYING:break;case X.PAUSED:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.READY:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PAUSED:{switch(i){case X.PLAYING:this.videoState.startTransitionTo(X.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case X.PAUSED:break;case X.READY:this.videoState.startTransitionTo(X.PAUSED),this.videoState.setState(X.PAUSED);break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}default:z(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pp(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 ue;this.subscription.add(e),this.subscription.add(H(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 C;e.add(r.pipe(st(Ip)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===ee.Applying||Math.abs(o-a)>Dp)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Rp&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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:z(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ee.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PAUSED||e===X.PLAYING)&&(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PLAYING||e===X.PAUSED)&&(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===X.READY&&this.videoState.setState(X.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==X.STOPPED&&this.videoState.setState(X.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];P(l);const c=ru(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(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 D(u)&&(o.metadata.title=u),D(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ee.Applying||i.state===ee.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(au(oo).subscribe(()=>a(`timeout(${oo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ee.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:R.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var xp=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Cp=s=>{const e=new T(1/0),t=new C,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,S;const b=Ei(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const g=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:g*1e3)!==null&&f!==void 0?f:NaN;D($)&&!isNaN($)&&e.next($)}const v=(m=b["x-delivery-type"])!==null&&m!==void 0?m:Ss.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(v),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),m(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ii=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Bp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),Mp=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const vt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=j(r),d=new ue;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},ri=(s,e,t)=>vt(e,()=>s.loop,i=>{D(i)&&(s.loop=i)},{onError:t}),Dt=(s,e,t,i)=>vt(e,()=>({muted:s.muted,volume:s.volume}),r=>{D(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Qt=(s,e,t,i)=>vt(e,()=>s.playbackRate,r=>{D(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Op=s=>["__",s.language,s.label].join("|"),Np=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class yt{constructor(){this.available$=new C,this.current$=new T(void 0),this.error$=new C,this.subscription=new ue,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(vt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{D(a)&&this.setInternal(a)},{equal:(a,n)=>D(a)&&D(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(vt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{D(a)&&this.setExternal(a)},{equal:(a,n)=>D(a)&&D(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(vt(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(vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(H(U(e,"addtrack"),U(e,"removetrack"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(U(e,"change"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;D(t.align)&&(r.align=t.align),D(t.position)&&(r.position=t.position),D(t.size)&&(r.size=t.size),D(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(yt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Op(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(j(e)||!Np(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const un=s=>{s.removeAttribute("src"),s.load()},Fp=s=>{try{s.pause(),s.playbackRate=0,un(s),s.remove()}catch(e){console.error(e)}};class Up{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ua=window.WeakMap?new WeakMap:new Up,Rt=s=>{let e=s.querySelector("video");const t=!!e;return e?un(e):(e=document.createElement("video"),s.appendChild(e)),Ua.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=s=>{const e=Ua.get(s);Ua.delete(s),e?un(s):Fp(s)};class ws{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 Pd=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},uo=s=>{const e=Pd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Vp=s=>{const e=Pd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Va=3;class Hp{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Va&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Va))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Dd=(s,e,t=Va)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Lt=s=>{const e=g=>U(s,g).pipe(Hi(void 0)),i=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>U(s,g))).pipe(_(g=>g.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=H(U(s,"progress"),U(s,"timeupdate")).pipe(_(()=>Dd(s.buffered,s.currentTime))),n=hr().browser===ja.Safari?Le({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(Hi(void 0)):e("playing"),o=U(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),u=U(s,"ratechange").pipe(_(()=>s.playbackRate)),d=U(s,"error").pipe(ae(()=>!!(s.error||s.played.length)),_(()=>{var g;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(g=s.error)!==null&&g!==void 0?g:void 0}})),l=U(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new C,h=.3;let f;l.subscribe(g=>{s.loop&&D(f)&&D(g)&&f>=s.duration-h&&g<=h&&c.next(f),f=g});const m=U(s,"enterpictureinpicture"),S=U(s,"leavepictureinpicture"),b=new T(Vp(s));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const v=new T(uo(s));return U(s,"fullscreenchange").pipe(_(()=>uo(s))).subscribe(v),{playing$:n,pause$:e("pause").pipe(ae(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(s,"durationchange").pipe(_(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:v}},Er=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Gp=yr,Yp=Sr,zp=on,qp=nn;Gp({target:"Array",proto:!0},{at:function(e){var t=Yp(this),i=zp(t),r=qp(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var jp=Ja,Rd=jp,Wp=Rd,Qp=Wp("Array","at"),Kp=Qp,Jp=Kp,Xp=Jp,Zp=Xp,Ie=Wa(Zp);let ln=!1,Vt={};const em=s=>{ln=s},tm=()=>{Vt={}},im=s=>{s(Vt)},Ms=(s,e)=>{var t;ln&&(Vt.meta=(t=Vt.meta)!==null&&t!==void 0?t:{},Vt.meta[s]=e)};class wt{constructor(e){this.name=e}next(e){var t,i;if(!ln)return;Vt.series=(t=Vt.series)!==null&&t!==void 0?t:{};const r=(i=Vt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Vt.series[this.name]=r}}var vi;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(vi||(vi={}));const sm=new wt("best_bitrate"),rm=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Id{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const am='Assertion "ABR Tracks is empty array" failed',_i=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,S,b;nu(s,am);const v=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},g=y&&si(y),E=i.considerPlaybackRate&&D(o)?o:1,$=s.filter(O=>!yi(O.quality)).sort((O,x)=>Vi(O.quality,x.quality)?-1:1),L=(f=Ie($,-1))===null||f===void 0?void 0:f.quality,G=(m=Ie($,0))===null||m===void 0?void 0:m.quality,Q=j(r)||D(r.min)&&D(r.max)&&qs(r.max,r.min)||D(r.min)&&G&&Vi(r.min,G)||D(r.max)&&L&&qs(r.max,L),V=E*rm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(O=>(g?qs(O.quality,g):!0)?(D(t)&&isFinite(t)&&D(O.bitrate)?t-a>=O.bitrate*V:!0)?i.lazyQualitySwitch&&D(i.minBufferToSwitchUp)&&u&&!yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Vi(O.quality,u.quality)?(q[O.quality]=vi.Buffer,!1):!!l&&Ra(O.quality,l)?(q[O.quality]=vi.DroppedFramesLimit,!1):Q||(j(r.max)||Fo(O.quality,r.max))&&(j(r.min)||Ra(O.quality,r.min))?!0:(q[O.quality]=vi.FitsQualityLimits,!1):(q[O.quality]=vi.FitsThroughput,!1):(q[O.quality]=vi.FitsContainer,!1))[0];B&&B.bitrate&&sm.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
6
+ import{ValueSubject as T,Subject as C,Subscription as ue,isNonNullable as D,ErrorCategory as R,isNullable as j,fromEvent as U,assertNever as z,merge as H,tap as vs,map as _,observableFrom as Ge,filterChanged as ve,assertNonNullable as P,debounce as st,getHighestQuality as ru,timeout as au,getCurrentBrowser as hr,CurrentClientBrowser as ja,combine as Le,once as Ae,mapTo as Hi,filter as ae,now as le,assertNotEmptyArray as nu,videoSizeToQuality as si,isInvariantQuality as yi,isHigher as Vi,isLower as qs,isHigherOrEqual as Ra,isLowerOrEqual as Fo,Observable as fr,debounceFn as ou,interval as Ti,VideoQuality as at,videoQualityToHeight as du,abortable as ce,getExponentialDelay as ms,throttle as uu,isIOS as lu,CurrentClientDevice as cu,safeStorage as Fr,fillWithDefault as hu,Logger as fu}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as lb,Subject as cb,Subscription as hb,ValueSubject as fb,VideoQuality as pb}from"@vkontakte/videoplayer-shared/es2018.esm.js";const pu="2.0.98-dev.97d8def3.0";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Ue;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ue||(Ue={}));var Ce;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ce||(Ce={}));var Ss;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ss||(Ss={}));var ee;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ee||(ee={}));var Zt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(Zt||(Zt={}));var mu=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class gu{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ce.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new T(Ce.NOT_AVAILABLE),this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=D((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||mu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();j(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();j(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(U(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return z(r.sessionState)}})).add(H(U(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),Ge([i.getCastState()])).pipe(ve(),_(vu),vs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ce.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(j(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===Ce.CONNECTED?D(this.connection$.getValue())?Ce.CONNECTED:Ce.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const vu=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ce.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ce.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ce.CONNECTING;case cast.framework.CastState.CONNECTED:return Ce.CONNECTED;default:return z(s)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var zt=function(s){try{return!!s()}catch(e){return!0}},Su=zt,pr=!Su(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Uo=pr,Vo=Function.prototype,Ia=Vo.call,bu=Uo&&Vo.bind.bind(Ia,Ia),qt=Uo?bu:function(s){return function(){return Ia.apply(s,arguments)}},Ho=qt,yu=Ho({}.toString),Tu=Ho("".slice),mr=function(s){return Tu(yu(s),8,-1)},Eu=qt,$u=zt,Au=mr,Vr=Object,wu=Eu("".split),ku=$u(function(){return!Vr("z").propertyIsEnumerable(0)})?function(s){return Au(s)=="String"?wu(s,""):Vr(s)}:Vr,gr=function(s){return s==null},_u=gr,Pu=TypeError,Qa=function(s){if(_u(s))throw Pu("Can't call method on "+s);return s},Du=ku,Ru=Qa,Es=function(s){return Du(Ru(s))},Wi={},Ps=function(s){return s&&s.Math==Math&&s},St=Ps(typeof globalThis=="object"&&globalThis)||Ps(typeof window=="object"&&window)||Ps(typeof self=="object"&&self)||Ps(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),La=typeof document=="object"&&document.all,Iu=typeof La=="undefined"&&La!==void 0,Go={all:La,IS_HTMLDDA:Iu},Yo=Go,Lu=Yo.all,ct=Yo.IS_HTMLDDA?function(s){return typeof s=="function"||s===Lu}:function(s){return typeof s=="function"},xu=St,Cu=ct,gn=xu.WeakMap,Bu=Cu(gn)&&/native code/.test(String(gn)),vn=ct,zo=Go,Mu=zo.all,Ai=zo.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:vn(s)||s===Mu}:function(s){return typeof s=="object"?s!==null:vn(s)},Ou=zt,wi=!Ou(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Qi={},Nu=St,Sn=Ai,xa=Nu.document,Fu=Sn(xa)&&Sn(xa.createElement),qo=function(s){return Fu?xa.createElement(s):{}},Uu=wi,Vu=zt,Hu=qo,jo=!Uu&&!Vu(function(){return Object.defineProperty(Hu("div"),"a",{get:function(){return 7}}).a!=7}),Gu=wi,Yu=zt,Wo=Gu&&Yu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),zu=Ai,qu=String,ju=TypeError,ki=function(s){if(zu(s))return s;throw ju(qu(s)+" is not an object")},Wu=pr,Ds=Function.prototype.call,jt=Wu?Ds.bind(Ds):function(){return Ds.apply(Ds,arguments)},Ka={},Hr=Ka,Gr=St,Qu=ct,bn=function(s){return Qu(s)?s:void 0},Ja=function(s,e){return arguments.length<2?bn(Hr[s])||bn(Gr[s]):Hr[s]&&Hr[s][e]||Gr[s]&&Gr[s][e]},Ku=qt,Xa=Ku({}.isPrototypeOf),Ju=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Qo=St,Yr=Ju,yn=Qo.process,Tn=Qo.Deno,En=yn&&yn.versions||Tn&&Tn.version,$n=En&&En.v8,gt,Js;$n&&(gt=$n.split("."),Js=gt[0]>0&&gt[0]<4?1:+(gt[0]+gt[1]));!Js&&Yr&&(gt=Yr.match(/Edge\/(\d+)/),(!gt||gt[1]>=74)&&(gt=Yr.match(/Chrome\/(\d+)/),gt&&(Js=+gt[1])));var Xu=Js,An=Xu,Zu=zt,el=St,tl=el.String,Ko=!!Object.getOwnPropertySymbols&&!Zu(function(){var s=Symbol();return!tl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&An&&An<41}),il=Ko,Jo=il&&!Symbol.sham&&typeof Symbol.iterator=="symbol",sl=Ja,rl=ct,al=Xa,nl=Jo,ol=Object,Xo=nl?function(s){return typeof s=="symbol"}:function(s){var e=sl("Symbol");return rl(e)&&al(e.prototype,ol(s))},dl=String,Za=function(s){try{return dl(s)}catch(e){return"Object"}},ul=ct,ll=Za,cl=TypeError,en=function(s){if(ul(s))return s;throw cl(ll(s)+" is not a function")},hl=en,fl=gr,vr=function(s,e){var t=s[e];return fl(t)?void 0:hl(t)},zr=jt,qr=ct,jr=Ai,pl=TypeError,ml=function(s,e){var t,i;if(e==="string"&&qr(t=s.toString)&&!jr(i=zr(t,s))||qr(t=s.valueOf)&&!jr(i=zr(t,s))||e!=="string"&&qr(t=s.toString)&&!jr(i=zr(t,s)))return i;throw pl("Can't convert object to primitive value")},Zo={exports:{}},wn=St,gl=Object.defineProperty,vl=function(s,e){try{gl(wn,s,{value:e,configurable:!0,writable:!0})}catch(t){wn[s]=e}return e},Sl=St,bl=vl,kn="__core-js_shared__",yl=Sl[kn]||bl(kn,{}),ed=yl,_n=ed;(Zo.exports=function(s,e){return _n[s]||(_n[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var td=Zo.exports,Tl=Qa,El=Object,Sr=function(s){return El(Tl(s))},$l=qt,Al=Sr,wl=$l({}.hasOwnProperty),Wt=Object.hasOwn||function(e,t){return wl(Al(e),t)},kl=qt,_l=0,Pl=Math.random(),Dl=kl(1 .toString),id=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Dl(++_l+Pl,36)},Rl=St,Il=td,Pn=Wt,Ll=id,xl=Ko,Cl=Jo,Ni=Rl.Symbol,Wr=Il("wks"),Bl=Cl?Ni.for||Ni:Ni&&Ni.withoutSetter||Ll,bt=function(s){return Pn(Wr,s)||(Wr[s]=xl&&Pn(Ni,s)?Ni[s]:Bl("Symbol."+s)),Wr[s]},Ml=jt,Dn=Ai,Rn=Xo,Ol=vr,Nl=ml,Fl=bt,Ul=TypeError,Vl=Fl("toPrimitive"),Hl=function(s,e){if(!Dn(s)||Rn(s))return s;var t=Ol(s,Vl),i;if(t){if(e===void 0&&(e="default"),i=Ml(t,s,e),!Dn(i)||Rn(i))return i;throw Ul("Can't convert object to primitive value")}return e===void 0&&(e="number"),Nl(s,e)},Gl=Hl,Yl=Xo,tn=function(s){var e=Gl(s,"string");return Yl(e)?e:e+""},zl=wi,ql=jo,jl=Wo,Rs=ki,In=tn,Wl=TypeError,Qr=Object.defineProperty,Ql=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";Qi.f=zl?jl?function(e,t,i){if(Rs(e),t=In(t),Rs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=Ql(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(Rs(e),t=In(t),Rs(i),ql)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Wl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var br=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Kl=wi,Jl=Qi,Xl=br,$s=Kl?function(s,e,t){return Jl.f(s,e,Xl(1,t))}:function(s,e,t){return s[e]=t,s},Zl=td,ec=id,Ln=Zl("keys"),sn=function(s){return Ln[s]||(Ln[s]=ec(s))},rn={},tc=Bu,sd=St,ic=Ai,sc=$s,Zr=Wt,ea=ed,rc=sn,ac=rn,xn="Object already initialized",Ca=sd.TypeError,nc=sd.WeakMap,Xs,bs,Zs,oc=function(s){return Zs(s)?bs(s):Xs(s,{})},dc=function(s){return function(e){var t;if(!ic(e)||(t=bs(e)).type!==s)throw Ca("Incompatible receiver, "+s+" required");return t}};if(tc||ea.state){var Et=ea.state||(ea.state=new nc);Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Xs=function(s,e){if(Et.has(s))throw Ca(xn);return e.facade=s,Et.set(s,e),e},bs=function(s){return Et.get(s)||{}},Zs=function(s){return Et.has(s)}}else{var Ii=rc("state");ac[Ii]=!0,Xs=function(s,e){if(Zr(s,Ii))throw Ca(xn);return e.facade=s,sc(s,Ii,e),e},bs=function(s){return Zr(s,Ii)?s[Ii]:{}},Zs=function(s){return Zr(s,Ii)}}var uc={set:Xs,get:bs,has:Zs,enforce:oc,getterFor:dc},lc=pr,rd=Function.prototype,Cn=rd.apply,Bn=rd.call,cc=typeof Reflect=="object"&&Reflect.apply||(lc?Bn.bind(Cn):function(){return Bn.apply(Cn,arguments)}),hc=mr,fc=qt,ad=function(s){if(hc(s)==="Function")return fc(s)},nd={},od={},dd={}.propertyIsEnumerable,ud=Object.getOwnPropertyDescriptor,pc=ud&&!dd.call({1:2},1);od.f=pc?function(e){var t=ud(this,e);return!!t&&t.enumerable}:dd;var mc=wi,gc=jt,vc=od,Sc=br,bc=Es,yc=tn,Tc=Wt,Ec=jo,Mn=Object.getOwnPropertyDescriptor;nd.f=mc?Mn:function(e,t){if(e=bc(e),t=yc(t),Ec)try{return Mn(e,t)}catch(i){}if(Tc(e,t))return Sc(!gc(vc.f,e,t),e[t])};var $c=zt,Ac=ct,wc=/#|\.prototype\./,As=function(s,e){var t=_c[kc(s)];return t==Dc?!0:t==Pc?!1:Ac(e)?$c(e):!!e},kc=As.normalize=function(s){return String(s).replace(wc,".").toLowerCase()},_c=As.data={},Pc=As.NATIVE="N",Dc=As.POLYFILL="P",Rc=As,On=ad,Ic=en,Lc=pr,xc=On(On.bind),ld=function(s,e){return Ic(s),e===void 0?s:Lc?xc(s,e):function(){return s.apply(e,arguments)}},Is=St,Cc=cc,Bc=ad,Mc=ct,Oc=nd.f,Nc=Rc,Li=Ka,Fc=ld,xi=$s,Nn=Wt,Uc=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Cc(s,this,arguments)};return e.prototype=s.prototype,e},yr=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Is:r?Is[t]:(Is[t]||{}).prototype,o=i?Li:Li[t]||xi(Li,t,{})[t],u=o.prototype,d,l,c,h,f,m,S,b,v;for(h in e)d=Nc(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Nn(n,h),m=o[h],l&&(s.dontCallGetSet?(v=Oc(n,h),S=v&&v.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?b=Fc(f,Is):s.wrap&&l?b=Uc(f):a&&Mc(f)?b=Bc(f):b=f,(s.sham||f&&f.sham||m&&m.sham)&&xi(b,"sham",!0),xi(o,h,b),a&&(c=t+"Prototype",Nn(Li,c)||xi(Li,c,{}),xi(Li[c],h,f),s.real&&u&&(d||!u[h])&&xi(u,h,f)))},Ba=wi,Vc=Wt,cd=Function.prototype,Hc=Ba&&Object.getOwnPropertyDescriptor,an=Vc(cd,"name"),Gc=an&&function(){}.name==="something",Yc=an&&(!Ba||Ba&&Hc(cd,"name").configurable),zc={EXISTS:an,PROPER:Gc,CONFIGURABLE:Yc},hd={},qc=Math.ceil,jc=Math.floor,Wc=Math.trunc||function(e){var t=+e;return(t>0?jc:qc)(t)},Qc=Wc,nn=function(s){var e=+s;return e!==e||e===0?0:Qc(e)},Kc=nn,Jc=Math.max,Xc=Math.min,Zc=function(s,e){var t=Kc(s);return t<0?Jc(t+e,0):Xc(t,e)},eh=nn,th=Math.min,ih=function(s){return s>0?th(eh(s),9007199254740991):0},sh=ih,on=function(s){return sh(s.length)},rh=Es,ah=Zc,nh=on,Fn=function(s){return function(e,t,i){var r=rh(e),a=nh(r),n=ah(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},oh={includes:Fn(!0),indexOf:Fn(!1)},dh=qt,ta=Wt,uh=Es,lh=oh.indexOf,ch=rn,Un=dh([].push),hh=function(s,e){var t=uh(s),i=0,r=[],a;for(a in t)!ta(ch,a)&&ta(t,a)&&Un(r,a);for(;e.length>i;)ta(t,a=e[i++])&&(~lh(r,a)||Un(r,a));return r},fd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],fh=hh,ph=fd,mh=Object.keys||function(e){return fh(e,ph)},gh=wi,vh=Wo,Sh=Qi,bh=ki,yh=Es,Th=mh;hd.f=gh&&!vh?Object.defineProperties:function(e,t){bh(e);for(var i=yh(t),r=Th(t),a=r.length,n=0,o;a>n;)Sh.f(e,o=r[n++],i[o]);return e};var Eh=Ja,$h=Eh("document","documentElement"),Ah=ki,wh=hd,Vn=fd,kh=rn,_h=$h,Ph=qo,Dh=sn,Hn=">",Gn="<",Ma="prototype",Oa="script",pd=Dh("IE_PROTO"),ia=function(){},md=function(s){return Gn+Oa+Hn+s+Gn+"/"+Oa+Hn},Yn=function(s){s.write(md("")),s.close();var e=s.parentWindow.Object;return s=null,e},Rh=function(){var s=Ph("iframe"),e="java"+Oa+":",t;return s.style.display="none",_h.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Ls,js=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}js=typeof document!="undefined"?document.domain&&Ls?Yn(Ls):Rh():Yn(Ls);for(var s=Vn.length;s--;)delete js[Ma][Vn[s]];return js()};kh[pd]=!0;var gd=Object.create||function(e,t){var i;return e!==null?(ia[Ma]=Ah(e),i=new ia,ia[Ma]=null,i[pd]=e):i=js(),t===void 0?i:wh.f(i,t)},Ih=zt,Lh=!Ih(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),xh=Wt,Ch=ct,Bh=Sr,Mh=sn,Oh=Lh,zn=Mh("IE_PROTO"),Na=Object,Nh=Na.prototype,vd=Oh?Na.getPrototypeOf:function(s){var e=Bh(s);if(xh(e,zn))return e[zn];var t=e.constructor;return Ch(t)&&e instanceof t?t.prototype:e instanceof Na?Nh:null},Fh=$s,Sd=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Fh(s,e,t),s},Uh=zt,Vh=ct,Hh=Ai,Gh=gd,qn=vd,Yh=Sd,zh=bt,Fa=zh("iterator"),bd=!1,Ht,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=qn(qn(ra)),sa!==Object.prototype&&(Ht=sa)):bd=!0);var qh=!Hh(Ht)||Uh(function(){var s={};return Ht[Fa].call(s)!==s});qh?Ht={}:Ht=Gh(Ht);Vh(Ht[Fa])||Yh(Ht,Fa,function(){return this});var yd={IteratorPrototype:Ht,BUGGY_SAFARI_ITERATORS:bd},jh=bt,Wh=jh("toStringTag"),Td={};Td[Wh]="z";var dn=String(Td)==="[object z]",Qh=dn,Kh=ct,Ws=mr,Jh=bt,Xh=Jh("toStringTag"),Zh=Object,ef=Ws(function(){return arguments}())=="Arguments",tf=function(s,e){try{return s[e]}catch(t){}},Tr=Qh?Ws:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=tf(e=Zh(s),Xh))=="string"?t:ef?Ws(e):(i=Ws(e))=="Object"&&Kh(e.callee)?"Arguments":i},sf=dn,rf=Tr,af=sf?{}.toString:function(){return"[object "+rf(this)+"]"},nf=dn,of=Qi.f,df=$s,uf=Wt,lf=af,cf=bt,jn=cf("toStringTag"),Ed=function(s,e,t,i){if(s){var r=t?s:s.prototype;uf(r,jn)||of(r,jn,{configurable:!0,value:e}),i&&!nf&&df(r,"toString",lf)}},hf=yd.IteratorPrototype,ff=gd,pf=br,mf=Ed,gf=Wi,vf=function(){return this},Sf=function(s,e,t,i){var r=e+" Iterator";return s.prototype=ff(hf,{next:pf(+!i,t)}),mf(s,r,!1,!0),gf[r]=vf,s},bf=yr,yf=jt,$d=zc,Tf=Sf,Ef=vd,$f=Ed,Wn=Sd,Af=bt,Qn=Wi,Ad=yd,wf=$d.PROPER;$d.CONFIGURABLE;Ad.IteratorPrototype;var xs=Ad.BUGGY_SAFARI_ITERATORS,aa=Af("iterator"),Kn="keys",Cs="values",Jn="entries",kf=function(){return this},_f=function(s,e,t,i,r,a,n){Tf(t,e,i);var o=function(v){if(v===r&&h)return h;if(!xs&&v in l)return l[v];switch(v){case Kn:return function(){return new t(this,v)};case Cs:return function(){return new t(this,v)};case Jn:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[aa]||l["@@iterator"]||r&&l[r],h=!xs&&c||o(r),f=e=="Array"&&l.entries||c,m,S,b;if(f&&(m=Ef(f.call(new s)),m!==Object.prototype&&m.next&&($f(m,u,!0,!0),Qn[u]=kf)),wf&&r==Cs&&c&&c.name!==Cs&&(d=!0,h=function(){return yf(c,this)}),r)if(S={values:o(Cs),keys:a?h:o(Kn),entries:o(Jn)},n)for(b in S)(xs||d||!(b in l))&&Wn(l,b,S[b]);else bf({target:e,proto:!0,forced:xs||d},S);return n&&l[aa]!==h&&Wn(l,aa,h,{name:r}),Qn[e]=h,S},Pf=function(s,e){return{value:s,done:e}},Df=Es,Xn=Wi,wd=uc;Qi.f;var Rf=_f,Bs=Pf,kd="Array Iterator",If=wd.set,Lf=wd.getterFor(kd);Rf(Array,"Array",function(s,e){If(this,{type:kd,target:Df(s),index:0,kind:e})},function(){var s=Lf(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Bs(void 0,!0)):t=="keys"?Bs(i,!1):t=="values"?Bs(e[i],!1):Bs([i,e[i]],!1)},"values");Xn.Arguments=Xn.Array;var xf=bt,Cf=Wi,Bf=xf("iterator"),Mf=Array.prototype,Of=function(s){return s!==void 0&&(Cf.Array===s||Mf[Bf]===s)},Nf=Tr,Zn=vr,Ff=gr,Uf=Wi,Vf=bt,Hf=Vf("iterator"),_d=function(s){if(!Ff(s))return Zn(s,Hf)||Zn(s,"@@iterator")||Uf[Nf(s)]},Gf=jt,Yf=en,zf=ki,qf=Za,jf=_d,Wf=TypeError,Qf=function(s,e){var t=arguments.length<2?jf(s):e;if(Yf(t))return zf(Gf(t,s));throw Wf(qf(s)+" is not iterable")},Kf=jt,eo=ki,Jf=vr,Xf=function(s,e,t){var i,r;eo(s);try{if(i=Jf(s,"return"),!i){if(e==="throw")throw t;return t}i=Kf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return eo(i),t},Zf=ld,ep=jt,tp=ki,ip=Za,sp=Of,rp=on,to=Xa,ap=Qf,np=_d,io=Xf,op=TypeError,Qs=function(s,e){this.stopped=s,this.result=e},so=Qs.prototype,dp=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zf(e,i),d,l,c,h,f,m,S,b=function(y){return d&&io(d,"normal",y),new Qs(!0,y)},v=function(y){return r?(tp(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=np(s),!l)throw op(ip(s)+" is not iterable");if(sp(l)){for(c=0,h=rp(s);h>c;c++)if(f=v(s[c]),f&&to(so,f))return f;return new Qs(!1)}d=ap(s,l)}for(m=a?s.next:d.next;!(S=ep(m,d)).done;){try{f=v(S.value)}catch(y){io(d,"throw",y)}if(typeof f=="object"&&f&&to(so,f))return f}return new Qs(!1)},up=tn,lp=Qi,cp=br,hp=function(s,e,t){var i=up(e);i in s?lp.f(s,i,cp(0,t)):s[i]=t},fp=yr,pp=dp,mp=hp;fp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pp(e,function(i,r){mp(t,i,r)},{AS_ENTRIES:!0}),t}});var gp=Ka,vp=gp.Object.fromEntries,Sp={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},bp=Sp,yp=St,Tp=Tr,Ep=$s,ro=Wi,$p=bt,ao=$p("toStringTag");for(var na in bp){var no=yp[na],oa=no&&no.prototype;oa&&Tp(oa)!==ao&&Ep(oa,ao,na),ro[na]=ro.Array}var Ap=vp,wp=Ap,kp=wp,_p=kp,Ei=Wa(_p),Se;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Se||(Se={}));var He=(s,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:z(t)}return s};const er=(s,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:z(e)}};var I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class he{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||D(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pp=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return z(s)}};var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const Dp=5,Rp=5,Ip=500,oo=7e3;class Lp{constructor(e){this.subscription=new ue,this.loadMediaTimeoutSubscription=new ue,this.videoState=new he(X.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===ee.Requested&&i!==X.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case X.PLAYING:case X.PAUSED:case X.READY:break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PLAYING:{switch(i){case X.PLAYING:break;case X.PAUSED:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.READY:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PAUSED:{switch(i){case X.PLAYING:this.videoState.startTransitionTo(X.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case X.PAUSED:break;case X.READY:this.videoState.startTransitionTo(X.PAUSED),this.videoState.setState(X.PAUSED);break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}default:z(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pp(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 ue;this.subscription.add(e),this.subscription.add(H(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 C;e.add(r.pipe(st(Ip)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===ee.Applying||Math.abs(o-a)>Dp)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Rp&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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:z(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ee.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PAUSED||e===X.PLAYING)&&(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PLAYING||e===X.PAUSED)&&(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===X.READY&&this.videoState.setState(X.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==X.STOPPED&&this.videoState.setState(X.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];P(l);const c=ru(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(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 D(u)&&(o.metadata.title=u),D(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ee.Applying||i.state===ee.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(au(oo).subscribe(()=>a(`timeout(${oo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ee.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:R.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var xp=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Cp=s=>{const e=new T(1/0),t=new C,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,S;const b=Ei(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const g=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:g*1e3)!==null&&f!==void 0?f:NaN;D($)&&!isNaN($)&&e.next($)}const v=(m=b["x-delivery-type"])!==null&&m!==void 0?m:Ss.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(v),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),m(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ii=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Bp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),Mp=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const vt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=j(r),d=new ue;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},ri=(s,e,t)=>vt(e,()=>s.loop,i=>{D(i)&&(s.loop=i)},{onError:t}),Dt=(s,e,t,i)=>vt(e,()=>({muted:s.muted,volume:s.volume}),r=>{D(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Qt=(s,e,t,i)=>vt(e,()=>s.playbackRate,r=>{D(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Op=s=>["__",s.language,s.label].join("|"),Np=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class yt{constructor(){this.available$=new C,this.current$=new T(void 0),this.error$=new C,this.subscription=new ue,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(vt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{D(a)&&this.setInternal(a)},{equal:(a,n)=>D(a)&&D(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(vt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{D(a)&&this.setExternal(a)},{equal:(a,n)=>D(a)&&D(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(vt(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(vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(H(U(e,"addtrack"),U(e,"removetrack"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(U(e,"change"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;D(t.align)&&(r.align=t.align),D(t.position)&&(r.position=t.position),D(t.size)&&(r.size=t.size),D(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(yt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Op(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(j(e)||!Np(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const un=s=>{s.removeAttribute("src"),s.load()},Fp=s=>{try{s.pause(),s.playbackRate=0,un(s),s.remove()}catch(e){console.error(e)}};class Up{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ua=window.WeakMap?new WeakMap:new Up,Rt=s=>{let e=s.querySelector("video");const t=!!e;return e?un(e):(e=document.createElement("video"),s.appendChild(e)),Ua.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=s=>{const e=Ua.get(s);Ua.delete(s),e?un(s):Fp(s)};class ws{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 Pd=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},uo=s=>{const e=Pd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Vp=s=>{const e=Pd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Va=3;class Hp{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Va&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Va))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Dd=(s,e,t=Va)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Lt=s=>{const e=g=>U(s,g).pipe(Hi(void 0)),i=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>U(s,g))).pipe(_(g=>g.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=H(U(s,"progress"),U(s,"timeupdate")).pipe(_(()=>Dd(s.buffered,s.currentTime))),n=hr().browser===ja.Safari?Le({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(Hi(void 0)):e("playing"),o=U(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),u=U(s,"ratechange").pipe(_(()=>s.playbackRate)),d=U(s,"error").pipe(ae(()=>!!(s.error||s.played.length)),_(()=>{var g;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(g=s.error)!==null&&g!==void 0?g:void 0}})),l=U(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new C,h=.3;let f;l.subscribe(g=>{s.loop&&D(f)&&D(g)&&f>=s.duration-h&&g<=h&&c.next(f),f=g});const m=U(s,"enterpictureinpicture"),S=U(s,"leavepictureinpicture"),b=new T(Vp(s));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const v=new T(uo(s));return U(s,"fullscreenchange").pipe(_(()=>uo(s))).subscribe(v),{playing$:n,pause$:e("pause").pipe(ae(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(s,"durationchange").pipe(_(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:v}},Er=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Gp=yr,Yp=Sr,zp=on,qp=nn;Gp({target:"Array",proto:!0},{at:function(e){var t=Yp(this),i=zp(t),r=qp(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var jp=Ja,Rd=jp,Wp=Rd,Qp=Wp("Array","at"),Kp=Qp,Jp=Kp,Xp=Jp,Zp=Xp,Ie=Wa(Zp);let ln=!1,Vt={};const em=s=>{ln=s},tm=()=>{Vt={}},im=s=>{s(Vt)},Ms=(s,e)=>{var t;ln&&(Vt.meta=(t=Vt.meta)!==null&&t!==void 0?t:{},Vt.meta[s]=e)};class wt{constructor(e){this.name=e}next(e){var t,i;if(!ln)return;Vt.series=(t=Vt.series)!==null&&t!==void 0?t:{};const r=(i=Vt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Vt.series[this.name]=r}}var vi;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(vi||(vi={}));const sm=new wt("best_bitrate"),rm=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Id{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const am='Assertion "ABR Tracks is empty array" failed',_i=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,S,b;nu(s,am);const v=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},g=y&&si(y),E=i.considerPlaybackRate&&D(o)?o:1,$=s.filter(O=>!yi(O.quality)).sort((O,x)=>Vi(O.quality,x.quality)?-1:1),L=(f=Ie($,-1))===null||f===void 0?void 0:f.quality,G=(m=Ie($,0))===null||m===void 0?void 0:m.quality,Q=j(r)||D(r.min)&&D(r.max)&&qs(r.max,r.min)||D(r.min)&&G&&Vi(r.min,G)||D(r.max)&&L&&qs(r.max,L),V=E*rm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(O=>(g?qs(O.quality,g):!0)?(D(t)&&isFinite(t)&&D(O.bitrate)?t-a>=O.bitrate*V:!0)?i.lazyQualitySwitch&&D(i.minBufferToSwitchUp)&&u&&!yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Vi(O.quality,u.quality)?(q[O.quality]=vi.Buffer,!1):!!l&&Ra(O.quality,l)?(q[O.quality]=vi.DroppedFramesLimit,!1):Q||(j(r.max)||Fo(O.quality,r.max))&&(j(r.min)||Ra(O.quality,r.min))?!0:(q[O.quality]=vi.FitsQualityLimits,!1):(q[O.quality]=vi.FitsThroughput,!1):(q[O.quality]=vi.FitsContainer,!1))[0];B&&B.bitrate&&sm.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
7
7
  [available tracks]
8
8
  ${s.map(O=>`{ id: ${O.id}, quality: ${O.quality}, bitrate: ${O.bitrate} }`).join(`
9
9
  `)}
@@ -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 Yd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new rv(this.params.fov,this.params.orientation),this.cameraRotationManager=new av(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(nv,this.gl.VERTEX_SHADER),i=this.createShader(ov,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let zd=class{constructor(e){this.subscription=new ue,this.videoState=new he(Te.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Te.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Te.STOPPED&&(this.videoState.startTransitionTo(Te.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(Te.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Te.STOPPED:this.videoState.startTransitionTo(Te.READY),this.prepare();return;case Te.READY:n===p.PAUSED?(this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Te.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Te.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Te.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Te.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&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(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(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new sv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Te.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Te.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Te.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===nt.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=hg(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=cg(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&fg(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=pg(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===nt.REPRESENTATIOS_READY&&(this.videoState.setState(Te.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==nt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Be.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Be.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,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:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(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),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.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),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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),It(this.video)}},dv=class extends zd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Me;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Me||(Me={}));var At;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(At||(At={}));var dr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(dr||(dr={}));var ut;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(ut||(ut={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var qi;(function(s){s.MP4="mp4",s.WEBM="webm"})(qi||(qi={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var Ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ee||(Ee={}));var fa,pa;let qd=!1;try{qd=hr().browser===ja.Safari&&parseInt((pa=(fa=navigator.userAgent.match(/Version\/(\d+)/))===null||fa===void 0?void 0:fa[1])!==null&&pa!==void 0?pa:"",10)<16}catch(s){console.error(s)}class uv{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;qd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.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:z(t)}}}class ht{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class jd extends ht{}class lv extends ht{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class cv extends ht{parseChildrenBoxes(){return ai(this.content)}}class hv extends ht{parseChildrenBoxes(){return ai(this.content)}}class fv extends ht{constructor(e){super(e),this.data=this.content}}class Jt extends ht{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class pv extends Jt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class mv extends ht{parseChildrenBoxes(){return ai(this.content)}}class gv extends ht{parseChildrenBoxes(){return ai(this.content)}}var bi;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(bi||(bi={}));class vv extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bi.MONOSCOPIC;break;case 1:this.stereoMode=bi.TOP_BOTTOM;break;case 2:this.stereoMode=bi.LEFT_RIGHT;break;case 3:this.stereoMode=bi.STEREO_CUSTOM;break;case 4:this.stereoMode=bi.RIGHT_LEFT;break}this.cursor+=1}}class Sv extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class bv extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class yv extends ht{parseChildrenBoxes(){return ai(this.content)}}class Tv extends Jt{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Ev extends ht{parseChildrenBoxes(){return ai(this.content)}}class $v extends ht{parseChildrenBoxes(){return ai(this.content)}}class Av extends Jt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class wv extends ht{parseChildrenBoxes(){return ai(this.content)}}class kv extends Jt{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class _v extends Jt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Pv extends Jt{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Dv={ftyp:lv,moov:cv,moof:hv,mdat:fv,sidx:pv,trak:mv,mdia:yv,mfhd:Av,tkhd:Tv,traf:wv,tfhd:kv,tfdt:_v,trun:Pv,minf:Ev,sv3d:gv,st3d:vv,prhd:Sv,proj:$v,equi:bv,unknown:jd};class Rv{createBox(e,t){const i=Dv[e];return i?new i(t):new jd(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return wr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const wr=new Rv;function ps(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:wr.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Ga(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ps(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function ai(s){const e=[];let t=0;for(;t<s.byteLength;){const i=wr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Iv=new TextDecoder("ascii"),Lv=s=>Iv.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",xv=s=>{const e=wr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Z.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Cv=s=>{const e=Ga(s,"mdat"),t=Ga(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},Bv=(s,e)=>{const t=Ga(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Mv=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ps(s,"sv3d")){e.is3dVideo=!0;const i=ps(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ps(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ps(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Ov={validateData:Lv,parseInit:Mv,getIndexRange:()=>{},parseSegments:xv,parseFeedableSegmentChunk:Cv,getSegmentEndTime:Bv};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var F;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(F||(F={}));const Eo={[k.EBML]:{type:F.Master},[k.EBMLVersion]:{type:F.UnsignedInteger},[k.EBMLReadVersion]:{type:F.UnsignedInteger},[k.EBMLMaxIDLength]:{type:F.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:F.UnsignedInteger},[k.DocType]:{type:F.String},[k.DocTypeVersion]:{type:F.UnsignedInteger},[k.DocTypeReadVersion]:{type:F.UnsignedInteger},[k.Void]:{type:F.Binary},[k.Segment]:{type:F.Master},[k.SeekHead]:{type:F.Master},[k.Seek]:{type:F.Master},[k.SeekID]:{type:F.Binary},[k.SeekPosition]:{type:F.UnsignedInteger},[k.Info]:{type:F.Master},[k.TimestampScale]:{type:F.UnsignedInteger},[k.Duration]:{type:F.Float},[k.Tracks]:{type:F.Master},[k.TrackEntry]:{type:F.Master},[k.Video]:{type:F.Master},[k.Projection]:{type:F.Master},[k.ProjectionType]:{type:F.UnsignedInteger},[k.ProjectionPrivate]:{type:F.Master},[k.Chapters]:{type:F.Master},[k.Cluster]:{type:F.Master},[k.Timestamp]:{type:F.UnsignedInteger},[k.SilentTracks]:{type:F.Master},[k.SilentTrackNumber]:{type:F.UnsignedInteger},[k.Position]:{type:F.UnsignedInteger},[k.PrevSize]:{type:F.UnsignedInteger},[k.SimpleBlock]:{type:F.Binary},[k.BlockGroup]:{type:F.Master},[k.EncryptedBlock]:{type:F.Binary},[k.Attachments]:{type:F.Master},[k.Tags]:{type:F.Master},[k.Cues]:{type:F.Master},[k.CuePoint]:{type:F.Master},[k.CueTime]:{type:F.UnsignedInteger},[k.CueTrackPositions]:{type:F.Master},[k.CueTrack]:{type:F.UnsignedInteger},[k.CueClusterPosition]:{type:F.UnsignedInteger},[k.CueRelativePosition]:{type:F.UnsignedInteger},[k.CueDuration]:{type:F.UnsignedInteger},[k.CueBlockNumber]:{type:F.UnsignedInteger},[k.CueCodecState]:{type:F.UnsignedInteger},[k.CueReference]:{type:F.Master},[k.CueRefTime]:{type:F.UnsignedInteger}},Wd=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=lr(s,t),r=i in Eo,a=r?Eo[i].type:F.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=lr(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},lr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return lr(s);case F.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case F.String:return new TextDecoder("ascii").decode(s);case F.UTF8:return new TextDecoder("utf-8").decode(s);case F.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case F.Master:return s;case F.Binary:return s;default:z(e)}},ji=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Wd(i);if(!e(r))return;r.type===F.Master&&ji(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Nv=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Wd(s);return ji(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=_t(o,n):a===k.DocType?t=_t(o,n):a===k.DocTypeReadVersion&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Qd=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Fv=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],Uv=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ji(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===k.SeekID){const b=_t(m,f);d=lr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=_t(m,f):h===k.Duration?r=_t(m,f):h===k.SeekPosition&&d===k.Cues?u=_t(m,f):h===k.Tracks?ji(m,({tag:b,type:v,value:y})=>b===k.ProjectionType?(l=_t(y,v)===1,!1):!0):a&&n&&Qd.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vv=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Hv=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ji(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=_t(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=_t(d,u));break;default:t&&Qd.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.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}}})},Gv=s=>{let e=0,t=!1;try{ji(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Fv.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Yv={validateData:Nv,parseInit:Uv,getIndexRange:Vv,parseSegments:Hv,parseFeedableSegmentChunk:Gv},$o=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Oi=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},zv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,v,y,g,E,$,L,G,Q,V,q,W,B,M,K,O,x,Y,te,fe,be,Pe,ze,rt,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},we=qe.children[0],Ct=we.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=we.getAttribute("type")==="dynamic",Mt=we.getAttribute("availabilityStartTime"),Pi=Mt?new Date(Mt).getTime():void 0;let Ne;const Xi=we.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=we.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Ne=$o(Xi);else if(Zi){const ye=$o(Zi);D(ye)&&(Ne=ye)}else es&&(Ne=parseInt(es,10));let kr=0;const oi=(i=(t=we.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(dr.WEBM_AS_IN_FFMPEG)||oi.includes(dr.WEBM_AS_IN_SPEC)?qi.WEBM:qi.MP4;for(const ye of Bt){const Ot=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Ot==null?void 0:Ot.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Me.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Ke=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Ke,e).toString(),ui=Re.includes("_auto");De[Me.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Me.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Ot,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Ke=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((v=J.getAttribute("width"))!==null&&v!==void 0?v:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((g=J.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(kr++).toString(10),Cr=Ke==="video"?`${ss}p`:Ke==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Mr=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Mr,e).toString(),Or=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Fe=(q=J.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:Rr;if(Nr){const Je=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Xe,hi]=Je.split("-").map(Ze=>parseInt(Ze,10)),je={from:Xe,to:hi},ft=(M=J.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[fi,Ft]=ft?ft.split("-").map(Ze=>parseInt(Ze,10)):[],pt=ft?{from:fi,to:Ft}:void 0;li={type:ut.BYTE_RANGE,url:ns,initRange:je,indexRange:pt}}else if(Fe){const Je={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(O=J.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},Xe=parseInt((x=Fe.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Fe.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",je=Fe.getAttribute("media"),ft=(fe=parseInt((te=Fe.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=Oi(hi,Je);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Fe.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],pt=[];let Ze=0,pi="",et=0;if(Ft.length){let tt=ft,ke=0;for(const mt of Ft){const We=parseInt((Pe=mt.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),Tt=parseInt((ze=mt.getAttribute("r"))!==null&&ze!==void 0?ze:"",10)||0,Ut=parseInt((rt=mt.getAttribute("t"))!==null&&rt!==void 0?rt:"",10);ke=Number.isFinite(Ut)?Ut:ke;const os=We/Xe*1e3,Di=ke/Xe*1e3;for(let Ri=0;Ri<Tt+1;Ri++){const iu=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:(ke+Ri*We).toString(10)}),mn=(Di!=null?Di:0)+Ri*os,su=mn+os;tt++,pt.push({time:{from:mn,to:su},url:iu})}ke+=(Tt+1)*We,Ze+=(Tt+1)*os}et=ke/Xe*1e3,pi=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:ke.toString(10)})}else if(D(Ne)){const ke=parseInt((ie=Fe.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Xe*1e3,mt=Math.ceil(Ne/ke);let We=0;for(let Tt=1;Tt<mt;Tt++){const Ut=Oi(je,{...Je,segmentNumber:Tt.toString(10),segmentTime:We.toString(10)});pt.push({time:{from:We,to:We+ke},url:Ut}),We+=ke}et=We,pi=Oi(je,{...Je,segmentNumber:mt.toString(10),segmentTime:We.toString(10)})}const mi={time:{from:et,to:1/0},url:pi};li={type:ut.TEMPLATE,baseUrl:ns,segmentTemplateUrl:je,initUrl:fi,totalSegmentsDurationMs:Ze,segments:pt,nextSegmentBeyondManifest:mi,timescale:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ke||!Re)continue;const ci={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Ke];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Or,duration:Ne,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Ne,container:_r,representations:De}},qv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},jv=({id:s,bitrate:e})=>({id:s,bitrate:e}),Wv=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},Qv=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Ao=s=>"size"in s,Bi=s=>s.type===ut.TEMPLATE,Ya=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class wo{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,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,async function*(c){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 uv(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),m=this.segments.get(h.id),S=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(m,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(m,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S))}.bind(this)),this.switchTo=ce(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;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(j(m)||j(f)?yield this.loadInit(h,"high",!1):m instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const S=this.getCurrentPosition();D(S)&&(this.isLive||(f.forEach(b=>b.status=Z.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const y of this.representations.keys()){const g=c.find(L=>L.id===y);g&&this.representations.set(y,g);const E=this.representations.get(y);if(!E||!Bi(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const S=this.segments.get(f);P(S,"No segments for starting representation");const b=this.initData.get(f);if(P(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return;const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal)),this.searchGaps(S,m),yield this.sourceBufferTaskQueue.append(b,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=i,i){case qi.MP4:this.containerParser=Ov;break;case qi.WEBM:this.containerParser=Yv;break;default:z(i)}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 lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Qe(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Qe(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&Qe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===Z.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;D(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=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<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Bi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:Z.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(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 i of this.representations.values()){const r=i.segmentReference;if(!Bi(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(i.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:Z.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+v||f<=i+v;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==ut.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===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===ut.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Z.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&&(await ce(o,async function*(){const l=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,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?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=Z.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Ya(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=Z.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&&(await ce(n,async function*(){const u=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Ya(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(Bi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,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:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Bi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.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:R.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)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&D(r)&&(i=Qe((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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=i,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=Z.PARTIALLY_FED,o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,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===ut.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,v=S<r,y=b<=r;if(c.status===Z.DOWNLOADING&&v&&y){c.status=Z.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(g,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?g:this.containerParser.parseFeedableSegmentChunk(g);E!=null&&E.byteLength&&(c.status=Z.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Z.FED,Ao(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===Z.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=Z.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{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&&Bi(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),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(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=Ao(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===Z.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===Z.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===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ui;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ui||(Ui={}));class Kv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new lt,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(ls);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ui.HEADER:Ui.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;let m=r;const S=new Headers;if(n)switch(a){case Ui.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Ui.PARAM:{const M=new URL(m,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),m=M.toString();break}default:z(a)}this.requestQuic&&(m=ii(m));let b=this.abortAllController.signal,v;if(d){const M=new lt;if(v=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{M.abort()}catch(K){ls(K)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(K){ls(K)}b=M.signal}const y=le(),g=yield $i(m,{priority:u,headers:S,signal:b}).catch(ls),E=le();if(!g)return v==null||v.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!g.ok||!g.body)return v==null||v.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!o&&!l)return v==null||v.unsubscribe(),g.arrayBuffer();const[$,L]=g.body.tee(),G=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(L,c));let Q=0,V=new Uint8Array(0),q=!1;const W=M=>{v==null||v.unsubscribe(),q=!0,ls(M)},B=ce(b,async function*({done:M,value:K}){if(Q===0&&this.lastRequestFirstBytes$.next(le()-y),b.aborted){v==null||v.unsubscribe();return}if(!M&&K){const O=new Uint8Array(V.length+K.length);O.set(V),O.set(K,V.length),V=O,Q+=K.byteLength,o==null||o(new DataView(V.buffer),Q),yield G==null?void 0:G.read().then(B,W)}}.bind(this));return yield G==null?void 0:G.read().then(B,W),v==null||v.unsubscribe(),q?null:V.buffer}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==ut.BYTE_RANGE)return 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 S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let g;if(h)g=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;g=new DataView($)}const E=a.parseSegments(g,v,y);return{init:v,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==ut.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case ut.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case ut.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ls=s=>{if(!Ya(s))throw s},za=1e3,cr=(s,e,t)=>t*e+(1-t)*s,Kd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Jv=(s,e,t,i)=>{let r=0,a=t;const n=Kd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class pn{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 T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new wt(`raw_${i}`),this.smoothedSeries$=new wt(`smoothed_${i}`),this.reportedSeries$=new wt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(j(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 Xv extends pn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Zv extends pn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Jv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class eS extends pn{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?cr(this.smoothed,e,this.params.emaAlpha):e}}class qa{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Xv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Zv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new eS({initial:e,label:"liveEdgeDelay",...t})}}const tS=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},ko=["timeupdate","progress","play","seeked","stalled","waiting"];var ot;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ot||(ot={}));let iS=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(ot.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ot.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(ot.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return null;let r;try{r=zv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Me.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)),{...r,representations:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ot.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new wo(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new wo(Me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(za).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+za,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...ko.map(o=>U(this.element,o))).pipe(_(o=>this.element?Qe(this.element.buffered,this.element.currentTime*1e3):0),ve(),ae(o=>!!o),vs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ae(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),tS(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(P(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let v=At.None;if(this.isActiveLowLatency?v=At.ActiveLowLatency:b<f+S&&b>=f?v=At.LiveWithTargetOffset:c!==0&&b<f&&(v=At.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),v===At.LiveForwardBuffering||v===At.LiveWithTargetOffset){const y=o-(f+m),g=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(g-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:g>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=g:$=0,this.manifestUrlString=He(this.manifestUrlString,$,Se.DASH_CMAF_OFFSET_P)}v!==At.None&&v!==At.ActiveLowLatency&&(o=0,this.updateLive())}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ot.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Kv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=qa.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,i,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=He(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(ot.RUNNING),this.subscription.add(H(...ko.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const i={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ot.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:R.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await 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,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class Jd{constructor(e){this.subscription=new ue,this.videoState=new he(Ee.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Ee.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Ee.STOPPED&&(this.videoState.startTransitionTo(Ee.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(Ee.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Ee.STOPPED:this.videoState.startTransitionTo(Ee.READY),this.prepare();return;case Ee.READY:n===p.PAUSED?(this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Ee.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Ee.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Ee.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Ee.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&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(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(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new iS({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ee.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ee.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ee.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===ot.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=jv(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=qv(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&Wv(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=Qv(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===ot.REPRESENTATIOS_READY&&(this.videoState.setState(Ee.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==ot.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Me.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,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:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(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),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.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),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){console.log("destroy DASH provider"),this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),It(this.video)}}class sS extends Jd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let rS=class extends zd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Le({interval:Ti(Ha),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Te.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Te.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)})}};class aS extends Jd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Le({interval:Ti(za),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ee.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(Le({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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Ee.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 $t={};var de;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));const cs=(s,e)=>new fr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class nS{constructor(e){this.subscription=new ue,this.videoState=new he(de.INITIALIZING),this.textTracksManager=new yt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==de.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case de.STOPPED:break;case de.READY:case de.PLAYING:case de.PAUSED:this.stop();break;default:z(t)}break;case p.READY:switch(t){case de.STOPPED:this.prepare();break;case de.READY:case de.PLAYING:case de.PAUSED:break;default:z(t)}break;case p.PLAYING:switch(t){case de.PLAYING:break;case de.STOPPED:this.prepare();break;case de.READY:case de.PAUSED:this.playIfAllowed();break;default:z(t)}break;case p.PAUSED:switch(t){case de.PAUSED:break;case de.STOPPED:this.prepare();break;case de.READY:this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case de.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Rt(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(Ye(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),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||($t.Hls=r.default,$t.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P($t.Hls,"hls.js not loaded"),this.hls=new $t.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(de.STOPPED)}subscribe(){P($t.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Lt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ri(this.video,e.isLooped,i)),this.subscription.add(Dt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(cs(this.hls,$t.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.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(de.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),a(cs(this.hls,$t.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:S,height:b}=c,v=(f=Ki((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:si({width:S,height:b});if(!v)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:m.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(m,{track:g,level:c}),l.push(g),l},[]))),t.availableVideoTracks$),a(cs(this.hls,$t.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,S="internal";l.push({id:h,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(cs(this.hls,$t.Events.LEVEL_LOADING).pipe(_(({url:d})=>Ye(d))),t.hostname$),this.subscription.add(vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=cs(this.hls,$t.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(ae(D)).subscribe(t.currentVideoTrack$,i),this.subscription.add(vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(j(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:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(de.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(de.PLAYING),await Kt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(de.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(de.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const _o="X-Playback-Duration";var Po=async s=>{var e;const t=await $i(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(_o)?parseInt(t.headers.get(_o),10):void 0};const oS=s=>{let e=null;if(s.QUALITY&&(e=Ki(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=si({width:t,height:i})}return e!=null?e:null},Xd=async(s,e=s)=>{var t,i;const n=(await(await $i(s)).text()).split(`
46
- `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Ei(c[1].split(",").map(E=>E.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=oS(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(L=>parseInt(L,10));E&&$&&(y={width:E,height:$})}const g=new URL(n[++d],e).toString();S&&o.push({id:m,quality:S,url:g,bandwidth:b,size:y,fps:v})}if(h){const f=Ei(h[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;m&&S&&u.push({type:"internal",id:S,label:b,language:S,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var pe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(pe||(pe={}));class dS{constructor(e){var t;this.subscription=new ue,this.videoState=new he(pe.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.liveOffset=new ws,this.manifestStartTime$=new T(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!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(pe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===pe.STOPPED){this.videoState.startTransitionTo(pe.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(pe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===ee.Requested){this.videoState.startTransitionTo(pe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case pe.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed());return;case pe.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case pe.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(pe.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&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case pe.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.INVARIANT,url:this.params.source.url},Xd(He(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:R.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(Ye(this.params.source.url)),this.maxSeekBackTime$=new T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,i,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:(i=n.getState())===null||i===void 0?void 0:i.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,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(pe.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(pe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===pe.READY&&this.videoState.setState(pe.READY),this.videoState.getState()===pe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&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(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===pe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ee.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(ae(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),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$,i));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.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===A.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=He(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),Po(u).then(d=>{var l;if(!j(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(j(c)||!isFinite(c))try{$i(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 S=new URL(m,u).toString();Po(S).then(b=>{j(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class uS{constructor(e){this.subscription=new ue,this.videoState=new he(ge.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=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){i!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===ee.Requested&&this.seek(l.position),i){case ge.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ge.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ge.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.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(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xd(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,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:(i=n.getState())===null||i===void 0?void 0:i.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,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Lt(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(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&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(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ee.Requested&&this.seek(o.position)},i))),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$,i)),!lu()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(H(U(o,"addtrack"),U(o,"removetrack"),U(o,"change"),Ge(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.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(){Kt(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var $e;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})($e||($e={}));class lS{constructor(e){this.subscription=new ue,this.videoState=new he($e.STOPPED),this.trackUrls={},this.textTracksManager=new yt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==$e.STOPPED&&(this.videoState.startTransitionTo($e.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($e.STOPPED),I(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!==$e.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===$e.STOPPED){this.videoState.startTransitionTo($e.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===ee.Requested&&this.seek(c.position),a){case $e.READY:n===p.READY?I(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed());return;case $e.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo($e.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case $e.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState($e.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState($e.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===$e.READY&&this.videoState.setState($e.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&D(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===$e.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(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:i}=this.trackUrls[t];P(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=ii(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Ye(i))}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,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=(i=Object.values(this.trackUrls).find(c=>!yi(c.track.quality)&&Fo(c.track.quality,e)))===null||i===void 0?void 0:i.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&&Ra(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!yi(f.track.quality)&&Vi(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=_i(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 Do=["stun:videostun.mycdn.me:80"],cS=1e3,hS=3,ma=()=>null;class fS{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ma,this.externalStopCallback=ma,this.externalErrorCallback=ma,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Do}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:R.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),cS)}normalizeOptions(e={}){const t={stunServerList:Do,maxRetryNumber:hS,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var me;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(me||(me={}));class pS{constructor(e){this.videoState=new he(me.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==me.STOPPED&&(this.videoState.startTransitionTo(me.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(me.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===me.STOPPED){this.videoState.startTransitionTo(me.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case me.READY:i===p.PAUSED?(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed());return;case me.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case me.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(t)}},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new fS(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),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(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=Lt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===me.READY&&this.videoState.setState(me.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Dt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case me.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case me.READY:break;case me.PAUSED:t.playbackState.setState(p.PAUSED);break;case me.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return z(n.to)}},i)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ye(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:at.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(me.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:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Ro{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 ga,va,Sa,ba,ya,Ta,Ea,$a,Us,Aa,Vs,wa,Hs,ka,Gs,_a,Ys,Pa,zs,Da;const Zd=hr().device===cu.Android,ti=document.createElement("video"),mS='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gS='video/mp4; codecs="hev1.1.6.L93.B0"',eu='video/webm; codecs="vp09.00.10.08"',tu='video/webm; codecs="av01.0.00M.08"',vS='audio/mp4; codecs="mp4a.40.2"',SS='audio/webm; codecs="opus"',xe={mms:!!(window.ManagedMediaSource&&(!((va=(ga=window.ManagedSourceBuffer)===null||ga===void 0?void 0:ga.prototype)===null||va===void 0)&&va.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((ba=(Sa=window.SourceBuffer)===null||Sa===void 0?void 0:Sa.prototype)===null||ba===void 0)&&ba.appendBuffer)),hls:!!(!((ya=ti.canPlayType)===null||ya===void 0)&&ya.call(ti,"application/x-mpegurl")||!((Ta=ti.canPlayType)===null||Ta===void 0)&&Ta.call(ti,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},it={mp4:!!(!((Ea=ti.canPlayType)===null||Ea===void 0)&&Ea.call(ti,"video/mp4")),webm:!!(!(($a=ti.canPlayType)===null||$a===void 0)&&$a.call(ti,"video/webm")),cmaf:!0},Pt={h264:!!(!((Aa=(Us=window.MediaSource||window.ManagedMediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Aa===void 0)&&Aa.call(Us,mS)),h265:!!(!((wa=(Vs=window.MediaSource||window.ManagedMediaSource)===null||Vs===void 0?void 0:Vs.isTypeSupported)===null||wa===void 0)&&wa.call(Vs,gS)),vp9:!!(!((ka=(Hs=window.MediaSource||window.ManagedMediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||ka===void 0)&&ka.call(Hs,eu)),av1:!!(!((_a=(Gs=window.MediaSource||window.ManagedMediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||_a===void 0)&&_a.call(Gs,tu)),aac:!!(!((Pa=(Ys=window.MediaSource||window.ManagedMediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Pa===void 0)&&Pa.call(Ys,vS)),opus:!!(!((Da=(zs=window.MediaSource||window.ManagedMediaSource)===null||zs===void 0?void 0:zs.isTypeSupported)===null||Da===void 0)&&Da.call(zs,SS))},Mi=(Pt.h264||Pt.h265)&&Pt.aac;var ei;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(ei||(ei={}));var Gt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Gt||(Gt={}));let gi;const bS=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:tu}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:eu}})]);gi={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}};try{bS()}catch(s){console.error(s)}const Ts=xe.hls&&it.mp4,yS=()=>Object.keys(Pt).filter(s=>Pt[s]),TS=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return xe.mse&&it.mp4&&Mi;case A.DASH_SEP:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.DASH_WEBM:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.vp9&&Pt.opus;case A.DASH_WEBM_AV1:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.av1&&Pt.opus;case A.DASH_LIVE:return xe.mse&&it.mp4&&Mi;case A.DASH_LIVE_CMAF:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi&&it.cmaf;case A.DASH_ONDEMAND:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.HLS:case A.HLS_ONDEMAND:return Ts||e&&xe.mse&&it.mp4&&Mi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Ts;case A.MPEG:return it.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return xe.webrtc&&xe.ws&&Pt.h264&&(it.mp4||it.webm);default:return z(i)}}),hs=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case ei.VP9:return[e,t];case ei.AV1:return[t,e];case ei.NONE:return[];case ei.SMOOTH:return gi?gi[t].smooth?[t,e]:gi[e].smooth?[e,t]:[t,e]:[e,t];case ei.POWER_EFFICIENT:return gi?gi[t].powerEfficient?[t,e]:gi[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},ES=({webmCodec:s,androidPreferredFormat:e})=>{if(Zd)switch(e){case Gt.MPEG:return[A.MPEG,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Gt.HLS:return[A.HLS,A.HLS_ONDEMAND,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Gt.DASH:return[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Ts?[...hs(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},$S=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(Zd)switch(s){case Gt.DASH:{o=a;break}case Gt.HLS:case Gt.MPEG:{o=n;break}}else Ts?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},Io=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var AS=s=>new fr(e=>{const t=new ue,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(_(({type:d})=>d!==void 0)),n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const wS={cacheDuration:12e4},kS={chunkDuration:5e3,maxParallelRequests:5};class _S{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new C,warning$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=TS([...$S(this.params.tuning),...ES(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>D(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ro(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...Io(!0),...Io(!1)];this.chromecastFormatsIterator=new Ro(n.filter(o=>D(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(console.log("Choose provider "+t),j(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==ee.None;if(this.params.desiredState.seekState.setState({state:ee.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ue.SCREEN:return this.createScreenProvider(t);case Ue.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new _m({...n,source:o,config:wS})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new sS({...n,source:o})):new dv({...n,source:o})}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new aS({...n,source:o}):new rS({...n,source:o})}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ts||!this.params.tuning.useHlsJs?new uS({...n,source:o}):new nS({...n,source:o})}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new dS({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new lS({...n,source:o})}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Em({...n,source:o,config:{...kS,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new pS({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Lp({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ue.CHROMECAST:Ue.SCREEN}chooseFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ue.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.next();case Ue.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ue.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ue.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return z(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ei(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ue;let t=!1,i=0;const r=le();return e.add(H(this.providerOutput.error$,AS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(a=>({id:`ProviderHangup:${a}`,category:R.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{console.log(a);const n=this.current$.getValue().destination;if(n===Ue.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ue.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===R.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,l=u&&(o&&t||!d),c=a.id.includes("partial_metadata"),h=le()-r;l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c&&h<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ue.SCREEN)}})),e}}const PS=5e3,Lo="one_video_throughput",xo="one_video_rtt",Yt=window.navigator.connection,Co=()=>{const s=Yt==null?void 0:Yt.downlink;if(D(s)&&s!==10)return s*1e3},Bo=()=>{const s=Yt==null?void 0:Yt.rtt;if(D(s)&&s!==3e3)return s},Mo=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class gs{constructor(e){var t,i;this.subscription=new ue,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=gs.load(Lo)||(e.useBrowserEstimation?Co():void 0)||PS,a=(i=(t=gs.load(xo))!==null&&t!==void 0?t:e.useBrowserEstimation?Bo():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Mo(r,a,e.rttPenaltyRequestSize)),this.throughput=qa.getSmoothedValue(r,-1,e),this.rtt=qa.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Co();u&&this.throughput.next(u);const d=Bo();D(d)&&this.rtt.next(d)};Yt&&"onchange"in Yt&&this.subscription.add(U(Yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fr.set(Lo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fr.set(xo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>Mo(n,o,e.rttPenaltyRequestSize)),ae(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le();const r=new ue;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!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());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(gs.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=Fr.get(e);if(D(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Oo={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},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:at.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ei.VP9,androidPreferredFormat:Gt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},DS=s=>{var e;return{...hu(s,Oo),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Oo.configName]}};var No=({seekState:s,position$:e})=>H(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===ee.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),ae(D)),e.pipe(ae(()=>s.getState().state===ee.None))),RS=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const IS=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ae(r=>r.length>0),Ae()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class nb{constructor(e={configName:[]}){if(this.subscription=new ue,this.logger=new fu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:ee.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 T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(Zt.NONE),chromecastState$:new T(Ce.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new C,ready$:new C,started$:new C,playing$:new C,paused$:new C,stopped$:new C,willStart$:new C,willResume$:new C,willPause$:new C,willStop$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:im},this.initLogs(),this.tuning=DS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new gu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gs(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=RS(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new _S({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(document,"visibilitychange").pipe(Ae()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ee.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()===Ce.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()===Ce.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(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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 i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return IS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.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 i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(j(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ee.None?void 0:t.position;return D(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(H(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(ae(({from:e})=>e===p.STOPPED),Ae()).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===ee.Requested?this.desiredState.seekState.setState({...n,state:ee.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ee.Applying&&(this.desiredState.seekState.setState({state:ee.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>yi(o)?1:yi(u)?-1:Vi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(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(Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Le({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),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),ve()).subscribe(this.info.volume$)).add(No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(Hi(!0)),e.providerOutput.seekedEvent$.pipe(Hi(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:R.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(Ae(),_(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),_(()=>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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>i.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Ce.CONNECTED?l=Zt.SECOND_SCREEN:u?n?l=Zt.PIP:o?l=Zt.FULLSCREEN:l=Zt.INLINE:l=Zt.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 ue;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=_i(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(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(H(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),tm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>em(i)),this.providerContainer.current$.subscribe(({type:i})=>Ms("provider",i)),t.duration$.subscribe(i=>Ms("duration",i)),t.availableVideoTracks$.pipe(ae(i=>!!i.length),Ae()).subscribe(i=>Ms("tracks",i)),this.events.fatalError$.subscribe(new wt("fatalError")),this.events.managedError$.subscribe(new wt("managedError")),t.position$.subscribe(new wt("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new wt("quality")),this.info.currentBuffer$.subscribe(new wt("buffer")),t.isBuffering$.subscribe(new wt("isBuffering"))].forEach(i=>this.subscription.add(i)),Ms("codecs",yS())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(r)})})};this.subscription.add(H(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const ob=`@vkontakte/videoplayer-core@${pu}`;export{Ce as ChromecastState,Ss as HttpConnectionType,lb as Observable,p as PlaybackState,nb as Player,ob as SDK_VERSION,cb as Subject,hb as Subscription,Zt as Surface,pu as VERSION,fb as ValueSubject,A as VideoFormat,pb 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 Yd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new rv(this.params.fov,this.params.orientation),this.cameraRotationManager=new av(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(nv,this.gl.VERTEX_SHADER),i=this.createShader(ov,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let zd=class{constructor(e){this.subscription=new ue,this.videoState=new he(Te.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Te.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Te.STOPPED&&(this.videoState.startTransitionTo(Te.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(Te.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Te.STOPPED:this.videoState.startTransitionTo(Te.READY),this.prepare();return;case Te.READY:n===p.PAUSED?(this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Te.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Te.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Te.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Te.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&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(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(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new sv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Te.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Te.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Te.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===nt.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=hg(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=cg(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&fg(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=pg(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===nt.REPRESENTATIOS_READY&&(this.videoState.setState(Te.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==nt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Be.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Be.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,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:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(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),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.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),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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),It(this.video)}},dv=class extends zd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Me;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Me||(Me={}));var At;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(At||(At={}));var dr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(dr||(dr={}));var ut;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(ut||(ut={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var qi;(function(s){s.MP4="mp4",s.WEBM="webm"})(qi||(qi={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var Ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ee||(Ee={}));var fa,pa;let qd=!1;try{qd=hr().browser===ja.Safari&&parseInt((pa=(fa=navigator.userAgent.match(/Version\/(\d+)/))===null||fa===void 0?void 0:fa[1])!==null&&pa!==void 0?pa:"",10)<16}catch(s){console.error(s)}class uv{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;qd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.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:z(t)}}}class ht{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class jd extends ht{}class lv extends ht{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class cv extends ht{parseChildrenBoxes(){return ai(this.content)}}class hv extends ht{parseChildrenBoxes(){return ai(this.content)}}class fv extends ht{constructor(e){super(e),this.data=this.content}}class Jt extends ht{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class pv extends Jt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class mv extends ht{parseChildrenBoxes(){return ai(this.content)}}class gv extends ht{parseChildrenBoxes(){return ai(this.content)}}var bi;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(bi||(bi={}));class vv extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bi.MONOSCOPIC;break;case 1:this.stereoMode=bi.TOP_BOTTOM;break;case 2:this.stereoMode=bi.LEFT_RIGHT;break;case 3:this.stereoMode=bi.STEREO_CUSTOM;break;case 4:this.stereoMode=bi.RIGHT_LEFT;break}this.cursor+=1}}class Sv extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class bv extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class yv extends ht{parseChildrenBoxes(){return ai(this.content)}}class Tv extends Jt{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Ev extends ht{parseChildrenBoxes(){return ai(this.content)}}class $v extends ht{parseChildrenBoxes(){return ai(this.content)}}class Av extends Jt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class wv extends ht{parseChildrenBoxes(){return ai(this.content)}}class kv extends Jt{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class _v extends Jt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Pv extends Jt{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Dv={ftyp:lv,moov:cv,moof:hv,mdat:fv,sidx:pv,trak:mv,mdia:yv,mfhd:Av,tkhd:Tv,traf:wv,tfhd:kv,tfdt:_v,trun:Pv,minf:Ev,sv3d:gv,st3d:vv,prhd:Sv,proj:$v,equi:bv,unknown:jd};class Rv{createBox(e,t){const i=Dv[e];return i?new i(t):new jd(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return wr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const wr=new Rv;function ps(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:wr.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Ga(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ps(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function ai(s){const e=[];let t=0;for(;t<s.byteLength;){const i=wr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Iv=new TextDecoder("ascii"),Lv=s=>Iv.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",xv=s=>{const e=wr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Z.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Cv=s=>{const e=Ga(s,"mdat"),t=Ga(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},Bv=(s,e)=>{const t=Ga(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Mv=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ps(s,"sv3d")){e.is3dVideo=!0;const i=ps(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ps(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ps(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Ov={validateData:Lv,parseInit:Mv,getIndexRange:()=>{},parseSegments:xv,parseFeedableSegmentChunk:Cv,getSegmentEndTime:Bv};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var F;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(F||(F={}));const Eo={[k.EBML]:{type:F.Master},[k.EBMLVersion]:{type:F.UnsignedInteger},[k.EBMLReadVersion]:{type:F.UnsignedInteger},[k.EBMLMaxIDLength]:{type:F.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:F.UnsignedInteger},[k.DocType]:{type:F.String},[k.DocTypeVersion]:{type:F.UnsignedInteger},[k.DocTypeReadVersion]:{type:F.UnsignedInteger},[k.Void]:{type:F.Binary},[k.Segment]:{type:F.Master},[k.SeekHead]:{type:F.Master},[k.Seek]:{type:F.Master},[k.SeekID]:{type:F.Binary},[k.SeekPosition]:{type:F.UnsignedInteger},[k.Info]:{type:F.Master},[k.TimestampScale]:{type:F.UnsignedInteger},[k.Duration]:{type:F.Float},[k.Tracks]:{type:F.Master},[k.TrackEntry]:{type:F.Master},[k.Video]:{type:F.Master},[k.Projection]:{type:F.Master},[k.ProjectionType]:{type:F.UnsignedInteger},[k.ProjectionPrivate]:{type:F.Master},[k.Chapters]:{type:F.Master},[k.Cluster]:{type:F.Master},[k.Timestamp]:{type:F.UnsignedInteger},[k.SilentTracks]:{type:F.Master},[k.SilentTrackNumber]:{type:F.UnsignedInteger},[k.Position]:{type:F.UnsignedInteger},[k.PrevSize]:{type:F.UnsignedInteger},[k.SimpleBlock]:{type:F.Binary},[k.BlockGroup]:{type:F.Master},[k.EncryptedBlock]:{type:F.Binary},[k.Attachments]:{type:F.Master},[k.Tags]:{type:F.Master},[k.Cues]:{type:F.Master},[k.CuePoint]:{type:F.Master},[k.CueTime]:{type:F.UnsignedInteger},[k.CueTrackPositions]:{type:F.Master},[k.CueTrack]:{type:F.UnsignedInteger},[k.CueClusterPosition]:{type:F.UnsignedInteger},[k.CueRelativePosition]:{type:F.UnsignedInteger},[k.CueDuration]:{type:F.UnsignedInteger},[k.CueBlockNumber]:{type:F.UnsignedInteger},[k.CueCodecState]:{type:F.UnsignedInteger},[k.CueReference]:{type:F.Master},[k.CueRefTime]:{type:F.UnsignedInteger}},Wd=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=lr(s,t),r=i in Eo,a=r?Eo[i].type:F.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=lr(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},lr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return lr(s);case F.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case F.String:return new TextDecoder("ascii").decode(s);case F.UTF8:return new TextDecoder("utf-8").decode(s);case F.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case F.Master:return s;case F.Binary:return s;default:z(e)}},ji=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Wd(i);if(!e(r))return;r.type===F.Master&&ji(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Nv=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Wd(s);return ji(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=_t(o,n):a===k.DocType?t=_t(o,n):a===k.DocTypeReadVersion&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Qd=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Fv=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],Uv=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ji(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===k.SeekID){const b=_t(m,f);d=lr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=_t(m,f):h===k.Duration?r=_t(m,f):h===k.SeekPosition&&d===k.Cues?u=_t(m,f):h===k.Tracks?ji(m,({tag:b,type:v,value:y})=>b===k.ProjectionType?(l=_t(y,v)===1,!1):!0):a&&n&&Qd.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vv=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Hv=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ji(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=_t(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=_t(d,u));break;default:t&&Qd.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.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}}})},Gv=s=>{let e=0,t=!1;try{ji(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Fv.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Yv={validateData:Nv,parseInit:Uv,getIndexRange:Vv,parseSegments:Hv,parseFeedableSegmentChunk:Gv},$o=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Oi=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},zv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,v,y,g,E,$,L,G,Q,V,q,W,B,M,K,O,x,Y,te,fe,be,Pe,ze,rt,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},we=qe.children[0],Ct=we.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=we.getAttribute("type")==="dynamic",Mt=we.getAttribute("availabilityStartTime"),Pi=Mt?new Date(Mt).getTime():void 0;let Ne;const Xi=we.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=we.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Ne=$o(Xi);else if(Zi){const ye=$o(Zi);D(ye)&&(Ne=ye)}else es&&(Ne=parseInt(es,10));let kr=0;const oi=(i=(t=we.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(dr.WEBM_AS_IN_FFMPEG)||oi.includes(dr.WEBM_AS_IN_SPEC)?qi.WEBM:qi.MP4;for(const ye of Bt){const Ot=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Ot==null?void 0:Ot.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Me.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Ke=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Ke,e).toString(),ui=Re.includes("_auto");De[Me.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Me.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Ot,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Ke=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((v=J.getAttribute("width"))!==null&&v!==void 0?v:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((g=J.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(kr++).toString(10),Cr=Ke==="video"?`${ss}p`:Ke==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Mr=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Mr,e).toString(),Or=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Fe=(q=J.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:Rr;if(Nr){const Je=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Xe,hi]=Je.split("-").map(Ze=>parseInt(Ze,10)),je={from:Xe,to:hi},ft=(M=J.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[fi,Ft]=ft?ft.split("-").map(Ze=>parseInt(Ze,10)):[],pt=ft?{from:fi,to:Ft}:void 0;li={type:ut.BYTE_RANGE,url:ns,initRange:je,indexRange:pt}}else if(Fe){const Je={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(O=J.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},Xe=parseInt((x=Fe.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Fe.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",je=Fe.getAttribute("media"),ft=(fe=parseInt((te=Fe.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=Oi(hi,Je);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Fe.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],pt=[];let Ze=0,pi="",et=0;if(Ft.length){let tt=ft,ke=0;for(const mt of Ft){const We=parseInt((Pe=mt.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),Tt=parseInt((ze=mt.getAttribute("r"))!==null&&ze!==void 0?ze:"",10)||0,Ut=parseInt((rt=mt.getAttribute("t"))!==null&&rt!==void 0?rt:"",10);ke=Number.isFinite(Ut)?Ut:ke;const os=We/Xe*1e3,Di=ke/Xe*1e3;for(let Ri=0;Ri<Tt+1;Ri++){const iu=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:(ke+Ri*We).toString(10)}),mn=(Di!=null?Di:0)+Ri*os,su=mn+os;tt++,pt.push({time:{from:mn,to:su},url:iu})}ke+=(Tt+1)*We,Ze+=(Tt+1)*os}et=ke/Xe*1e3,pi=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:ke.toString(10)})}else if(D(Ne)){const ke=parseInt((ie=Fe.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Xe*1e3,mt=Math.ceil(Ne/ke);let We=0;for(let Tt=1;Tt<mt;Tt++){const Ut=Oi(je,{...Je,segmentNumber:Tt.toString(10),segmentTime:We.toString(10)});pt.push({time:{from:We,to:We+ke},url:Ut}),We+=ke}et=We,pi=Oi(je,{...Je,segmentNumber:mt.toString(10),segmentTime:We.toString(10)})}const mi={time:{from:et,to:1/0},url:pi};li={type:ut.TEMPLATE,baseUrl:ns,segmentTemplateUrl:je,initUrl:fi,totalSegmentsDurationMs:Ze,segments:pt,nextSegmentBeyondManifest:mi,timescale:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ke||!Re)continue;const ci={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Ke];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Or,duration:Ne,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Ne,container:_r,representations:De}},qv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},jv=({id:s,bitrate:e})=>({id:s,bitrate:e}),Wv=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},Qv=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Ao=s=>"size"in s,Bi=s=>s.type===ut.TEMPLATE,Ya=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class wo{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,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,async function*(c){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 uv(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),m=this.segments.get(h.id),S=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(m,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(m,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S))}.bind(this)),this.switchTo=ce(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;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(j(m)||j(f)?yield this.loadInit(h,"high",!1):m instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const S=this.getCurrentPosition();D(S)&&(this.isLive||(f.forEach(b=>b.status=Z.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const y of this.representations.keys()){const g=c.find(L=>L.id===y);g&&this.representations.set(y,g);const E=this.representations.get(y);if(!E||!Bi(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const S=this.segments.get(f);P(S,"No segments for starting representation");const b=this.initData.get(f);if(P(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return;const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal)),this.searchGaps(S,m),yield this.sourceBufferTaskQueue.append(b,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=i,i){case qi.MP4:this.containerParser=Ov;break;case qi.WEBM:this.containerParser=Yv;break;default:z(i)}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 lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Qe(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Qe(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&Qe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===Z.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;D(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=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<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Bi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:Z.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(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 i of this.representations.values()){const r=i.segmentReference;if(!Bi(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(i.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:Z.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+v||f<=i+v;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==ut.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===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===ut.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Z.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&&(await ce(o,async function*(){const l=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,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?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=Z.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Ya(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=Z.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&&(await ce(n,async function*(){const u=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Ya(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(Bi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,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:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Bi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.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:R.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)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&D(r)&&(i=Qe((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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=i,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=Z.PARTIALLY_FED,o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,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===ut.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,v=S<r,y=b<=r;if(c.status===Z.DOWNLOADING&&v&&y){c.status=Z.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(g,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?g:this.containerParser.parseFeedableSegmentChunk(g);E!=null&&E.byteLength&&(c.status=Z.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Z.FED,Ao(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===Z.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=Z.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{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&&Bi(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),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(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=Ao(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===Z.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===Z.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===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ui;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ui||(Ui={}));class Kv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new lt,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(ls);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ui.HEADER:Ui.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;let m=r;const S=new Headers;if(n)switch(a){case Ui.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Ui.PARAM:{const M=new URL(m,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),m=M.toString();break}default:z(a)}this.requestQuic&&(m=ii(m));let b=this.abortAllController.signal,v;if(d){const M=new lt;if(v=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{M.abort()}catch(K){ls(K)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(K){ls(K)}b=M.signal}const y=le(),g=yield $i(m,{priority:u,headers:S,signal:b}).catch(ls),E=le();if(!g)return v==null||v.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!g.ok||!g.body)return v==null||v.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!o&&!l)return v==null||v.unsubscribe(),g.arrayBuffer();const[$,L]=g.body.tee(),G=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(L,c));let Q=0,V=new Uint8Array(0),q=!1;const W=M=>{v==null||v.unsubscribe(),q=!0,ls(M)},B=ce(b,async function*({done:M,value:K}){if(Q===0&&this.lastRequestFirstBytes$.next(le()-y),b.aborted){v==null||v.unsubscribe();return}if(!M&&K){const O=new Uint8Array(V.length+K.length);O.set(V),O.set(K,V.length),V=O,Q+=K.byteLength,o==null||o(new DataView(V.buffer),Q),yield G==null?void 0:G.read().then(B,W)}}.bind(this));return yield G==null?void 0:G.read().then(B,W),v==null||v.unsubscribe(),q?null:V.buffer}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==ut.BYTE_RANGE)return 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 S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let g;if(h)g=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;g=new DataView($)}const E=a.parseSegments(g,v,y);return{init:v,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==ut.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case ut.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case ut.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ls=s=>{if(!Ya(s))throw s},za=1e3,cr=(s,e,t)=>t*e+(1-t)*s,Kd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Jv=(s,e,t,i)=>{let r=0,a=t;const n=Kd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class pn{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 T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new wt(`raw_${i}`),this.smoothedSeries$=new wt(`smoothed_${i}`),this.reportedSeries$=new wt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(j(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 Xv extends pn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Zv extends pn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Jv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class eS extends pn{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?cr(this.smoothed,e,this.params.emaAlpha):e}}class qa{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Xv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Zv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new eS({initial:e,label:"liveEdgeDelay",...t})}}const tS=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},ko=["timeupdate","progress","play","seeked","stalled","waiting"];var ot;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ot||(ot={}));let iS=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(ot.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ot.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(ot.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return null;let r;try{r=zv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Me.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)),{...r,representations:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ot.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new wo(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new wo(Me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(za).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+za,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...ko.map(o=>U(this.element,o))).pipe(_(o=>this.element?Qe(this.element.buffered,this.element.currentTime*1e3):0),ve(),ae(o=>!!o),vs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ae(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),tS(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(P(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let v=At.None;if(this.isActiveLowLatency?v=At.ActiveLowLatency:b<f+S&&b>=f?v=At.LiveWithTargetOffset:c!==0&&b<f&&(v=At.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),v===At.LiveForwardBuffering||v===At.LiveWithTargetOffset){const y=o-(f+m),g=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(g-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:g>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=g:$=0,this.manifestUrlString=He(this.manifestUrlString,$,Se.DASH_CMAF_OFFSET_P)}v!==At.None&&v!==At.ActiveLowLatency&&(o=0,this.updateLive())}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ot.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Kv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=qa.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,i,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=He(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(ot.RUNNING),this.subscription.add(H(...ko.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const i={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ot.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:R.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await 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,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class Jd{constructor(e){this.subscription=new ue,this.videoState=new he(Ee.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Ee.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Ee.STOPPED&&(this.videoState.startTransitionTo(Ee.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(Ee.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Ee.STOPPED:this.videoState.startTransitionTo(Ee.READY),this.prepare();return;case Ee.READY:n===p.PAUSED?(this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Ee.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Ee.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Ee.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Ee.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&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(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(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new iS({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ee.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ee.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ee.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===ot.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=jv(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=qv(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&Wv(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=Qv(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===ot.REPRESENTATIOS_READY&&(this.videoState.setState(Ee.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==ot.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Me.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,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:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(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),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.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),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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),It(this.video)}}class sS extends Jd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let rS=class extends zd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Le({interval:Ti(Ha),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Te.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Te.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)})}};class aS extends Jd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Le({interval:Ti(za),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ee.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(Le({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(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Ee.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 $t={};var de;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));const cs=(s,e)=>new fr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class nS{constructor(e){this.subscription=new ue,this.videoState=new he(de.INITIALIZING),this.textTracksManager=new yt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==de.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case de.STOPPED:break;case de.READY:case de.PLAYING:case de.PAUSED:this.stop();break;default:z(t)}break;case p.READY:switch(t){case de.STOPPED:this.prepare();break;case de.READY:case de.PLAYING:case de.PAUSED:break;default:z(t)}break;case p.PLAYING:switch(t){case de.PLAYING:break;case de.STOPPED:this.prepare();break;case de.READY:case de.PAUSED:this.playIfAllowed();break;default:z(t)}break;case p.PAUSED:switch(t){case de.PAUSED:break;case de.STOPPED:this.prepare();break;case de.READY:this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case de.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Rt(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(Ye(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),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||($t.Hls=r.default,$t.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P($t.Hls,"hls.js not loaded"),this.hls=new $t.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(de.STOPPED)}subscribe(){P($t.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Lt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ri(this.video,e.isLooped,i)),this.subscription.add(Dt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(cs(this.hls,$t.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.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(de.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),a(cs(this.hls,$t.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:S,height:b}=c,v=(f=Ki((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:si({width:S,height:b});if(!v)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:m.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(m,{track:g,level:c}),l.push(g),l},[]))),t.availableVideoTracks$),a(cs(this.hls,$t.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,S="internal";l.push({id:h,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(cs(this.hls,$t.Events.LEVEL_LOADING).pipe(_(({url:d})=>Ye(d))),t.hostname$),this.subscription.add(vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=cs(this.hls,$t.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(ae(D)).subscribe(t.currentVideoTrack$,i),this.subscription.add(vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(j(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:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(de.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(de.PLAYING),await Kt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(de.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(de.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const _o="X-Playback-Duration";var Po=async s=>{var e;const t=await $i(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(_o)?parseInt(t.headers.get(_o),10):void 0};const oS=s=>{let e=null;if(s.QUALITY&&(e=Ki(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=si({width:t,height:i})}return e!=null?e:null},Xd=async(s,e=s)=>{var t,i;const n=(await(await $i(s)).text()).split(`
46
+ `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Ei(c[1].split(",").map(E=>E.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=oS(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(L=>parseInt(L,10));E&&$&&(y={width:E,height:$})}const g=new URL(n[++d],e).toString();S&&o.push({id:m,quality:S,url:g,bandwidth:b,size:y,fps:v})}if(h){const f=Ei(h[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;m&&S&&u.push({type:"internal",id:S,label:b,language:S,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var pe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(pe||(pe={}));class dS{constructor(e){var t;this.subscription=new ue,this.videoState=new he(pe.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.liveOffset=new ws,this.manifestStartTime$=new T(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!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(pe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===pe.STOPPED){this.videoState.startTransitionTo(pe.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(pe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===ee.Requested){this.videoState.startTransitionTo(pe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case pe.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed());return;case pe.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case pe.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(pe.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&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case pe.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.INVARIANT,url:this.params.source.url},Xd(He(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:R.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(Ye(this.params.source.url)),this.maxSeekBackTime$=new T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,i,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:(i=n.getState())===null||i===void 0?void 0:i.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,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(pe.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(pe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===pe.READY&&this.videoState.setState(pe.READY),this.videoState.getState()===pe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&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(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===pe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ee.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(ae(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),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$,i));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.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===A.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=He(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),Po(u).then(d=>{var l;if(!j(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(j(c)||!isFinite(c))try{$i(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 S=new URL(m,u).toString();Po(S).then(b=>{j(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class uS{constructor(e){this.subscription=new ue,this.videoState=new he(ge.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=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){i!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===ee.Requested&&this.seek(l.position),i){case ge.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ge.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ge.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.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(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xd(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,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:(i=n.getState())===null||i===void 0?void 0:i.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,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Lt(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(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&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(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ee.Requested&&this.seek(o.position)},i))),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$,i)),!lu()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(H(U(o,"addtrack"),U(o,"removetrack"),U(o,"change"),Ge(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.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(){Kt(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var $e;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})($e||($e={}));class lS{constructor(e){this.subscription=new ue,this.videoState=new he($e.STOPPED),this.trackUrls={},this.textTracksManager=new yt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==$e.STOPPED&&(this.videoState.startTransitionTo($e.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($e.STOPPED),I(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!==$e.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===$e.STOPPED){this.videoState.startTransitionTo($e.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===ee.Requested&&this.seek(c.position),a){case $e.READY:n===p.READY?I(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed());return;case $e.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo($e.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case $e.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState($e.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState($e.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===$e.READY&&this.videoState.setState($e.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&D(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===$e.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(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:i}=this.trackUrls[t];P(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=ii(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Ye(i))}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,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=(i=Object.values(this.trackUrls).find(c=>!yi(c.track.quality)&&Fo(c.track.quality,e)))===null||i===void 0?void 0:i.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&&Ra(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!yi(f.track.quality)&&Vi(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=_i(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 Do=["stun:videostun.mycdn.me:80"],cS=1e3,hS=3,ma=()=>null;class fS{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ma,this.externalStopCallback=ma,this.externalErrorCallback=ma,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Do}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:R.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),cS)}normalizeOptions(e={}){const t={stunServerList:Do,maxRetryNumber:hS,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var me;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(me||(me={}));class pS{constructor(e){this.videoState=new he(me.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==me.STOPPED&&(this.videoState.startTransitionTo(me.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(me.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===me.STOPPED){this.videoState.startTransitionTo(me.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case me.READY:i===p.PAUSED?(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed());return;case me.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case me.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(t)}},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new fS(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),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(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=Lt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===me.READY&&this.videoState.setState(me.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Dt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case me.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case me.READY:break;case me.PAUSED:t.playbackState.setState(p.PAUSED);break;case me.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return z(n.to)}},i)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ye(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:at.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(me.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:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Ro{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 ga,va,Sa,ba,ya,Ta,Ea,$a,Us,Aa,Vs,wa,Hs,ka,Gs,_a,Ys,Pa,zs,Da;const Zd=hr().device===cu.Android,ti=document.createElement("video"),mS='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gS='video/mp4; codecs="hev1.1.6.L93.B0"',eu='video/webm; codecs="vp09.00.10.08"',tu='video/webm; codecs="av01.0.00M.08"',vS='audio/mp4; codecs="mp4a.40.2"',SS='audio/webm; codecs="opus"',xe={mms:!!(window.ManagedMediaSource&&(!((va=(ga=window.ManagedSourceBuffer)===null||ga===void 0?void 0:ga.prototype)===null||va===void 0)&&va.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((ba=(Sa=window.SourceBuffer)===null||Sa===void 0?void 0:Sa.prototype)===null||ba===void 0)&&ba.appendBuffer)),hls:!!(!((ya=ti.canPlayType)===null||ya===void 0)&&ya.call(ti,"application/x-mpegurl")||!((Ta=ti.canPlayType)===null||Ta===void 0)&&Ta.call(ti,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},it={mp4:!!(!((Ea=ti.canPlayType)===null||Ea===void 0)&&Ea.call(ti,"video/mp4")),webm:!!(!(($a=ti.canPlayType)===null||$a===void 0)&&$a.call(ti,"video/webm")),cmaf:!0},Pt={h264:!!(!((Aa=(Us=window.MediaSource||window.ManagedMediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Aa===void 0)&&Aa.call(Us,mS)),h265:!!(!((wa=(Vs=window.MediaSource||window.ManagedMediaSource)===null||Vs===void 0?void 0:Vs.isTypeSupported)===null||wa===void 0)&&wa.call(Vs,gS)),vp9:!!(!((ka=(Hs=window.MediaSource||window.ManagedMediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||ka===void 0)&&ka.call(Hs,eu)),av1:!!(!((_a=(Gs=window.MediaSource||window.ManagedMediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||_a===void 0)&&_a.call(Gs,tu)),aac:!!(!((Pa=(Ys=window.MediaSource||window.ManagedMediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Pa===void 0)&&Pa.call(Ys,vS)),opus:!!(!((Da=(zs=window.MediaSource||window.ManagedMediaSource)===null||zs===void 0?void 0:zs.isTypeSupported)===null||Da===void 0)&&Da.call(zs,SS))},Mi=(Pt.h264||Pt.h265)&&Pt.aac;var ei;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(ei||(ei={}));var Gt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Gt||(Gt={}));let gi;const bS=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:tu}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:eu}})]);gi={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}};try{bS()}catch(s){console.error(s)}const Ts=xe.hls&&it.mp4,yS=()=>Object.keys(Pt).filter(s=>Pt[s]),TS=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return xe.mse&&it.mp4&&Mi;case A.DASH_SEP:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.DASH_WEBM:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.vp9&&Pt.opus;case A.DASH_WEBM_AV1:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.av1&&Pt.opus;case A.DASH_LIVE:return xe.mse&&it.mp4&&Mi;case A.DASH_LIVE_CMAF:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi&&it.cmaf;case A.DASH_ONDEMAND:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.HLS:case A.HLS_ONDEMAND:return Ts||e&&xe.mse&&it.mp4&&Mi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Ts;case A.MPEG:return it.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return xe.webrtc&&xe.ws&&Pt.h264&&(it.mp4||it.webm);default:return z(i)}}),hs=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case ei.VP9:return[e,t];case ei.AV1:return[t,e];case ei.NONE:return[];case ei.SMOOTH:return gi?gi[t].smooth?[t,e]:gi[e].smooth?[e,t]:[t,e]:[e,t];case ei.POWER_EFFICIENT:return gi?gi[t].powerEfficient?[t,e]:gi[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},ES=({webmCodec:s,androidPreferredFormat:e})=>{if(Zd)switch(e){case Gt.MPEG:return[A.MPEG,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Gt.HLS:return[A.HLS,A.HLS_ONDEMAND,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Gt.DASH:return[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Ts?[...hs(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},$S=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(Zd)switch(s){case Gt.DASH:{o=a;break}case Gt.HLS:case Gt.MPEG:{o=n;break}}else Ts?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},Io=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var AS=s=>new fr(e=>{const t=new ue,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(_(({type:d})=>d!==void 0)),n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const wS={cacheDuration:12e4},kS={chunkDuration:5e3,maxParallelRequests:5};class _S{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new C,warning$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=TS([...$S(this.params.tuning),...ES(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>D(e.sources[o]));console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(t);const{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ro(a);const n=[...Io(!0),...Io(!1)];this.chromecastFormatsIterator=new Ro(n.filter(o=>D(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(j(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==ee.None;if(this.params.desiredState.seekState.setState({state:ee.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ue.SCREEN:return this.createScreenProvider(t);case Ue.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new _m({...n,source:o,config:wS})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new sS({...n,source:o}):new dv({...n,source:o})}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new aS({...n,source:o}):new rS({...n,source:o})}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ts||!this.params.tuning.useHlsJs?new uS({...n,source:o}):new nS({...n,source:o})}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new dS({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new lS({...n,source:o})}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Em({...n,source:o,config:{...kS,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new pS({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Lp({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ue.CHROMECAST:Ue.SCREEN}chooseFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ue.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.next();case Ue.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ue.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ue.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return z(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ei(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ue;let t=!1,i=0;const r=le();return e.add(H(this.providerOutput.error$,AS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(a=>({id:`ProviderHangup:${a}`,category:R.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===Ue.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ue.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===R.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,l=u&&(o&&t||!d),c=a.id.includes("partial_metadata"),h=le()-r;l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c&&h<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ue.SCREEN)}})),e}}const PS=5e3,Lo="one_video_throughput",xo="one_video_rtt",Yt=window.navigator.connection,Co=()=>{const s=Yt==null?void 0:Yt.downlink;if(D(s)&&s!==10)return s*1e3},Bo=()=>{const s=Yt==null?void 0:Yt.rtt;if(D(s)&&s!==3e3)return s},Mo=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class gs{constructor(e){var t,i;this.subscription=new ue,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=gs.load(Lo)||(e.useBrowserEstimation?Co():void 0)||PS,a=(i=(t=gs.load(xo))!==null&&t!==void 0?t:e.useBrowserEstimation?Bo():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Mo(r,a,e.rttPenaltyRequestSize)),this.throughput=qa.getSmoothedValue(r,-1,e),this.rtt=qa.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Co();u&&this.throughput.next(u);const d=Bo();D(d)&&this.rtt.next(d)};Yt&&"onchange"in Yt&&this.subscription.add(U(Yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fr.set(Lo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fr.set(xo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>Mo(n,o,e.rttPenaltyRequestSize)),ae(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le();const r=new ue;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!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());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(gs.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=Fr.get(e);if(D(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Oo={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},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:at.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ei.VP9,androidPreferredFormat:Gt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},DS=s=>{var e;return{...hu(s,Oo),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Oo.configName]}};var No=({seekState:s,position$:e})=>H(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===ee.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),ae(D)),e.pipe(ae(()=>s.getState().state===ee.None))),RS=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const IS=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ae(r=>r.length>0),Ae()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class nb{constructor(e={configName:[]}){if(this.subscription=new ue,this.logger=new fu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:ee.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 T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(Zt.NONE),chromecastState$:new T(Ce.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new C,ready$:new C,started$:new C,playing$:new C,paused$:new C,stopped$:new C,willStart$:new C,willResume$:new C,willPause$:new C,willStop$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:im},this.initLogs(),this.tuning=DS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new gu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gs(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=RS(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new _S({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(document,"visibilitychange").pipe(Ae()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ee.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()===Ce.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()===Ce.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(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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 i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return IS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.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 i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(j(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ee.None?void 0:t.position;return D(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(H(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(ae(({from:e})=>e===p.STOPPED),Ae()).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===ee.Requested?this.desiredState.seekState.setState({...n,state:ee.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ee.Applying&&(this.desiredState.seekState.setState({state:ee.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>yi(o)?1:yi(u)?-1:Vi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(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(Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Le({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),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),ve()).subscribe(this.info.volume$)).add(No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(Hi(!0)),e.providerOutput.seekedEvent$.pipe(Hi(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:R.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(Ae(),_(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),_(()=>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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>i.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Ce.CONNECTED?l=Zt.SECOND_SCREEN:u?n?l=Zt.PIP:o?l=Zt.FULLSCREEN:l=Zt.INLINE:l=Zt.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 ue;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=_i(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(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(H(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),tm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>em(i)),this.providerContainer.current$.subscribe(({type:i})=>Ms("provider",i)),t.duration$.subscribe(i=>Ms("duration",i)),t.availableVideoTracks$.pipe(ae(i=>!!i.length),Ae()).subscribe(i=>Ms("tracks",i)),this.events.fatalError$.subscribe(new wt("fatalError")),this.events.managedError$.subscribe(new wt("managedError")),t.position$.subscribe(new wt("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new wt("quality")),this.info.currentBuffer$.subscribe(new wt("buffer")),t.isBuffering$.subscribe(new wt("isBuffering"))].forEach(i=>this.subscription.add(i)),Ms("codecs",yS())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(r)})})};this.subscription.add(H(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const ob=`@vkontakte/videoplayer-core@${pu}`;export{Ce as ChromecastState,Ss as HttpConnectionType,lb as Observable,p as PlaybackState,nb as Player,ob as SDK_VERSION,cb as Subject,hb as Subscription,Zt as Surface,pu as VERSION,fb as ValueSubject,A as VideoFormat,pb as VideoQuality};