@vkontakte/videoplayer-core 2.0.103-dev.620e0c0f.0 → 2.0.103-dev.9b9f4181.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +8 -8
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +8 -8
- package/es2018.esm.js +8 -8
- package/esnext.cjs.js +7 -7
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +7 -7
- package/package.json +2 -2
package/es2018.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.103-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.103-dev.9b9f4181.0
|
|
3
|
+
* Mon, 03 Jun 2024 08:01:27 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-103/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as y,Subject as R,Subscription as ie,isNonNullable as D,ErrorCategory as _,isNullable as Q,fromEvent as C,assertNever as U,merge as N,tap as vi,map as $,observableFrom as Ce,filterChanged as he,assertNonNullable as P,debounce as Ke,getHighestQuality as hd,timeout as fd,getCurrentBrowser as Or,CurrentClientBrowser as Bn,combine as Re,once as Ae,mapTo as Zi,filter as ce,VideoQuality as Pe,now as ne,assertNotEmptyArray as pd,videoSizeToQuality as kt,isInvariantQuality as Pt,isHigher as Xt,isLower as Wi,isHigherOrEqual as Sr,isLowerOrEqual as es,interval as fi,videoQualityToHeight as md,abortable as we,getExponentialDelay as zi,throttle as vd,Observable as Mr,observeElementSize as gd,isIOS as Sd,CurrentClientDevice as bd,safeStorage as Rs,fillWithDefault as yd,Logger as Td}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as tg,Subject as ig,Subscription as sg,ValueSubject as rg,VideoQuality as ag}from"@vkontakte/videoplayer-shared/es2018.esm.js";const Ed="2.0.103-dev.620e0c0f.0";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var ye;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ye||(ye={}));var ge;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ge||(ge={}));var br;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(br||(br={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var ht;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(ht||(ht={}));var $d=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Ad{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ge.NOT_AVAILABLE),this.errorEvent$=new R,this.realCastState$=new y(ge.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=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||$d("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(C(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return U(r.sessionState)}})).add(N(C(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Ce([s.getCastState()])).pipe(he(),$(wd),vi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ge.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(Q(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===ge.CONNECTED?D(this.connection$.getValue())?ge.CONNECTED:ge.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const wd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return U(i)}};var Is=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Br(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var rt=function(i){try{return!!i()}catch(e){return!0}},kd=rt,ls=!kd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Nn=ls,Fn=Function.prototype,yr=Fn.call,Pd=Nn&&Fn.bind.bind(yr,yr),at=Nn?Pd:function(i){return function(){return yr.apply(i,arguments)}},Vn=at,Dd=Vn({}.toString),Ld=Vn("".slice),us=function(i){return Ld(Dd(i),8,-1)},xd=at,_d=rt,Rd=us,Cs=Object,Id=xd("".split),Cd=_d(function(){return!Cs("z").propertyIsEnumerable(0)})?function(i){return Rd(i)=="String"?Id(i,""):Cs(i)}:Cs,cs=function(i){return i==null},Od=cs,Md=TypeError,Nr=function(i){if(Od(i))throw Md("Can't call method on "+i);return i},Bd=Cd,Nd=Nr,yi=function(i){return Bd(Nd(i))},ii={},_i=function(i){return i&&i.Math==Math&&i},Ve=_i(typeof globalThis=="object"&&globalThis)||_i(typeof window=="object"&&window)||_i(typeof self=="object"&&self)||_i(typeof Is=="object"&&Is)||function(){return this}()||Is||Function("return this")(),Tr=typeof document=="object"&&document.all,Fd=typeof Tr=="undefined"&&Tr!==void 0,Un={all:Tr,IS_HTMLDDA:Fd},Hn=Un,Vd=Hn.all,Oe=Hn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Vd}:function(i){return typeof i=="function"},Ud=Ve,Hd=Oe,ma=Ud.WeakMap,Gd=Hd(ma)&&/native code/.test(String(ma)),va=Oe,Gn=Un,Yd=Gn.all,Lt=Gn.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:va(i)||i===Yd}:function(i){return typeof i=="object"?i!==null:va(i)},qd=rt,xt=!qd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),si={},jd=Ve,ga=Lt,Er=jd.document,Wd=ga(Er)&&ga(Er.createElement),Yn=function(i){return Wd?Er.createElement(i):{}},zd=xt,Qd=rt,Kd=Yn,qn=!zd&&!Qd(function(){return Object.defineProperty(Kd("div"),"a",{get:function(){return 7}}).a!=7}),Jd=xt,Xd=rt,jn=Jd&&Xd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Zd=Lt,el=String,tl=TypeError,_t=function(i){if(Zd(i))return i;throw tl(el(i)+" is not an object")},il=ls,Ri=Function.prototype.call,nt=il?Ri.bind(Ri):function(){return Ri.apply(Ri,arguments)},Fr={},Os=Fr,Ms=Ve,sl=Oe,Sa=function(i){return sl(i)?i:void 0},Vr=function(i,e){return arguments.length<2?Sa(Os[i])||Sa(Ms[i]):Os[i]&&Os[i][e]||Ms[i]&&Ms[i][e]},rl=at,Ur=rl({}.isPrototypeOf),al=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wn=Ve,Bs=al,ba=Wn.process,ya=Wn.Deno,Ta=ba&&ba.versions||ya&&ya.version,Ea=Ta&&Ta.v8,Ne,ts;Ea&&(Ne=Ea.split("."),ts=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!ts&&Bs&&(Ne=Bs.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Bs.match(/Chrome\/(\d+)/),Ne&&(ts=+Ne[1])));var nl=ts,$a=nl,ol=rt,dl=Ve,ll=dl.String,zn=!!Object.getOwnPropertySymbols&&!ol(function(){var i=Symbol();return!ll(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&$a&&$a<41}),ul=zn,Qn=ul&&!Symbol.sham&&typeof Symbol.iterator=="symbol",cl=Vr,hl=Oe,fl=Ur,pl=Qn,ml=Object,Kn=pl?function(i){return typeof i=="symbol"}:function(i){var e=cl("Symbol");return hl(e)&&fl(e.prototype,ml(i))},vl=String,Hr=function(i){try{return vl(i)}catch(e){return"Object"}},gl=Oe,Sl=Hr,bl=TypeError,Gr=function(i){if(gl(i))return i;throw bl(Sl(i)+" is not a function")},yl=Gr,Tl=cs,hs=function(i,e){var t=i[e];return Tl(t)?void 0:yl(t)},Ns=nt,Fs=Oe,Vs=Lt,El=TypeError,$l=function(i,e){var t,s;if(e==="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i))||Fs(t=i.valueOf)&&!Vs(s=Ns(t,i))||e!=="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i)))return s;throw El("Can't convert object to primitive value")},Jn={exports:{}},Aa=Ve,Al=Object.defineProperty,wl=function(i,e){try{Al(Aa,i,{value:e,configurable:!0,writable:!0})}catch(t){Aa[i]=e}return e},kl=Ve,Pl=wl,wa="__core-js_shared__",Dl=kl[wa]||Pl(wa,{}),Xn=Dl,ka=Xn;(Jn.exports=function(i,e){return ka[i]||(ka[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Zn=Jn.exports,Ll=Nr,xl=Object,fs=function(i){return xl(Ll(i))},_l=at,Rl=fs,Il=_l({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return Il(Rl(e),t)},Cl=at,Ol=0,Ml=Math.random(),Bl=Cl(1 .toString),eo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Bl(++Ol+Ml,36)},Nl=Ve,Fl=Zn,Pa=ot,Vl=eo,Ul=zn,Hl=Qn,Kt=Nl.Symbol,Us=Fl("wks"),Gl=Hl?Kt.for||Kt:Kt&&Kt.withoutSetter||Vl,Ue=function(i){return Pa(Us,i)||(Us[i]=Ul&&Pa(Kt,i)?Kt[i]:Gl("Symbol."+i)),Us[i]},Yl=nt,Da=Lt,La=Kn,ql=hs,jl=$l,Wl=Ue,zl=TypeError,Ql=Wl("toPrimitive"),Kl=function(i,e){if(!Da(i)||La(i))return i;var t=ql(i,Ql),s;if(t){if(e===void 0&&(e="default"),s=Yl(t,i,e),!Da(s)||La(s))return s;throw zl("Can't convert object to primitive value")}return e===void 0&&(e="number"),jl(i,e)},Jl=Kl,Xl=Kn,Yr=function(i){var e=Jl(i,"string");return Xl(e)?e:e+""},Zl=xt,eu=qn,tu=jn,Ii=_t,xa=Yr,iu=TypeError,Hs=Object.defineProperty,su=Object.getOwnPropertyDescriptor,Gs="enumerable",Ys="configurable",qs="writable";si.f=Zl?tu?function(e,t,s){if(Ii(e),t=xa(t),Ii(s),typeof e=="function"&&t==="prototype"&&"value"in s&&qs in s&&!s[qs]){var r=su(e,t);r&&r[qs]&&(e[t]=s.value,s={configurable:Ys in s?s[Ys]:r[Ys],enumerable:Gs in s?s[Gs]:r[Gs],writable:!1})}return Hs(e,t,s)}:Hs:function(e,t,s){if(Ii(e),t=xa(t),Ii(s),eu)try{return Hs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw iu("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var ps=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},ru=xt,au=si,nu=ps,Ti=ru?function(i,e,t){return au.f(i,e,nu(1,t))}:function(i,e,t){return i[e]=t,i},ou=Zn,du=eo,_a=ou("keys"),qr=function(i){return _a[i]||(_a[i]=du(i))},jr={},lu=Gd,to=Ve,uu=Lt,cu=Ti,js=ot,Ws=Xn,hu=qr,fu=jr,Ra="Object already initialized",$r=to.TypeError,pu=to.WeakMap,is,gi,ss,mu=function(i){return ss(i)?gi(i):is(i,{})},vu=function(i){return function(e){var t;if(!uu(e)||(t=gi(e)).type!==i)throw $r("Incompatible receiver, "+i+" required");return t}};if(lu||Ws.state){var Ye=Ws.state||(Ws.state=new pu);Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,is=function(i,e){if(Ye.has(i))throw $r(Ra);return e.facade=i,Ye.set(i,e),e},gi=function(i){return Ye.get(i)||{}},ss=function(i){return Ye.has(i)}}else{var Gt=hu("state");fu[Gt]=!0,is=function(i,e){if(js(i,Gt))throw $r(Ra);return e.facade=i,cu(i,Gt,e),e},gi=function(i){return js(i,Gt)?i[Gt]:{}},ss=function(i){return js(i,Gt)}}var gu={set:is,get:gi,has:ss,enforce:mu,getterFor:vu},Su=ls,io=Function.prototype,Ia=io.apply,Ca=io.call,bu=typeof Reflect=="object"&&Reflect.apply||(Su?Ca.bind(Ia):function(){return Ca.apply(Ia,arguments)}),yu=us,Tu=at,so=function(i){if(yu(i)==="Function")return Tu(i)},ro={},ao={},no={}.propertyIsEnumerable,oo=Object.getOwnPropertyDescriptor,Eu=oo&&!no.call({1:2},1);ao.f=Eu?function(e){var t=oo(this,e);return!!t&&t.enumerable}:no;var $u=xt,Au=nt,wu=ao,ku=ps,Pu=yi,Du=Yr,Lu=ot,xu=qn,Oa=Object.getOwnPropertyDescriptor;ro.f=$u?Oa:function(e,t){if(e=Pu(e),t=Du(t),xu)try{return Oa(e,t)}catch(s){}if(Lu(e,t))return ku(!Au(wu.f,e,t),e[t])};var _u=rt,Ru=Oe,Iu=/#|\.prototype\./,Ei=function(i,e){var t=Ou[Cu(i)];return t==Bu?!0:t==Mu?!1:Ru(e)?_u(e):!!e},Cu=Ei.normalize=function(i){return String(i).replace(Iu,".").toLowerCase()},Ou=Ei.data={},Mu=Ei.NATIVE="N",Bu=Ei.POLYFILL="P",Nu=Ei,Ma=so,Fu=Gr,Vu=ls,Uu=Ma(Ma.bind),lo=function(i,e){return Fu(i),e===void 0?i:Vu?Uu(i,e):function(){return i.apply(e,arguments)}},Ci=Ve,Hu=bu,Gu=so,Yu=Oe,qu=ro.f,ju=Nu,Yt=Fr,Wu=lo,qt=Ti,Ba=ot,zu=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Hu(i,this,arguments)};return e.prototype=i.prototype,e},ms=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Ci:r?Ci[t]:(Ci[t]||{}).prototype,o=s?Yt:Yt[t]||qt(Yt,t,{})[t],u=o.prototype,d,l,c,h,f,g,m,v,S;for(h in e)d=ju(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Ba(n,h),g=o[h],l&&(i.dontCallGetSet?(S=qu(n,h),m=S&&S.value):m=n[h]),f=l&&m?m:e[h],!(l&&typeof g==typeof f)&&(i.bind&&l?v=Wu(f,Ci):i.wrap&&l?v=zu(f):a&&Yu(f)?v=Gu(f):v=f,(i.sham||f&&f.sham||g&&g.sham)&&qt(v,"sham",!0),qt(o,h,v),a&&(c=t+"Prototype",Ba(Yt,c)||qt(Yt,c,{}),qt(Yt[c],h,f),i.real&&u&&(d||!u[h])&&qt(u,h,f)))},Ar=xt,Qu=ot,uo=Function.prototype,Ku=Ar&&Object.getOwnPropertyDescriptor,Wr=Qu(uo,"name"),Ju=Wr&&function(){}.name==="something",Xu=Wr&&(!Ar||Ar&&Ku(uo,"name").configurable),Zu={EXISTS:Wr,PROPER:Ju,CONFIGURABLE:Xu},co={},ec=Math.ceil,tc=Math.floor,ic=Math.trunc||function(e){var t=+e;return(t>0?tc:ec)(t)},sc=ic,zr=function(i){var e=+i;return e!==e||e===0?0:sc(e)},rc=zr,ac=Math.max,nc=Math.min,oc=function(i,e){var t=rc(i);return t<0?ac(t+e,0):nc(t,e)},dc=zr,lc=Math.min,uc=function(i){return i>0?lc(dc(i),9007199254740991):0},cc=uc,Qr=function(i){return cc(i.length)},hc=yi,fc=oc,pc=Qr,Na=function(i){return function(e,t,s){var r=hc(e),a=pc(r),n=fc(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},mc={includes:Na(!0),indexOf:Na(!1)},vc=at,zs=ot,gc=yi,Sc=mc.indexOf,bc=jr,Fa=vc([].push),yc=function(i,e){var t=gc(i),s=0,r=[],a;for(a in t)!zs(bc,a)&&zs(t,a)&&Fa(r,a);for(;e.length>s;)zs(t,a=e[s++])&&(~Sc(r,a)||Fa(r,a));return r},ho=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Tc=yc,Ec=ho,$c=Object.keys||function(e){return Tc(e,Ec)},Ac=xt,wc=jn,kc=si,Pc=_t,Dc=yi,Lc=$c;co.f=Ac&&!wc?Object.defineProperties:function(e,t){Pc(e);for(var s=Dc(t),r=Lc(t),a=r.length,n=0,o;a>n;)kc.f(e,o=r[n++],s[o]);return e};var xc=Vr,_c=xc("document","documentElement"),Rc=_t,Ic=co,Va=ho,Cc=jr,Oc=_c,Mc=Yn,Bc=qr,Ua=">",Ha="<",wr="prototype",kr="script",fo=Bc("IE_PROTO"),Qs=function(){},po=function(i){return Ha+kr+Ua+i+Ha+"/"+kr+Ua},Ga=function(i){i.write(po("")),i.close();var e=i.parentWindow.Object;return i=null,e},Nc=function(){var i=Mc("iframe"),e="java"+kr+":",t;return i.style.display="none",Oc.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(po("document.F=Object")),t.close(),t.F},Oi,Qi=function(){try{Oi=new ActiveXObject("htmlfile")}catch(e){}Qi=typeof document!="undefined"?document.domain&&Oi?Ga(Oi):Nc():Ga(Oi);for(var i=Va.length;i--;)delete Qi[wr][Va[i]];return Qi()};Cc[fo]=!0;var mo=Object.create||function(e,t){var s;return e!==null?(Qs[wr]=Rc(e),s=new Qs,Qs[wr]=null,s[fo]=e):s=Qi(),t===void 0?s:Ic.f(s,t)},Fc=rt,Vc=!Fc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Uc=ot,Hc=Oe,Gc=fs,Yc=qr,qc=Vc,Ya=Yc("IE_PROTO"),Pr=Object,jc=Pr.prototype,vo=qc?Pr.getPrototypeOf:function(i){var e=Gc(i);if(Uc(e,Ya))return e[Ya];var t=e.constructor;return Hc(t)&&e instanceof t?t.prototype:e instanceof Pr?jc:null},Wc=Ti,go=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Wc(i,e,t),i},zc=rt,Qc=Oe,Kc=Lt,Jc=mo,qa=vo,Xc=go,Zc=Ue,Dr=Zc("iterator"),So=!1,it,Ks,Js;[].keys&&(Js=[].keys(),"next"in Js?(Ks=qa(qa(Js)),Ks!==Object.prototype&&(it=Ks)):So=!0);var eh=!Kc(it)||zc(function(){var i={};return it[Dr].call(i)!==i});eh?it={}:it=Jc(it);Qc(it[Dr])||Xc(it,Dr,function(){return this});var bo={IteratorPrototype:it,BUGGY_SAFARI_ITERATORS:So},th=Ue,ih=th("toStringTag"),yo={};yo[ih]="z";var Kr=String(yo)==="[object z]",sh=Kr,rh=Oe,Ki=us,ah=Ue,nh=ah("toStringTag"),oh=Object,dh=Ki(function(){return arguments}())=="Arguments",lh=function(i,e){try{return i[e]}catch(t){}},vs=sh?Ki:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=lh(e=oh(i),nh))=="string"?t:dh?Ki(e):(s=Ki(e))=="Object"&&rh(e.callee)?"Arguments":s},uh=Kr,ch=vs,hh=uh?{}.toString:function(){return"[object "+ch(this)+"]"},fh=Kr,ph=si.f,mh=Ti,vh=ot,gh=hh,Sh=Ue,ja=Sh("toStringTag"),To=function(i,e,t,s){if(i){var r=t?i:i.prototype;vh(r,ja)||ph(r,ja,{configurable:!0,value:e}),s&&!fh&&mh(r,"toString",gh)}},bh=bo.IteratorPrototype,yh=mo,Th=ps,Eh=To,$h=ii,Ah=function(){return this},wh=function(i,e,t,s){var r=e+" Iterator";return i.prototype=yh(bh,{next:Th(+!s,t)}),Eh(i,r,!1,!0),$h[r]=Ah,i},kh=ms,Ph=nt,Eo=Zu,Dh=wh,Lh=vo,xh=To,Wa=go,_h=Ue,za=ii,$o=bo,Rh=Eo.PROPER;Eo.CONFIGURABLE;$o.IteratorPrototype;var Mi=$o.BUGGY_SAFARI_ITERATORS,Xs=_h("iterator"),Qa="keys",Bi="values",Ka="entries",Ih=function(){return this},Ch=function(i,e,t,s,r,a,n){Dh(t,e,s);var o=function(S){if(S===r&&h)return h;if(!Mi&&S in l)return l[S];switch(S){case Qa:return function(){return new t(this,S)};case Bi:return function(){return new t(this,S)};case Ka:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[Xs]||l["@@iterator"]||r&&l[r],h=!Mi&&c||o(r),f=e=="Array"&&l.entries||c,g,m,v;if(f&&(g=Lh(f.call(new i)),g!==Object.prototype&&g.next&&(xh(g,u,!0,!0),za[u]=Ih)),Rh&&r==Bi&&c&&c.name!==Bi&&(d=!0,h=function(){return Ph(c,this)}),r)if(m={values:o(Bi),keys:a?h:o(Qa),entries:o(Ka)},n)for(v in m)(Mi||d||!(v in l))&&Wa(l,v,m[v]);else kh({target:e,proto:!0,forced:Mi||d},m);return n&&l[Xs]!==h&&Wa(l,Xs,h,{name:r}),za[e]=h,m},Oh=function(i,e){return{value:i,done:e}},Mh=yi,Ja=ii,Ao=gu;si.f;var Bh=Ch,Ni=Oh,wo="Array Iterator",Nh=Ao.set,Fh=Ao.getterFor(wo);Bh(Array,"Array",function(i,e){Nh(this,{type:wo,target:Mh(i),index:0,kind:e})},function(){var i=Fh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Ni(void 0,!0)):t=="keys"?Ni(s,!1):t=="values"?Ni(e[s],!1):Ni([s,e[s]],!1)},"values");Ja.Arguments=Ja.Array;var Vh=Ue,Uh=ii,Hh=Vh("iterator"),Gh=Array.prototype,Yh=function(i){return i!==void 0&&(Uh.Array===i||Gh[Hh]===i)},qh=vs,Xa=hs,jh=cs,Wh=ii,zh=Ue,Qh=zh("iterator"),ko=function(i){if(!jh(i))return Xa(i,Qh)||Xa(i,"@@iterator")||Wh[qh(i)]},Kh=nt,Jh=Gr,Xh=_t,Zh=Hr,ef=ko,tf=TypeError,sf=function(i,e){var t=arguments.length<2?ef(i):e;if(Jh(t))return Xh(Kh(t,i));throw tf(Zh(i)+" is not iterable")},rf=nt,Za=_t,af=hs,nf=function(i,e,t){var s,r;Za(i);try{if(s=af(i,"return"),!s){if(e==="throw")throw t;return t}s=rf(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Za(s),t},of=lo,df=nt,lf=_t,uf=Hr,cf=Yh,hf=Qr,en=Ur,ff=sf,pf=ko,tn=nf,mf=TypeError,Ji=function(i,e){this.stopped=i,this.result=e},sn=Ji.prototype,vf=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=of(e,s),d,l,c,h,f,g,m,v=function(E){return d&&tn(d,"normal",E),new Ji(!0,E)},S=function(E){return r?(lf(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(a)d=i.iterator;else if(n)d=i;else{if(l=pf(i),!l)throw mf(uf(i)+" is not iterable");if(cf(l)){for(c=0,h=hf(i);h>c;c++)if(f=S(i[c]),f&&en(sn,f))return f;return new Ji(!1)}d=ff(i,l)}for(g=a?i.next:d.next;!(m=df(g,d)).done;){try{f=S(m.value)}catch(E){tn(d,"throw",E)}if(typeof f=="object"&&f&&en(sn,f))return f}return new Ji(!1)},gf=Yr,Sf=si,bf=ps,yf=function(i,e,t){var s=gf(e);s in i?Sf.f(i,s,bf(0,t)):i[s]=t},Tf=ms,Ef=vf,$f=yf;Tf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ef(e,function(s,r){$f(t,s,r)},{AS_ENTRIES:!0}),t}});var Af=Fr,wf=Af.Object.fromEntries,kf={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},Pf=kf,Df=Ve,Lf=vs,xf=Ti,rn=ii,_f=Ue,an=_f("toStringTag");for(var Zs in Pf){var nn=Df[Zs],er=nn&&nn.prototype;er&&Lf(er)!==an&&xf(er,an,Zs),rn[Zs]=rn.Array}var Rf=wf,If=Rf,Cf=If,Of=Cf,rs=Br(Of),me;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(me||(me={}));var Fe=(i,e=0,t=me.OFFSET_P)=>{switch(t){case me.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case me.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:U(t)}return i};const on=(i,e)=>{var t;switch(e){case me.OFFSET_P:return NaN;case me.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:U(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ue{constructor(e){this.transitionStarted$=new R,this.transitionEnded$=new R,this.transitionUpdated$=new R,this.forceChanged$=new R,this.stateChangeStarted$=N(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=N(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||D(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Mf=i=>{switch(i){case b.MPEG:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return U(i)}};var V;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Bf=5,Nf=5,Ff=500,dn=7e3;class Vf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new ue(V.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==V.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PLAYING:{switch(s){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PAUSED:{switch(s){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}default:U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Mf(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 ie;this.subscription.add(e),this.subscription.add(N(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 R;e.add(r.pipe(Ke(Ff)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-a)>Bf)&&r.next(o),a=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(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<Nf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:U(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=N(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===V.READY&&this.videoState.setState(V.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const l=s[e];P(l);const c=hd(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=s[e];P(l),r=Fe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(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 s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(fd(dn).subscribe(()=>a(`timeout(${dn})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Jr=i=>{i.removeAttribute("src"),i.load()},Uf=i=>{try{i.pause(),i.playbackRate=0,Jr(i),i.remove()}catch(e){console.error(e)}};class Hf{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 Lr=window.WeakMap?new WeakMap:new Hf,Rt=i=>{let e=i.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),i.appendChild(e)),Lr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=i=>{const e=Lr.get(i);Lr.delete(i),e?Jr(i):Uf(i)},et=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=Q(r),d=new ie;return r&&d.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},$i=(i,e,t)=>et(e,()=>i.loop,s=>{D(s)&&(i.loop=s)},{onError:t}),Ct=(i,e,t,s)=>et(e,()=>({muted:i.muted,volume:i.volume}),r=>{D(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),ri=(i,e,t,s)=>et(e,()=>i.playbackRate,r=>{D(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Gf=i=>["__",i.language,i.label].join("|"),Yf=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class mt{constructor(){this.available$=new R,this.current$=new y(void 0),this.error$=new R,this.subscription=new ie,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(et(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(et(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(et(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(et(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(C(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(N(C(e,"addtrack"),C(e,"removetrack"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(N(C(e,"change"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(C(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(C(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;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(mt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:Gf(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!Yf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Xr{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 Po=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},ln=i=>{const e=Po(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},qf=i=>{const e=Po(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},jf=3;var Wf=(i,e,t=jf)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const Ot=i=>{const e=A=>C(i,A).pipe(Zi(void 0)),s=N(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>C(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),he()),r=N(C(i,"progress"),C(i,"timeupdate")).pipe($(()=>Wf(i.buffered,i.currentTime))),n=Or().browser===Bn.Safari?Re({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(Zi(void 0)):e("playing"),o=C(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=C(i,"ratechange").pipe($(()=>i.playbackRate)),d=C(i,"error").pipe(ce(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),l=C(i,"timeupdate").pipe($(()=>i.currentTime)),c=new R,h=.3;let f;l.subscribe(A=>{i.loop&&D(f)&&D(A)&&f>=i.duration-h&&A<=h&&c.next(f),f=A});const g=C(i,"enterpictureinpicture"),m=C(i,"leavepictureinpicture"),v=new y(qf(i));g.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new y(ln(i));return C(i,"fullscreenchange").pipe($(()=>ln(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ce(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:C(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}};var gs=i=>{switch(i){case"mobile":return Pe.Q_144P;case"lowest":return Pe.Q_240P;case"low":return Pe.Q_360P;case"sd":case"medium":return Pe.Q_480P;case"hd":case"high":return Pe.Q_720P;case"fullhd":case"full":return Pe.Q_1080P;case"quadhd":case"quad":return Pe.Q_1440P;case"ultrahd":case"ultra":return Pe.Q_2160P}},zf=ms,Qf=fs,Kf=Qr,Jf=zr;zf({target:"Array",proto:!0},{at:function(e){var t=Qf(this),s=Kf(t),r=Jf(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var Xf=Vr,Do=Xf,Zf=Do,ep=Zf("Array","at"),tp=ep,ip=tp,sp=ip,rp=sp,Ze=Br(rp);let Zr=!1,tt={};const ap=i=>{Zr=i},np=()=>{tt={}},op=i=>{i(tt)},Fi=(i,e)=>{var t;Zr&&(tt.meta=(t=tt.meta)!==null&&t!==void 0?t:{},tt.meta[i]=e)};class We{constructor(e){this.name=e}next(e){var t,s;if(!Zr)return;tt.series=(t=tt.series)!==null&&t!==void 0?t:{};const r=(s=tt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),tt.series[this.name]=r}}var At;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(At||(At={}));const dp=new We("best_bitrate"),lp=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class up{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const cp='Assertion "ABR Tracks is empty array" failed',Ss=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,g,m,v;pd(i,cp);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&kt(E),w=s.considerPlaybackRate&&D(o)?o:1,k=i.filter(B=>!Pt(B.quality)).sort((B,x)=>Xt(B.quality,x.quality)?-1:1),q=(f=Ze(k,-1))===null||f===void 0?void 0:f.quality,j=(g=Ze(k,0))===null||g===void 0?void 0:g.quality,K=Q(r)||D(r.min)&&D(r.max)&&Wi(r.max,r.min)||D(r.min)&&j&&Xt(r.min,j)||D(r.max)&&q&&Wi(r.max,q),G=w*lp(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),J={},M=k.filter(B=>(A?Wi(B.quality,A):!0)?(D(t)&&isFinite(t)&&D(B.bitrate)?t-a>=B.bitrate*G:!0)?s.lazyQualitySwitch&&D(s.minBufferToSwitchUp)&&u&&!Pt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Xt(B.quality,u.quality)?(J[B.quality]=At.Buffer,!1):!!l&&Sr(B.quality,l)?(J[B.quality]=At.DroppedFramesLimit,!1):K||(Q(r.max)||es(B.quality,r.max))&&(Q(r.min)||Sr(B.quality,r.min))?!0:(J[B.quality]=At.FitsQualityLimits,!1):(J[B.quality]=At.FitsThroughput,!1):(J[B.quality]=At.FitsContainer,!1))[0];M&&M.bitrate&&dp.next(M.bitrate);const I=(m=M!=null?M:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];I.quality!==((v=d==null?void 0:d.last)===null||v===void 0?void 0:v.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as y,Subject as R,Subscription as ie,isNonNullable as D,ErrorCategory as _,isNullable as Q,fromEvent as C,assertNever as U,merge as N,tap as gi,map as $,observableFrom as Ce,filterChanged as he,assertNonNullable as P,debounce as Ke,getHighestQuality as fd,timeout as pd,getCurrentBrowser as Mr,CurrentClientBrowser as Nn,combine as Re,once as Ae,mapTo as es,filter as ce,VideoQuality as Pe,now as ne,assertNotEmptyArray as md,videoSizeToQuality as kt,isInvariantQuality as Pt,isHigher as Xt,isLower as zi,isHigherOrEqual as br,isLowerOrEqual as ts,interval as pi,Observable as Br,videoQualityToHeight as vd,abortable as we,getExponentialDelay as Qi,throttle as gd,observeElementSize as Sd,isIOS as bd,CurrentClientDevice as yd,safeStorage as Is,fillWithDefault as Td,Logger as Ed}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as tg,Subject as ig,Subscription as sg,ValueSubject as rg,VideoQuality as ag}from"@vkontakte/videoplayer-shared/es2018.esm.js";const $d="2.0.103-dev.9b9f4181.0";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var ye;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ye||(ye={}));var ge;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ge||(ge={}));var yr;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(yr||(yr={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var ht;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(ht||(ht={}));var Ad=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class wd{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ge.NOT_AVAILABLE),this.errorEvent$=new R,this.realCastState$=new y(ge.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=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||Ad("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(C(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return U(r.sessionState)}})).add(N(C(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Ce([s.getCastState()])).pipe(he(),$(kd),gi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ge.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const l=s.getCurrentSession();P(l);const d=l.getCastDevice(),u=(a=l.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(Q(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ge.CONNECTED?D(this.connection$.getValue())?ge.CONNECTED:ge.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const kd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return U(i)}};var Cs=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Nr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var rt=function(i){try{return!!i()}catch(e){return!0}},Pd=rt,us=!Pd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Fn=us,Vn=Function.prototype,Tr=Vn.call,Dd=Fn&&Vn.bind.bind(Tr,Tr),at=Fn?Dd:function(i){return function(){return Tr.apply(i,arguments)}},Un=at,Ld=Un({}.toString),xd=Un("".slice),cs=function(i){return xd(Ld(i),8,-1)},_d=at,Rd=rt,Id=cs,Os=Object,Cd=_d("".split),Od=Rd(function(){return!Os("z").propertyIsEnumerable(0)})?function(i){return Id(i)=="String"?Cd(i,""):Os(i)}:Os,hs=function(i){return i==null},Md=hs,Bd=TypeError,Fr=function(i){if(Md(i))throw Bd("Can't call method on "+i);return i},Nd=Od,Fd=Fr,Ti=function(i){return Nd(Fd(i))},ii={},Ri=function(i){return i&&i.Math==Math&&i},Ve=Ri(typeof globalThis=="object"&&globalThis)||Ri(typeof window=="object"&&window)||Ri(typeof self=="object"&&self)||Ri(typeof Cs=="object"&&Cs)||function(){return this}()||Cs||Function("return this")(),Er=typeof document=="object"&&document.all,Vd=typeof Er=="undefined"&&Er!==void 0,Hn={all:Er,IS_HTMLDDA:Vd},Gn=Hn,Ud=Gn.all,Oe=Gn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Ud}:function(i){return typeof i=="function"},Hd=Ve,Gd=Oe,va=Hd.WeakMap,Yd=Gd(va)&&/native code/.test(String(va)),ga=Oe,Yn=Hn,jd=Yn.all,Lt=Yn.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ga(i)||i===jd}:function(i){return typeof i=="object"?i!==null:ga(i)},qd=rt,xt=!qd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),si={},Wd=Ve,Sa=Lt,$r=Wd.document,zd=Sa($r)&&Sa($r.createElement),jn=function(i){return zd?$r.createElement(i):{}},Qd=xt,Kd=rt,Jd=jn,qn=!Qd&&!Kd(function(){return Object.defineProperty(Jd("div"),"a",{get:function(){return 7}}).a!=7}),Xd=xt,Zd=rt,Wn=Xd&&Zd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),el=Lt,tl=String,il=TypeError,_t=function(i){if(el(i))return i;throw il(tl(i)+" is not an object")},sl=us,Ii=Function.prototype.call,nt=sl?Ii.bind(Ii):function(){return Ii.apply(Ii,arguments)},Vr={},Ms=Vr,Bs=Ve,rl=Oe,ba=function(i){return rl(i)?i:void 0},Ur=function(i,e){return arguments.length<2?ba(Ms[i])||ba(Bs[i]):Ms[i]&&Ms[i][e]||Bs[i]&&Bs[i][e]},al=at,Hr=al({}.isPrototypeOf),nl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zn=Ve,Ns=nl,ya=zn.process,Ta=zn.Deno,Ea=ya&&ya.versions||Ta&&Ta.version,$a=Ea&&Ea.v8,Ne,is;$a&&(Ne=$a.split("."),is=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!is&&Ns&&(Ne=Ns.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Ns.match(/Chrome\/(\d+)/),Ne&&(is=+Ne[1])));var ol=is,Aa=ol,dl=rt,ll=Ve,ul=ll.String,Qn=!!Object.getOwnPropertySymbols&&!dl(function(){var i=Symbol();return!ul(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Aa&&Aa<41}),cl=Qn,Kn=cl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",hl=Ur,fl=Oe,pl=Hr,ml=Kn,vl=Object,Jn=ml?function(i){return typeof i=="symbol"}:function(i){var e=hl("Symbol");return fl(e)&&pl(e.prototype,vl(i))},gl=String,Gr=function(i){try{return gl(i)}catch(e){return"Object"}},Sl=Oe,bl=Gr,yl=TypeError,Yr=function(i){if(Sl(i))return i;throw yl(bl(i)+" is not a function")},Tl=Yr,El=hs,fs=function(i,e){var t=i[e];return El(t)?void 0:Tl(t)},Fs=nt,Vs=Oe,Us=Lt,$l=TypeError,Al=function(i,e){var t,s;if(e==="string"&&Vs(t=i.toString)&&!Us(s=Fs(t,i))||Vs(t=i.valueOf)&&!Us(s=Fs(t,i))||e!=="string"&&Vs(t=i.toString)&&!Us(s=Fs(t,i)))return s;throw $l("Can't convert object to primitive value")},Xn={exports:{}},wa=Ve,wl=Object.defineProperty,kl=function(i,e){try{wl(wa,i,{value:e,configurable:!0,writable:!0})}catch(t){wa[i]=e}return e},Pl=Ve,Dl=kl,ka="__core-js_shared__",Ll=Pl[ka]||Dl(ka,{}),Zn=Ll,Pa=Zn;(Xn.exports=function(i,e){return Pa[i]||(Pa[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,xl=Fr,_l=Object,ps=function(i){return _l(xl(i))},Rl=at,Il=ps,Cl=Rl({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return Cl(Il(e),t)},Ol=at,Ml=0,Bl=Math.random(),Nl=Ol(1 .toString),to=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Nl(++Ml+Bl,36)},Fl=Ve,Vl=eo,Da=ot,Ul=to,Hl=Qn,Gl=Kn,Kt=Fl.Symbol,Hs=Vl("wks"),Yl=Gl?Kt.for||Kt:Kt&&Kt.withoutSetter||Ul,Ue=function(i){return Da(Hs,i)||(Hs[i]=Hl&&Da(Kt,i)?Kt[i]:Yl("Symbol."+i)),Hs[i]},jl=nt,La=Lt,xa=Jn,ql=fs,Wl=Al,zl=Ue,Ql=TypeError,Kl=zl("toPrimitive"),Jl=function(i,e){if(!La(i)||xa(i))return i;var t=ql(i,Kl),s;if(t){if(e===void 0&&(e="default"),s=jl(t,i,e),!La(s)||xa(s))return s;throw Ql("Can't convert object to primitive value")}return e===void 0&&(e="number"),Wl(i,e)},Xl=Jl,Zl=Jn,jr=function(i){var e=Xl(i,"string");return Zl(e)?e:e+""},eu=xt,tu=qn,iu=Wn,Ci=_t,_a=jr,su=TypeError,Gs=Object.defineProperty,ru=Object.getOwnPropertyDescriptor,Ys="enumerable",js="configurable",qs="writable";si.f=eu?iu?function(e,t,s){if(Ci(e),t=_a(t),Ci(s),typeof e=="function"&&t==="prototype"&&"value"in s&&qs in s&&!s[qs]){var r=ru(e,t);r&&r[qs]&&(e[t]=s.value,s={configurable:js in s?s[js]:r[js],enumerable:Ys in s?s[Ys]:r[Ys],writable:!1})}return Gs(e,t,s)}:Gs:function(e,t,s){if(Ci(e),t=_a(t),Ci(s),tu)try{return Gs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw su("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var ms=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},au=xt,nu=si,ou=ms,Ei=au?function(i,e,t){return nu.f(i,e,ou(1,t))}:function(i,e,t){return i[e]=t,i},du=eo,lu=to,Ra=du("keys"),qr=function(i){return Ra[i]||(Ra[i]=lu(i))},Wr={},uu=Yd,io=Ve,cu=Lt,hu=Ei,Ws=ot,zs=Zn,fu=qr,pu=Wr,Ia="Object already initialized",Ar=io.TypeError,mu=io.WeakMap,ss,Si,rs,vu=function(i){return rs(i)?Si(i):ss(i,{})},gu=function(i){return function(e){var t;if(!cu(e)||(t=Si(e)).type!==i)throw Ar("Incompatible receiver, "+i+" required");return t}};if(uu||zs.state){var Ye=zs.state||(zs.state=new mu);Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,ss=function(i,e){if(Ye.has(i))throw Ar(Ia);return e.facade=i,Ye.set(i,e),e},Si=function(i){return Ye.get(i)||{}},rs=function(i){return Ye.has(i)}}else{var Gt=fu("state");pu[Gt]=!0,ss=function(i,e){if(Ws(i,Gt))throw Ar(Ia);return e.facade=i,hu(i,Gt,e),e},Si=function(i){return Ws(i,Gt)?i[Gt]:{}},rs=function(i){return Ws(i,Gt)}}var Su={set:ss,get:Si,has:rs,enforce:vu,getterFor:gu},bu=us,so=Function.prototype,Ca=so.apply,Oa=so.call,yu=typeof Reflect=="object"&&Reflect.apply||(bu?Oa.bind(Ca):function(){return Oa.apply(Ca,arguments)}),Tu=cs,Eu=at,ro=function(i){if(Tu(i)==="Function")return Eu(i)},ao={},no={},oo={}.propertyIsEnumerable,lo=Object.getOwnPropertyDescriptor,$u=lo&&!oo.call({1:2},1);no.f=$u?function(e){var t=lo(this,e);return!!t&&t.enumerable}:oo;var Au=xt,wu=nt,ku=no,Pu=ms,Du=Ti,Lu=jr,xu=ot,_u=qn,Ma=Object.getOwnPropertyDescriptor;ao.f=Au?Ma:function(e,t){if(e=Du(e),t=Lu(t),_u)try{return Ma(e,t)}catch(s){}if(xu(e,t))return Pu(!wu(ku.f,e,t),e[t])};var Ru=rt,Iu=Oe,Cu=/#|\.prototype\./,$i=function(i,e){var t=Mu[Ou(i)];return t==Nu?!0:t==Bu?!1:Iu(e)?Ru(e):!!e},Ou=$i.normalize=function(i){return String(i).replace(Cu,".").toLowerCase()},Mu=$i.data={},Bu=$i.NATIVE="N",Nu=$i.POLYFILL="P",Fu=$i,Ba=ro,Vu=Yr,Uu=us,Hu=Ba(Ba.bind),uo=function(i,e){return Vu(i),e===void 0?i:Uu?Hu(i,e):function(){return i.apply(e,arguments)}},Oi=Ve,Gu=yu,Yu=ro,ju=Oe,qu=ao.f,Wu=Fu,Yt=Vr,zu=uo,jt=Ei,Na=ot,Qu=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Gu(i,this,arguments)};return e.prototype=i.prototype,e},vs=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=s?Yt:Yt[t]||jt(Yt,t,{})[t],l=o.prototype,d,u,c,h,f,g,m,v,S;for(h in e)d=Wu(s?h:t+(r?".":"#")+h,i.forced),u=!d&&n&&Na(n,h),g=o[h],u&&(i.dontCallGetSet?(S=qu(n,h),m=S&&S.value):m=n[h]),f=u&&m?m:e[h],!(u&&typeof g==typeof f)&&(i.bind&&u?v=zu(f,Oi):i.wrap&&u?v=Qu(f):a&&ju(f)?v=Yu(f):v=f,(i.sham||f&&f.sham||g&&g.sham)&&jt(v,"sham",!0),jt(o,h,v),a&&(c=t+"Prototype",Na(Yt,c)||jt(Yt,c,{}),jt(Yt[c],h,f),i.real&&l&&(d||!l[h])&&jt(l,h,f)))},wr=xt,Ku=ot,co=Function.prototype,Ju=wr&&Object.getOwnPropertyDescriptor,zr=Ku(co,"name"),Xu=zr&&function(){}.name==="something",Zu=zr&&(!wr||wr&&Ju(co,"name").configurable),ec={EXISTS:zr,PROPER:Xu,CONFIGURABLE:Zu},ho={},tc=Math.ceil,ic=Math.floor,sc=Math.trunc||function(e){var t=+e;return(t>0?ic:tc)(t)},rc=sc,Qr=function(i){var e=+i;return e!==e||e===0?0:rc(e)},ac=Qr,nc=Math.max,oc=Math.min,dc=function(i,e){var t=ac(i);return t<0?nc(t+e,0):oc(t,e)},lc=Qr,uc=Math.min,cc=function(i){return i>0?uc(lc(i),9007199254740991):0},hc=cc,Kr=function(i){return hc(i.length)},fc=Ti,pc=dc,mc=Kr,Fa=function(i){return function(e,t,s){var r=fc(e),a=mc(r),n=pc(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},vc={includes:Fa(!0),indexOf:Fa(!1)},gc=at,Qs=ot,Sc=Ti,bc=vc.indexOf,yc=Wr,Va=gc([].push),Tc=function(i,e){var t=Sc(i),s=0,r=[],a;for(a in t)!Qs(yc,a)&&Qs(t,a)&&Va(r,a);for(;e.length>s;)Qs(t,a=e[s++])&&(~bc(r,a)||Va(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ec=Tc,$c=fo,Ac=Object.keys||function(e){return Ec(e,$c)},wc=xt,kc=Wn,Pc=si,Dc=_t,Lc=Ti,xc=Ac;ho.f=wc&&!kc?Object.defineProperties:function(e,t){Dc(e);for(var s=Lc(t),r=xc(t),a=r.length,n=0,o;a>n;)Pc.f(e,o=r[n++],s[o]);return e};var _c=Ur,Rc=_c("document","documentElement"),Ic=_t,Cc=ho,Ua=fo,Oc=Wr,Mc=Rc,Bc=jn,Nc=qr,Ha=">",Ga="<",kr="prototype",Pr="script",po=Nc("IE_PROTO"),Ks=function(){},mo=function(i){return Ga+Pr+Ha+i+Ga+"/"+Pr+Ha},Ya=function(i){i.write(mo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Fc=function(){var i=Bc("iframe"),e="java"+Pr+":",t;return i.style.display="none",Mc.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Mi,Ki=function(){try{Mi=new ActiveXObject("htmlfile")}catch(e){}Ki=typeof document!="undefined"?document.domain&&Mi?Ya(Mi):Fc():Ya(Mi);for(var i=Ua.length;i--;)delete Ki[kr][Ua[i]];return Ki()};Oc[po]=!0;var vo=Object.create||function(e,t){var s;return e!==null?(Ks[kr]=Ic(e),s=new Ks,Ks[kr]=null,s[po]=e):s=Ki(),t===void 0?s:Cc.f(s,t)},Vc=rt,Uc=!Vc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Hc=ot,Gc=Oe,Yc=ps,jc=qr,qc=Uc,ja=jc("IE_PROTO"),Dr=Object,Wc=Dr.prototype,go=qc?Dr.getPrototypeOf:function(i){var e=Yc(i);if(Hc(e,ja))return e[ja];var t=e.constructor;return Gc(t)&&e instanceof t?t.prototype:e instanceof Dr?Wc:null},zc=Ei,So=function(i,e,t,s){return s&&s.enumerable?i[e]=t:zc(i,e,t),i},Qc=rt,Kc=Oe,Jc=Lt,Xc=vo,qa=go,Zc=So,eh=Ue,Lr=eh("iterator"),bo=!1,it,Js,Xs;[].keys&&(Xs=[].keys(),"next"in Xs?(Js=qa(qa(Xs)),Js!==Object.prototype&&(it=Js)):bo=!0);var th=!Jc(it)||Qc(function(){var i={};return it[Lr].call(i)!==i});th?it={}:it=Xc(it);Kc(it[Lr])||Zc(it,Lr,function(){return this});var yo={IteratorPrototype:it,BUGGY_SAFARI_ITERATORS:bo},ih=Ue,sh=ih("toStringTag"),To={};To[sh]="z";var Jr=String(To)==="[object z]",rh=Jr,ah=Oe,Ji=cs,nh=Ue,oh=nh("toStringTag"),dh=Object,lh=Ji(function(){return arguments}())=="Arguments",uh=function(i,e){try{return i[e]}catch(t){}},gs=rh?Ji:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=uh(e=dh(i),oh))=="string"?t:lh?Ji(e):(s=Ji(e))=="Object"&&ah(e.callee)?"Arguments":s},ch=Jr,hh=gs,fh=ch?{}.toString:function(){return"[object "+hh(this)+"]"},ph=Jr,mh=si.f,vh=Ei,gh=ot,Sh=fh,bh=Ue,Wa=bh("toStringTag"),Eo=function(i,e,t,s){if(i){var r=t?i:i.prototype;gh(r,Wa)||mh(r,Wa,{configurable:!0,value:e}),s&&!ph&&vh(r,"toString",Sh)}},yh=yo.IteratorPrototype,Th=vo,Eh=ms,$h=Eo,Ah=ii,wh=function(){return this},kh=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Th(yh,{next:Eh(+!s,t)}),$h(i,r,!1,!0),Ah[r]=wh,i},Ph=vs,Dh=nt,$o=ec,Lh=kh,xh=go,_h=Eo,za=So,Rh=Ue,Qa=ii,Ao=yo,Ih=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Bi=Ao.BUGGY_SAFARI_ITERATORS,Zs=Rh("iterator"),Ka="keys",Ni="values",Ja="entries",Ch=function(){return this},Oh=function(i,e,t,s,r,a,n){Lh(t,e,s);var o=function(S){if(S===r&&h)return h;if(!Bi&&S in u)return u[S];switch(S){case Ka:return function(){return new t(this,S)};case Ni:return function(){return new t(this,S)};case Ja:return function(){return new t(this,S)}}return function(){return new t(this)}},l=e+" Iterator",d=!1,u=i.prototype,c=u[Zs]||u["@@iterator"]||r&&u[r],h=!Bi&&c||o(r),f=e=="Array"&&u.entries||c,g,m,v;if(f&&(g=xh(f.call(new i)),g!==Object.prototype&&g.next&&(_h(g,l,!0,!0),Qa[l]=Ch)),Ih&&r==Ni&&c&&c.name!==Ni&&(d=!0,h=function(){return Dh(c,this)}),r)if(m={values:o(Ni),keys:a?h:o(Ka),entries:o(Ja)},n)for(v in m)(Bi||d||!(v in u))&&za(u,v,m[v]);else Ph({target:e,proto:!0,forced:Bi||d},m);return n&&u[Zs]!==h&&za(u,Zs,h,{name:r}),Qa[e]=h,m},Mh=function(i,e){return{value:i,done:e}},Bh=Ti,Xa=ii,wo=Su;si.f;var Nh=Oh,Fi=Mh,ko="Array Iterator",Fh=wo.set,Vh=wo.getterFor(ko);Nh(Array,"Array",function(i,e){Fh(this,{type:ko,target:Bh(i),index:0,kind:e})},function(){var i=Vh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(s,!1):t=="values"?Fi(e[s],!1):Fi([s,e[s]],!1)},"values");Xa.Arguments=Xa.Array;var Uh=Ue,Hh=ii,Gh=Uh("iterator"),Yh=Array.prototype,jh=function(i){return i!==void 0&&(Hh.Array===i||Yh[Gh]===i)},qh=gs,Za=fs,Wh=hs,zh=ii,Qh=Ue,Kh=Qh("iterator"),Po=function(i){if(!Wh(i))return Za(i,Kh)||Za(i,"@@iterator")||zh[qh(i)]},Jh=nt,Xh=Yr,Zh=_t,ef=Gr,tf=Po,sf=TypeError,rf=function(i,e){var t=arguments.length<2?tf(i):e;if(Xh(t))return Zh(Jh(t,i));throw sf(ef(i)+" is not iterable")},af=nt,en=_t,nf=fs,of=function(i,e,t){var s,r;en(i);try{if(s=nf(i,"return"),!s){if(e==="throw")throw t;return t}s=af(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return en(s),t},df=uo,lf=nt,uf=_t,cf=Gr,hf=jh,ff=Kr,tn=Hr,pf=rf,mf=Po,sn=of,vf=TypeError,Xi=function(i,e){this.stopped=i,this.result=e},rn=Xi.prototype,gf=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=df(e,s),d,u,c,h,f,g,m,v=function(E){return d&&sn(d,"normal",E),new Xi(!0,E)},S=function(E){return r?(uf(E),o?l(E[0],E[1],v):l(E[0],E[1])):o?l(E,v):l(E)};if(a)d=i.iterator;else if(n)d=i;else{if(u=mf(i),!u)throw vf(cf(i)+" is not iterable");if(hf(u)){for(c=0,h=ff(i);h>c;c++)if(f=S(i[c]),f&&tn(rn,f))return f;return new Xi(!1)}d=pf(i,u)}for(g=a?i.next:d.next;!(m=lf(g,d)).done;){try{f=S(m.value)}catch(E){sn(d,"throw",E)}if(typeof f=="object"&&f&&tn(rn,f))return f}return new Xi(!1)},Sf=jr,bf=si,yf=ms,Tf=function(i,e,t){var s=Sf(e);s in i?bf.f(i,s,yf(0,t)):i[s]=t},Ef=vs,$f=gf,Af=Tf;Ef({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $f(e,function(s,r){Af(t,s,r)},{AS_ENTRIES:!0}),t}});var wf=Vr,kf=wf.Object.fromEntries,Pf={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},Df=Pf,Lf=Ve,xf=gs,_f=Ei,an=ii,Rf=Ue,nn=Rf("toStringTag");for(var er in Df){var on=Lf[er],tr=on&&on.prototype;tr&&xf(tr)!==nn&&_f(tr,nn,er),an[er]=an.Array}var If=kf,Cf=If,Of=Cf,Mf=Of,as=Nr(Mf),me;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(me||(me={}));var Fe=(i,e=0,t=me.OFFSET_P)=>{switch(t){case me.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case me.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:U(t)}return i};const dn=(i,e)=>{var t;switch(e){case me.OFFSET_P:return NaN;case me.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:U(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ue{constructor(e){this.transitionStarted$=new R,this.transitionEnded$=new R,this.transitionUpdated$=new R,this.forceChanged$=new R,this.stateChangeStarted$=N(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=N(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||D(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Bf=i=>{switch(i){case b.MPEG:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return U(i)}};var V;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Nf=5,Ff=5,Vf=500,ln=7e3;class Uf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new ue(V.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==V.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PLAYING:{switch(s){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PAUSED:{switch(s){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}default:U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bf(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 ie;this.subscription.add(e),this.subscription.add(N(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 R;e.add(r.pipe(Ke(Vf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-a)>Nf)&&r.next(o),a=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(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(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Ff&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:U(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=N(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===V.READY&&this.videoState.setState(V.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const u=s[e];P(u);const c=fd(Object.keys(u));P(c);const h=u[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const u=s[e];P(u),r=u.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:{const u=s[e];P(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const u=s[e];P(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const u=s[e];P(u),r=Fe(u.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:u,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(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:l,subtitle:d}=this.params.meta;return D(l)&&(o.metadata.title=l),D(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(pd(ln).subscribe(()=>a(`timeout(${ln})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Xr=i=>{i.removeAttribute("src"),i.load()},Hf=i=>{try{i.pause(),i.playbackRate=0,Xr(i),i.remove()}catch(e){console.error(e)}};class Gf{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 xr=window.WeakMap?new WeakMap:new Gf,Rt=i=>{let e=i.querySelector("video");const t=!!e;return e?Xr(e):(e=document.createElement("video"),i.appendChild(e)),xr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=i=>{const e=xr.get(i);xr.delete(i),e?Xr(i):Hf(i)},et=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),l=Q(r),d=new ie;return r&&d.add(r.subscribe(u=>{const c=i.getState();s(u,c)&&i.setState(u)},a)),s(o,n)||(t(n),l&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(u=>{t(u.to),l&&i.setState(u.to)},a)),d},Ai=(i,e,t)=>et(e,()=>i.loop,s=>{D(s)&&(i.loop=s)},{onError:t}),Ct=(i,e,t,s)=>et(e,()=>({muted:i.muted,volume:i.volume}),r=>{D(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),ri=(i,e,t,s)=>et(e,()=>i.playbackRate,r=>{D(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Yf=i=>["__",i.language,i.label].join("|"),jf=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class mt{constructor(){this.available$=new R,this.current$=new y(void 0),this.error$=new R,this.subscription=new ie,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(et(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},l)=>o===n[l].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(et(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},l)=>o===n[l].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(et(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(et(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(C(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(N(C(e,"addtrack"),C(e,"removetrack"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(N(C(e,"change"),Ce(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(C(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var l,d,u,c,h;const f=(d=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(C(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;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(mt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:Yf(e),o=this.externalTracks.has(n),l=n.includes("auto");return o?{id:n,type:"external",isAuto:l,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:l,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!jf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Zr{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 Do=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},un=i=>{const e=Do(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},qf=i=>{const e=Do(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Wf=3;var zf=(i,e,t=Wf)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let l=a-1;l>=0;l--)i.end(l)+t>=s&&(s=i.start(l));for(let l=a+1;l<i.length;l++)i.start(l)-t<=r&&(r=i.end(l))}}return{from:s,to:r}};const Ot=i=>{const e=A=>C(i,A).pipe(es(void 0)),s=N(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>C(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),he()),r=N(C(i,"progress"),C(i,"timeupdate")).pipe($(()=>zf(i.buffered,i.currentTime))),n=Mr().browser===Nn.Safari?Re({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(es(void 0)):e("playing"),o=C(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),l=C(i,"ratechange").pipe($(()=>i.playbackRate)),d=C(i,"error").pipe(ce(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),u=C(i,"timeupdate").pipe($(()=>i.currentTime)),c=new R,h=.3;let f;u.subscribe(A=>{i.loop&&D(f)&&D(A)&&f>=i.duration-h&&A<=h&&c.next(f),f=A});const g=C(i,"enterpictureinpicture"),m=C(i,"leavepictureinpicture"),v=new y(qf(i));g.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new y(un(i));return C(i,"fullscreenchange").pipe($(()=>un(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ce(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:C(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:S}};var Ss=i=>{switch(i){case"mobile":return Pe.Q_144P;case"lowest":return Pe.Q_240P;case"low":return Pe.Q_360P;case"sd":case"medium":return Pe.Q_480P;case"hd":case"high":return Pe.Q_720P;case"fullhd":case"full":return Pe.Q_1080P;case"quadhd":case"quad":return Pe.Q_1440P;case"ultrahd":case"ultra":return Pe.Q_2160P}},Qf=vs,Kf=ps,Jf=Kr,Xf=Qr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),s=Jf(t),r=Xf(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var Zf=Ur,Lo=Zf,ep=Lo,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,Ze=Nr(ap);let ea=!1,tt={};const np=i=>{ea=i},op=()=>{tt={}},dp=i=>{i(tt)},Vi=(i,e)=>{var t;ea&&(tt.meta=(t=tt.meta)!==null&&t!==void 0?t:{},tt.meta[i]=e)};class We{constructor(e){this.name=e}next(e){var t,s;if(!ea)return;tt.series=(t=tt.series)!==null&&t!==void 0?t:{};const r=(s=tt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),tt.series[this.name]=r}}var At;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(At||(At={}));const lp=new We("best_bitrate"),up=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const hp='Assertion "ABR Tracks is empty array" failed',bs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:l,history:d,droppedVideoMaxQualityLimit:u,abrLogger:c})=>{var h,f,g,m,v;md(i,hp);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&kt(E),w=s.considerPlaybackRate&&D(o)?o:1,k=i.filter(B=>!Pt(B.quality)).sort((B,x)=>Xt(B.quality,x.quality)?-1:1),j=(f=Ze(k,-1))===null||f===void 0?void 0:f.quality,q=(g=Ze(k,0))===null||g===void 0?void 0:g.quality,K=Q(r)||D(r.min)&&D(r.max)&&zi(r.max,r.min)||D(r.min)&&q&&Xt(r.min,q)||D(r.max)&&j&&zi(r.max,j),G=w*up(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),J={},M=k.filter(B=>(A?zi(B.quality,A):!0)?(D(t)&&isFinite(t)&&D(B.bitrate)?t-a>=B.bitrate*G:!0)?s.lazyQualitySwitch&&D(s.minBufferToSwitchUp)&&l&&!Pt(l.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Xt(B.quality,l.quality)?(J[B.quality]=At.Buffer,!1):!!u&&br(B.quality,u)?(J[B.quality]=At.DroppedFramesLimit,!1):K||(Q(r.max)||ts(B.quality,r.max))&&(Q(r.min)||br(B.quality,r.min))?!0:(J[B.quality]=At.FitsQualityLimits,!1):(J[B.quality]=At.FitsThroughput,!1):(J[B.quality]=At.FitsContainer,!1))[0];M&&M.bitrate&&lp.next(M.bitrate);const I=(m=M!=null?M:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];I.quality!==((v=d==null?void 0:d.last)===null||v===void 0?void 0:v.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -21,7 +21,7 @@ import{ValueSubject as y,Subject as R,Subscription as ie,isNonNullable as D,Erro
|
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
22
|
bitrateFactor: ${G},
|
|
23
23
|
minBufferToSwitchUp: ${s.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
24
|
+
droppedVideoMaxQualityLimit: ${u},
|
|
25
25
|
limitsAreInvalid: ${K},
|
|
26
26
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
@@ -34,13 +34,13 @@ import{ValueSubject as y,Subject as R,Subscription as ie,isNonNullable as D,Erro
|
|
|
34
34
|
[selected track] ${I==null?void 0:I.quality}
|
|
35
35
|
`});const se=I&&d&&d.history[I.id]&&ne()-d.history[I.id]<=s.trackCooldown&&(!d.last||I.id!==d.last.id);if(I!=null&&I.id&&d&&!se&&d.recordSelection(I),se&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),c({message:`
|
|
36
36
|
[last selected] ${B==null?void 0:B.quality}
|
|
37
|
-
`}),B}return d==null||d.recordSwitch(I),I};var Je=i=>new URL(i).hostname;const un=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Mt=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!un(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return un(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function Te(){return ne()}function Lo(i){return Te()-i}function cn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function hp(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Xi(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",g=7e3,m=2e3,v=()=>{if(u)return;P(l);const M=Lo(l);let I;if(M<m){I=m-M,setTimeout(v,I);return}m*=2,m>g&&(m=g),n&&n.abort(),n=new r,q()};const S=M=>(a=M,Z),E=M=>(c=M,Z),A=()=>(f="json",Z),w=()=>{if(!u){if(--d>=0){v(),s&&s();return}u=!0,c&&c(),t&&t()}},k=M=>(h=M,Z),q=()=>{l=Te(),n=new r,n.open("get",i);let M=0,I,se=0;const B=()=>(P(l),Math.max(l,Math.max(I||0,se||0)));if(a&&n.addEventListener("progress",x=>{const X=Te();a.updateChunk&&x.loaded>M&&(a.updateChunk(B(),x.loaded-M),M=x.loaded,I=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&a){const X=n.response.byteLength-M;X&&a.updateChunk&&a.updateChunk(B(),X)}n.responseType==="json"&&!Object.values(n.response).length?w():(c&&c(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const x=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=Te(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),Z},Z={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:M=>(d=M,Z),withRetryInterval:(M,I)=>(D(M)&&(m=M),D(I)&&(g=I),Z),withTimeout:M=>(o=M,Z),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Z}const fp=100,pp=2e3,mp=500;let vp=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-mp;if(t-e>pp){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>fp&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class gp{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Vi=1e4,tr=3,Sp=6e4,bp=10,yp=1,Tp=500;class Ep{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new vp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||D(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{hp(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new gp(tr,Vi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,k,q)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(Vi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tr).withFinally(()=>{u=null}).send()},f=(w,k,q)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},g=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},m=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const q=Te()-1e4;let j=0;for(let G=0;G<this.bufferStates.length;G++){const J=this.bufferStates[G];w=Math.min(w,J.buf),J.ts<q&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${w} drop=${j} jitter=${this.sourceJitter}`);let K=w-yp;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?g(1.15):K>1?g(1.1):K>.3?g(1.05):g(1)}},S=w=>{let k;const q=()=>k&&k.start?k.start.length:0,j=x=>k.start[x]/1e3,K=x=>k.dur[x]/1e3,G=x=>k.fragIndex+x,J=(x,X)=>({chunkIdx:G(x),startTS:j(x),dur:K(x),discontinuity:X}),Z=()=>{let x=0;if(k&&k.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=X;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=k.dur.length-1;for(;ve>=0&&(fe-=k.dur[ve],!(fe<=0));--ve);x=Math.min(ve,k.dur.length-1-oe),x=Math.max(x,0)}return J(x,!0)},M=x=>{const X=q();if(!(X<=0)){if(D(x)){for(let oe=0;oe<X;oe++)if(j(oe)>x)return J(oe)}return Z()}},I=x=>{const X=q(),oe=x?x.chunkIdx+1:0,fe=oe-k.fragIndex;if(!(X<=0)){if(!x||fe<0||fe-X>bp)return t(`Resync: offset=${fe} bChunks=${X} chunk=`+JSON.stringify(x)),Z();if(!(fe>=X))return J(oe-k.fragIndex,!1)}},se=(x,X,oe)=>{d&&d.abort(),d=Xi(this.urlResolver.resolve(x,!0,this.lowLatency),X,oe,()=>this._retryCallback()).withTimeout(Vi).withRetryCount(tr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,X)=>{se(w,oe=>{if(!c())return;k=oe;const fe=!!k.lowLatency;fe!==this.lowLatency&&m(fe);let ve=0;for(let He=0;He<k.dur.length;++He)ve+=k.dur[He];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,x(M(X))},()=>this._handleNetworkError())},nextChunk:I}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:k,logger:q}=this.params;let j=S(e.jidxUrl),K,G,J,Z,M=0,I,se,B;const x=()=>{I&&(clearTimeout(I),I=void 0);const z=Math.max(Tp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+z,$e=Te(),ke=Math.min(1e4,be-$e);M=$e;const Nt=()=>{d||c()&&j.seek(()=>{c()&&(M=Te(),X(),x())})};ke>0?I=window.setTimeout(()=>{this.paused?x():Nt()},ke):Nt()},X=()=>{let z;for(;z=j.nextChunk(Z);)Z=z,ai(z);const be=j.nextChunk(J);if(be){if(J&&be.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?x():(E(),this._initPlayerWith(e));return}He(be)}else x()},oe=(z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,ke,Nt;const ni=Xe=>{window.setTimeout(()=>{c()&&oe(z,be)},Xe)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),ni(100);else{const Xe=Te(),De=k.currentTime;!this.paused&&k.buffered.length>1&&se===De&&Xe-B>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),se!==De&&(se=De,B=Xe);const Ft=this._getBufferSizeSec();if(Ft>30)q(`Buffered ${Ft} seconds; delaying appendBuffer`),ni(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Xe,buf:Ft}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(oi){if(oi.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Nt=this.sourceBuffer.buffered.length,Nt!==0&&($e=this.sourceBuffer.buffered.start(0),ke=De,ke-$e>4&&this.sourceBuffer.remove($e,ke-3)),ni(1e3);else throw oi}}},fe=()=>{G&&K&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(J)]),oe(G,function(){G=null,X()}))},ve=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),He=z=>{c()&&f(ve(z),(be,$e)=>{if(c()){if($e/=1e3,G=be,J=z,n=z.startTS,$e){const ke=Math.min(10,z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}fe()}},()=>this._handleNetworkError())},ai=z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(z),!1)))},Bt=z=>{c()&&(e.cachedHeader=z,oe(z,()=>{K=!0,fe()}))};a=!0,j.seek(z=>{if(c()){if(M=Te(),!z){x();return}Z=z,!Q(w)||z.startTS>w?He(z):(J=z,X())}},w),e.cachedHeader?Bt(e.cachedHeader):h(e.headerUrl,Bt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),D(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return D(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),g=c/this.bitrate,f>10&&g>.8||f>15&&g>.5||f>20&&g>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const g=Te();if(this.chunkRateEstimator.addInterval(h,g,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:g-h,speed:v}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Lo(n)<3e4)return;s(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Vi).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Mt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Sp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class xo{constructor(){this.onDroopedVideoFramesLimit$=new R,this.subscription=new ie,this.playing=!1,this.tracks=[],this.forceChecker$=new R,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Pt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&Xt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=fi(this.droppedFramesChecker.checkTime).pipe(ce(()=>this.playing),ce(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Ke(this.droppedFramesChecker.checkTime)),s=N(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Wi(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var H;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const $p=[H.PAUSED,H.PLAYING,H.READY],Ap=[H.PAUSED,H.PLAYING,H.READY];class wp{constructor(e){this.subscription=new ie,this.videoState=new ue(H.STOPPED),this.representations$=new y([]),this.textTracksManager=new mt,this.droppedFramesManager=new xo,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Xr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=gs(c.name))!==null&&n!==void 0?n:kt(c.video),g=c.bitrate/1e3,m={...c.video};if(!f)continue;const v={id:h,quality:f,bitrate:g,size:m};l.push({track:v,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),D(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ap.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&$p.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Fe(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(n===p.PAUSED)this.videoState.setState(H.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)})}return;case H.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Fe(this.params.source.url,c))}return;default:return U(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:r})};N(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Ot(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe($(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===H.READY&&this.videoState.setState(H.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Re({zeroTime:this.zeroTime$.pipe(ce(D)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add($i(this.video,this.params.desiredState.isLooped,t)).add(Ct(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ri(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&md(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case H.MANIFEST_READY:case H.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return U(r.to)}},t)).add(N(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ce(["init"])).pipe(Ke(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),It(this.video)}createLiveDashPlayer(){const e=new Ep({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&D(u)?u:Ss(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=l==null?void 0:l.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,g=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),g&&this.setAutoQuality(d),h||g||c!==f){const m=(n=o.find(({track:v})=>v.id===c))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===H.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Fe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var je;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(je||(je={}));var as;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(as||(as={}));var Ie;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ie||(Ie={}));var F;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(F||(F={}));var ei;(function(i){i.MP4="mp4",i.WEBM="webm"})(ei||(ei={}));var ns;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(ns||(ns={}));var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));var pi=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class hn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class _o extends hn{constructor(){super(),this.listeners||hn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Ro=class{constructor(){Object.defineProperty(this,"signal",{value:new _o,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ro.prototype[Symbol.toStringTag]="AbortController",_o.prototype[Symbol.toStringTag]="AbortSignal");function Io(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function kp(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Io({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,g)=>{l.addEventListener("abort",()=>g(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const bs=Io({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Co=bs?kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Si=bs?Co.fetch:window.fetch;bs?Co.Request:window.Request;const Zt=bs?Ro:window.AbortController;var xr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Pp=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Dp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fn=Dp?Pp:window.requestIdleCallback;var ir,sr;const Lp=16;let Oo=!1;try{Oo=Or().browser===Bn.Safari&&parseInt((sr=(ir=navigator.userAgent.match(/Version\/(\d+)/))===null||ir===void 0?void 0:ir[1])!==null&&sr!==void 0?sr:"",10)<=Lp}catch(i){console.error(i)}class xp{constructor(e){this.bufferFull$=new R,this.error$=new R,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:_.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Oo&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:_.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:U(t)}}}var pn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Me{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.size32=s<=e.buffer.byteLength?s:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Mo extends Me{}class _p extends Me{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class Rp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ip extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Cp extends Me{constructor(e,t){super(e,t),this.data=this.content}}class dt extends Me{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class Bo extends dt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Op extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Mp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var wt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(wt||(wt={}));class Bp extends dt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=wt.MONOSCOPIC;break;case 1:this.stereoMode=wt.TOP_BOTTOM;break;case 2:this.stereoMode=wt.LEFT_RIGHT;break;case 3:this.stereoMode=wt.STEREO_CUSTOM;break;case 4:this.stereoMode=wt.RIGHT_LEFT;break}this.cursor+=1}}class Np extends dt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Fp extends dt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Vp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Up extends dt{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Hp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Gp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Yp extends dt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class qp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class jp extends dt{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wp extends dt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class zp extends dt{constructor(e,t){super(e,t),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let s=0;s<this.sampleCount;s++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}var de;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UnknownBox="unknown"})(de||(de={}));const Qp={[de.FtypBox]:_p,[de.MoovBox]:Rp,[de.MoofBox]:Ip,[de.MdatBox]:Cp,[de.SidxBox]:Bo,[de.TrakBox]:Op,[de.MdiaBox]:Vp,[de.MfhdBox]:Yp,[de.TkhdBox]:Up,[de.TrafBox]:qp,[de.TfhdBox]:jp,[de.TfdtBox]:Wp,[de.TrunBox]:zp,[de.MinfBox]:Hp,[de.Sv3dBox]:Mp,[de.St3dBox]:Bp,[de.PrhdBox]:Np,[de.ProjBox]:Gp,[de.EquiBox]:Fp,[de.UnknownBox]:Mo};class Dt{constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;){const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(t.push(n),!n.size)break;s+=n.size}return t}createBox(e,t){const s=Qp[e];return s?new s(t,new Dt):new Mo(t,new Dt)}}class ea{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const Kp=new TextDecoder("ascii"),Jp=i=>Kp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Xp=i=>{const e=new Bo(i,new Dt);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:F.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},Zp=i=>{const t=new Dt().parse(i),s=new ea(t),r=s.findAll("mdat"),a=s.findAll("moof");if(!(r.length&&a.length))return null;const n=a[0],o=r[r.length-1],u=n.source.byteOffset,l=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(i.buffer,u,l)},em=(i,e)=>{const s=new Dt().parse(i),a=new ea(s).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun");let d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,h)=>c+h,0):d=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},tm=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ns.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Dt().parse(i),r=new ea(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},im={validateData:Jp,parseInit:tm,getIndexRange:()=>{},parseSegments:Xp,parseFeedableSegmentChunk:Zp,getSegmentEndTime:em};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var L;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(L||(L={}));const mn={[T.EBML]:{type:L.Master},[T.EBMLVersion]:{type:L.UnsignedInteger},[T.EBMLReadVersion]:{type:L.UnsignedInteger},[T.EBMLMaxIDLength]:{type:L.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:L.UnsignedInteger},[T.DocType]:{type:L.String},[T.DocTypeVersion]:{type:L.UnsignedInteger},[T.DocTypeReadVersion]:{type:L.UnsignedInteger},[T.Void]:{type:L.Binary},[T.Segment]:{type:L.Master},[T.SeekHead]:{type:L.Master},[T.Seek]:{type:L.Master},[T.SeekID]:{type:L.Binary},[T.SeekPosition]:{type:L.UnsignedInteger},[T.Info]:{type:L.Master},[T.TimestampScale]:{type:L.UnsignedInteger},[T.Duration]:{type:L.Float},[T.Tracks]:{type:L.Master},[T.TrackEntry]:{type:L.Master},[T.Video]:{type:L.Master},[T.Projection]:{type:L.Master},[T.ProjectionType]:{type:L.UnsignedInteger},[T.ProjectionPrivate]:{type:L.Master},[T.Chapters]:{type:L.Master},[T.Cluster]:{type:L.Master},[T.Timestamp]:{type:L.UnsignedInteger},[T.SilentTracks]:{type:L.Master},[T.SilentTrackNumber]:{type:L.UnsignedInteger},[T.Position]:{type:L.UnsignedInteger},[T.PrevSize]:{type:L.UnsignedInteger},[T.SimpleBlock]:{type:L.Binary},[T.BlockGroup]:{type:L.Master},[T.EncryptedBlock]:{type:L.Binary},[T.Attachments]:{type:L.Master},[T.Tags]:{type:L.Master},[T.Cues]:{type:L.Master},[T.CuePoint]:{type:L.Master},[T.CueTime]:{type:L.UnsignedInteger},[T.CueTrackPositions]:{type:L.Master},[T.CueTrack]:{type:L.UnsignedInteger},[T.CueClusterPosition]:{type:L.UnsignedInteger},[T.CueRelativePosition]:{type:L.UnsignedInteger},[T.CueDuration]:{type:L.UnsignedInteger},[T.CueBlockNumber]:{type:L.UnsignedInteger},[T.CueCodecState]:{type:L.UnsignedInteger},[T.CueReference]:{type:L.Master},[T.CueRefTime]:{type:L.UnsignedInteger}},No=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=os(i,t),r=s in mn,a=r?mn[s].type:L.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,l=os(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},os=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{const t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(i,e)=>{switch(e){case L.SignedInteger:return i.getInt8(0);case L.UnsignedInteger:return os(i);case L.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case L.String:return new TextDecoder("ascii").decode(i);case L.UTF8:return new TextDecoder("utf-8").decode(i);case L.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case L.Master:return i;case L.Binary:return i;default:U(e)}},ti=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=No(s);if(!e(r))return;r.type===L.Master&&ti(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},sm=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=No(i);return ti(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=ze(o,n):a===T.DocType?t=ze(o,n):a===T.DocTypeReadVersion&&(s=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Fo=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],rm=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],am=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ti(i,({tag:h,type:f,value:g,valueSize:m})=>{if(h===T.SeekID){const v=ze(g,f);d=os(v)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=g.byteOffset,t=g.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=ze(g,f):h===T.Duration?r=ze(g,f):h===T.SeekPosition&&d===T.Cues?u=ze(g,f):h===T.Tracks?ti(g,({tag:v,type:S,value:E})=>v===T.ProjectionType?(l=ze(E,S)===1,!1):!0):a&&n&&Fo.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:ns.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nm=i=>{if(Q(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},om=(i,e)=>{let t=!1,s=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ti(i,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=ze(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=ze(d,u));break;default:t&&Fo.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:F.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}}})},dm=i=>{let e=0,t=!1;try{ti(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):rm.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},lm={validateData:sm,parseInit:am,getIndexRange:nm,parseSegments:om,parseFeedableSegmentChunk:dm};var um=Lt,cm=us,hm=Ue,fm=hm("match"),pm=function(i){var e;return um(i)&&((e=i[fm])!==void 0?!!e:cm(i)=="RegExp")},mm=vs,vm=String,gm=function(i){if(mm(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return vm(i)},Sm=_t,bm=function(){var i=Sm(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},ym=nt,Tm=ot,Em=Ur,$m=bm,vn=RegExp.prototype,Am=function(i){var e=i.flags;return e===void 0&&!("flags"in vn)&&!Tm(i,"flags")&&Em(vn,i)?ym($m,i):e},ta=at,wm=fs,km=Math.floor,rr=ta("".charAt),Pm=ta("".replace),ar=ta("".slice),Dm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Lm=/\$([$&'`]|\d{1,2})/g,xm=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=Lm;return r!==void 0&&(r=wm(r),u=Dm),Pm(a,u,function(d,l){var c;switch(rr(l,0)){case"$":return"$";case"&":return i;case"`":return ar(e,0,t);case"'":return ar(e,n);case"<":c=r[ar(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=km(h/10);return f===0?d:f<=o?s[f-1]===void 0?rr(l,1):s[f-1]+rr(l,1):d}c=s[h-1]}return c===void 0?"":c})},_m=ms,Rm=nt,ia=at,gn=Nr,Im=Oe,Cm=cs,Om=pm,jt=gm,Mm=hs,Bm=Am,Nm=xm,Fm=Ue,Vm=Fm("replace"),Um=TypeError,Vo=ia("".indexOf),Hm=ia("".replace),Sn=ia("".slice),Gm=Math.max,bn=function(i,e,t){return t>i.length?-1:e===""?t:Vo(i,e,t)};_m({target:"String",proto:!0},{replaceAll:function(e,t){var s=gn(this),r,a,n,o,u,d,l,c,h,f=0,g=0,m="";if(!Cm(e)){if(r=Om(e),r&&(a=jt(gn(Bm(e))),!~Vo(a,"g")))throw Um("`.replaceAll` does not allow non-global regexes");if(n=Mm(e,Vm),n)return Rm(n,e,s,t);if(r)return Hm(jt(s),e,t)}for(o=jt(s),u=jt(e),d=Im(t),d||(t=jt(t)),l=u.length,c=Gm(1,l),f=bn(o,u,0);f!==-1;)h=d?jt(t(u,f,o)):Nm(u,o,f,[],void 0,t),m+=Sn(o,g,f)+h,g=f+l,f=bn(o,u,f+c);return g<o.length&&(m+=Sn(o,g)),m}});var Ym=Do,qm=Ym("String","replaceAll"),jm=qm,Wm=jm,zm=Wm,Qm=zm,yn=Br(Qm);const Km=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Tn=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},zt=(i,e)=>{let t=i;t=yn(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=yn(t,n,(o,u)=>Q(a)?o:Q(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Jm=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,g,m,v,S,E,A,w,k,q,j,K,G,J,Z,M,I,se,B,x,X,oe,fe,ve,He,ai,Bt,z,be,$e,ke;const ni=new DOMParser().parseFromString(i,"application/xml"),Xe={video:[],audio:[],text:[]},De=ni.children[0],Ft=De.getElementsByTagName("Period")[0],oi=(r=(s=(t=De.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",Wo=Ft.children,zo=De.getAttribute("type")==="dynamic",aa=De.getAttribute("availabilityStartTime"),Qo=aa?new Date(aa).getTime():void 0;let vt;const na=De.getAttribute("mediaPresentationDuration"),oa=Ft.getAttribute("duration"),ys=De.getElementsByTagName("vk:Attrs")[0],da=ys==null?void 0:ys.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(na)vt=Tn(na);else if(oa){const Le=Tn(oa);D(Le)&&(vt=Le)}else da&&(vt=parseInt(da,10));let Ko=0;const Ts=(n=(a=De.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Jo=Ts.includes(as.WEBM_AS_IN_FFMPEG)||Ts.includes(as.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const Le of Wo){const Ai=Le.getAttribute("mimeType"),Xo=Le.getAttribute("codecs"),la=(o=Le.getAttribute("contentType"))!==null&&o!==void 0?o:Ai==null?void 0:Ai.split("/")[0],Zo=(d=(u=Le.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&d!==void 0?d:[],ua=Le.querySelectorAll("Representation"),ed=Le.querySelector("SegmentTemplate");if(la===Se.TEXT){for(const pe of ua){const lt=pe.getAttribute("id")||"",wi=Le.getAttribute("lang"),Vt=Le.getAttribute("label"),Es=(h=(c=(l=pe.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",$s=new URL(Es||oi,e).toString(),ki=lt.includes("_auto");Xe[Se.TEXT].push({id:lt,lang:wi,label:Vt,isAuto:ki,kind:Se.TEXT,url:$s})}continue}for(const pe of ua){const lt=(f=pe.getAttribute("mimeType"))!==null&&f!==void 0?f:Ai,wi=(m=(g=pe.getAttribute("codecs"))!==null&&g!==void 0?g:Xo)!==null&&m!==void 0?m:"",Vt=(S=(v=pe.getAttribute("contentType"))!==null&&v!==void 0?v:lt==null?void 0:lt.split("/")[0])!==null&&S!==void 0?S:la,Es=(A=(E=Le.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],$s=parseInt((w=pe.getAttribute("width"))!==null&&w!==void 0?w:"",10),ki=parseInt((k=pe.getAttribute("height"))!==null&&k!==void 0?k:"",10),ca=parseInt((q=pe.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,ha=(j=pe.getAttribute("frameRate"))!==null&&j!==void 0?j:"",td=(K=pe.getAttribute("quality"))!==null&&K!==void 0?K:void 0,id=ha?Km(ha):void 0,sd=(G=pe.getAttribute("id"))!==null&&G!==void 0?G:(Ko++).toString(10),rd=Vt==="video"?`${ki}p`:Vt==="audio"?`${ca}Kbps`:wi,ad=`${sd}@${rd}`,nd=(M=(Z=(J=pe.querySelector("BaseURL"))===null||J===void 0?void 0:J.textContent)===null||Z===void 0?void 0:Z.trim())!==null&&M!==void 0?M:"",fa=new URL(nd||oi,e).toString(),od=[...Ts,...Zo,...Es];let As;const dd=pe.querySelector("SegmentBase"),gt=(I=pe.querySelector("SegmentTemplate"))!==null&&I!==void 0?I:ed;if(dd){const St=(B=(se=pe.querySelector("SegmentBase Initialization"))===null||se===void 0?void 0:se.getAttribute("range"))!==null&&B!==void 0?B:"",[bt,ks]=St.split("-").map(Ut=>parseInt(Ut,10)),ut={from:bt,to:ks},di=(x=pe.querySelector("SegmentBase"))===null||x===void 0?void 0:x.getAttribute("indexRange"),[Ps,Pi]=di?di.split("-").map(Ut=>parseInt(Ut,10)):[],li=di?{from:Ps,to:Pi}:void 0;As={type:Ie.BYTE_RANGE,url:fa,initRange:ut,indexRange:li}}else if(gt){const St={representationId:(X=pe.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(oe=pe.getAttribute("bandwidth"))!==null&&oe!==void 0?oe:void 0},bt=parseInt((fe=gt.getAttribute("timescale"))!==null&&fe!==void 0?fe:"",10),ks=(ve=gt.getAttribute("initialization"))!==null&&ve!==void 0?ve:"",ut=gt.getAttribute("media"),di=(ai=parseInt((He=gt.getAttribute("startNumber"))!==null&&He!==void 0?He:"",10))!==null&&ai!==void 0?ai:1,Ps=zt(ks,St);if(!ut)throw new ReferenceError("No media attribute in SegmentTemplate");const Pi=(Bt=gt.querySelectorAll("SegmentTimeline S"))!==null&&Bt!==void 0?Bt:[],li=[];let Ut=0,Ds="",Ls=0;if(Pi.length){let Di=di,Be=0;for(const Ht of Pi){const Ge=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10),yt=parseInt((be=Ht.getAttribute("r"))!==null&&be!==void 0?be:"",10)||0,Li=parseInt(($e=Ht.getAttribute("t"))!==null&&$e!==void 0?$e:"",10);Be=Number.isFinite(Li)?Li:Be;const xs=Ge/bt*1e3,_s=Be/bt*1e3;for(let xi=0;xi<yt+1;xi++){const ud=zt(ut,{...St,segmentNumber:Di.toString(10),segmentTime:(Be+xi*Ge).toString(10)}),pa=(_s!=null?_s:0)+xi*xs,cd=pa+xs;Di++,li.push({time:{from:pa,to:cd},url:ud})}Be+=(yt+1)*Ge,Ut+=(yt+1)*xs}Ls=Be/bt*1e3,Ds=zt(ut,{...St,segmentNumber:Di.toString(10),segmentTime:Be.toString(10)})}else if(D(vt)){const Be=parseInt((ke=gt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/bt*1e3,Ht=Math.ceil(vt/Be);let Ge=0;for(let yt=1;yt<Ht;yt++){const Li=zt(ut,{...St,segmentNumber:yt.toString(10),segmentTime:Ge.toString(10)});li.push({time:{from:Ge,to:Ge+Be},url:Li}),Ge+=Be}Ls=Ge,Ds=zt(ut,{...St,segmentNumber:Ht.toString(10),segmentTime:Ge.toString(10)})}const ld={time:{from:Ls,to:1/0},url:Ds};As={type:Ie.TEMPLATE,baseUrl:fa,segmentTemplateUrl:ut,initUrl:Ps,totalSegmentsDurationMs:Ut,segments:li,nextSegmentBeyondManifest:ld,timescale:bt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Vt||!lt)continue;const ws={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[Vt];ws&&Xe[ws].push({id:ad,kind:ws,segmentReference:As,profiles:od,duration:vt,bitrate:ca,mime:lt,codecs:wi,width:$s,height:ki,fps:id,quality:td})}}return{dynamic:zo,liveAvailabilityStartTime:Qo,duration:vt,container:Jo,representations:Xe}},Xm=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?gs(a):void 0)!==null&&n!==void 0?n:kt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Zm=({id:i,bitrate:e})=>({id:i,bitrate:e}),ev=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Ze(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Ze(i,-1)},tv=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),En=i=>"url"in i,Wt=i=>i.type===Ie.TEMPLATE,_r=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class $n{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new R,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Zt,this.destroyAbortController=new Zt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=we(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 xp(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,pn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),g=this.segments.get(h.id),m=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(g,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(g,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=we(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),g=this.initData.get(c);if(Q(g)||Q(f)?yield this.loadInit(h,"high",!1):g instanceof Promise&&(yield g),f=this.segments.get(c),P(f,"No segments for starting representation"),g=this.initData.get(c),!g||!(g instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(g,this.downloadAbortController.signal);const m=this.getCurrentPosition();D(m)&&(this.isLive||(f.forEach(v=>v.status=F.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=we(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const E of this.representations.keys()){const A=c.find(q=>q.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!Wt(w.segmentReference))return;const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,g=this.representations.get(f);P(g);const m=this.segments.get(f);P(m,"No segments for starting representation");const v=this.initData.get(f);if(P(v,"No init buffer for starting representation"),!(v instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,g),yield this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=s,s){case ei.MP4:this.containerParser=im;break;case ei.WEBM:this.containerParser=lm;break;default:U(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Zt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=pi(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)&&pn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=pi(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ze(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===F.FED&&!o.length&&pi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Ze(s,-1);u&&u.status===F.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;D(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Wt(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:F.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=Ze(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!Wt(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=zt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:F.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},g)=>{const m=h<=s&&f>=s,v=h>s||m||g===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===F.NONE||c===F.PARTIALLY_EJECTED&&v&&E&&this.sourceBuffer&&!xr(this.sourceBuffer.buffered,s))&&v&&E});if(r===-1)return[];if(t!==Ie.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===F.NONE||h.status===F.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,s="auto"){t.segmentReference.type===Ie.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=F.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 we(o,async function*(){const l=zi(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:s,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=F.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),_r(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const u of e)u.status=F.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 we(n,async function*(){const u=zi(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:s}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),_r(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:Ze(e,0).byte.from,to:Ze(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.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)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,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=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=F.PARTIALLY_FED,o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===Ie.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,v=h?c.byte.to-s:e.byteLength,S=m<r,E=v<=r;if(c.status===F.DOWNLOADING&&S&&E){c.status=F.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(l.loadedBytes=Math.min(f,r-m),l.loadedBytes>l.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+m+l.feedingBytes,l.loadedBytes-l.feedingBytes),w=l.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(c.status=F.PARTIALLY_FED,l.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)l.fedBytes+=w.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=F.FED,En(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===F.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=F.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===F.PARTIALLY_FED||e.status===F.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=F.NONE),e.status=F.PARTIALLY_EJECTED):e.status=F.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=fn(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?we(this.destroyAbortController.signal,async function*(){const o=zi(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&&Wt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(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=En(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===F.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===F.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===F.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===F.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=fn(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==F.FED&&a!==F.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1||this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status=F.PARTIALLY_EJECTED:r.status=F.NONE)}}}var Rr=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},iv=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?br.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Jt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Jt||(Jt={}));class sv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Zt,this.subscription=new ie,this.fetchManifest=we(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Rr(a));const n=yield Si(a,{signal:this.abortAllController.signal}).catch(ui);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=we(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Jt.HEADER:Jt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;let g=r;const m=new Headers;if(n)switch(a){case Jt.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case Jt.PARAM:{const I=new URL(g,location.href);I.searchParams.append("bytes",`${n.from}-${n.to}`),g=I.toString();break}default:U(a)}this.requestQuic&&(g=Rr(g));let v=this.abortAllController.signal,S;if(d){const I=new Zt;if(S=N(C(this.abortAllController.signal,"abort"),C(d,"abort")).subscribe(()=>{try{I.abort()}catch(se){ui(se)}}),this.abortAllController.signal.aborted||d.aborted)try{I.abort()}catch(se){ui(se)}v=I.signal}const E=ne(),A=yield Si(g,{priority:u,headers:m,signal:v}).catch(ui),w=ne();if(!A)return S==null||S.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));if(this.onHeadersReceived(A.headers),!o&&!l)return S==null||S.unsubscribe(),A.arrayBuffer();const[k,q]=A.body.tee(),j=k.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,c));let K=0,G=new Uint8Array(0),J=!1;const Z=I=>{S==null||S.unsubscribe(),J=!0,ui(I)},M=we(v,async function*({done:I,value:se}){if(K===0&&this.lastRequestFirstBytes$.next(ne()-E),v.aborted){S==null||S.unsubscribe();return}if(!I&&se){const B=new Uint8Array(G.length+se.length);B.set(G),B.set(se,G.length),G=B,K+=se.byteLength,o==null||o(new DataView(G.buffer),K),yield j==null?void 0:j.read().then(M,Z)}}.bind(this));return yield j==null?void 0:j.read().then(M,Z),S==null||S.unsubscribe(),J?null:G.buffer}.bind(this)),this.fetchByteRangeRepresentation=we(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Ie.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,g;r.indexRange&&(f=r.indexRange.from,g=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(g,d))),l=Math.min(l,0);const m=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!m)return null;const v=new DataView(m,u-l,d-l+1);if(!a.validateData(v))throw new Error("Invalid media file");const S=a.parseInit(v),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(m,E.from-l,E.to-E.from+1);else{const k=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!k)return null;A=new DataView(k)}const w=a.parseSegments(A,S,E);return{init:S,dataView:new DataView(m),segments:w}}.bind(this)),this.fetchTemplateRepresentation=we(this.abortAllController.signal,async function*(r,a){if(r.type!==Ie.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:F.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=iv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var r,a;const{type:n}=e;switch(n){case Ie.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ie.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:U(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ui=i=>{if(!_r(i))throw i},Qt=1e3,ds=(i,e,t)=>t*e+(1-t)*i,Uo=(i,e)=>i.reduce((t,s)=>t+s,0)/e,rv=(i,e,t,s)=>{let r=0,a=t;const n=Uo(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class sa{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new We(`raw_${s}`),this.smoothedSeries$=new We(`smoothed_${s}`),this.reportedSeries$=new We(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Q(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 av extends sa{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ds(this.slow,e,this.params.emaAlphaSlow),this.fast=ds(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class nv extends sa{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Uo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ds(this.emaSmoothed,e,this.params.emaAlpha);const s=rv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class ov extends sa{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?ds(this.smoothed,e,this.params.emaAlpha):e}}class Ir{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new av({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new nv({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ov({initial:e,label:"liveEdgeDelay",...t})}}const dv=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Tt=()=>window.ManagedMediaSource||window.MediaSource,Ho=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},lv=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},uv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,An=["timeupdate","progress","play","seeked","stalled","waiting"];var _e;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(_e||(_e={}));let cv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ie,this.representationSubscription=new ie,this.state$=new ue(_e.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.error$=new R,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new R,this.gapWatchdogStarted=!1,this.destroyController=new Zt,this.initManifest=we(this.destroyController.signal,async function*(t,s,r){var a;this.element=t,this.manifestUrlString=Fe(s,r,me.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(_e.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(_e.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=we(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n})});if(!s)return null;let r;try{r=Jm(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:_.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=Tt())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Se.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:rs(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=we(this.destroyController.signal,async function*(t,s,r){var a;P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(_e.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(C(m,"error").pipe(ce(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:_.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?uv():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Ho())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $n(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],D(s)&&(this.audioBufferManager=new $n(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(fi(Qt).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=on(this.manifestUrlString,me.DASH_CMAF_OFFSET_P);this.manifestUrlString=Fe(this.manifestUrlString,S+Qt,me.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(N(...An.filter(m=>m!=="waiting").map(m=>C(this.element,m))).pipe($(m=>this.element?pi(this.element.buffered,this.element.currentTime*1e3):0),he(),ce(m=>!!m),vi(m=>{var v;(v=this.stallWatchdogSubscription)===null||v===void 0||v.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ce(v=>this.isActiveLowLatency&&!!v)).subscribe(v=>this.liveEstimatedDelay.next(v))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(v=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=v-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),dv(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,E;let A=0;if(v){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(q=>{var j,K;return(K=(j=q.getLiveSegmentsToLoadState(this.manifest))===null||j===void 0?void 0:j.to)!==null&&K!==void 0?K:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let m=0;this.representationSubscription.add(Re({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(vd(Qt)).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=on(this.manifestUrlString,me.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,j=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,K=this.isActiveLowLatency?S:v;let G=je.None;if(this.isActiveLowLatency?G=je.ActiveLowLatency:K<k+j&&K>=k?G=je.LiveWithTargetOffset:A!==0&&K<k&&(G=je.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),G===je.LiveForwardBuffering||G===je.LiveWithTargetOffset){const J=m-(k+q),Z=this.normolizeLiveOffset(Math.trunc(A+J/E)),M=Math.abs(Z-A);let I;!v||M<=this.tuning.dashCmafLive.offsetCalculationError?I=A:Z>0&&M>this.tuning.dashCmafLive.offsetCalculationError?I=Z:I=0,this.manifestUrlString=Fe(this.manifestUrlString,I,me.DASH_CMAF_OFFSET_P)}G!==je.None&&G!==je.ActiveLowLatency&&(m=0,this.updateLive())}))}const d=N(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),l=N(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe($(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(N(this.forceEnded$,Re({allBuffersFull:d,someBufferEnded:l}).pipe(ce(({allBuffersFull:m,someBufferEnded:v})=>m&&v))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(v=>!v.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(v){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(N(...this.bufferManagers.map(m=>m.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(m=>{var v;return(v=this.source)===null||v===void 0?void 0:v.addEventListener("sourceopen",m)}));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),g=this.manifest.representations.video.reduce(h,c);(f||g)&&(this.source.duration=Math.max(f,g)/1e3),this.audioBufferManager&&D(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(_e.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=fi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ir.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=Fe(this.manifestUrlString,n,me.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.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(_e.RUNNING),this.subscription.add(N(...An.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&xr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=Qt,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=fi(Qt).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:_.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){const s={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),xr(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(_e.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class hv{constructor(e,t){this.fov=e,this.orientation=t}}class fv{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var pv=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
37
|
+
`}),B}return d==null||d.recordSwitch(I),I};var Je=i=>new URL(i).hostname;const cn=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Mt=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!cn(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return cn(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function Te(){return ne()}function xo(i){return Te()-i}function hn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,l=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return l&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fp(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Zi(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,l=!1,d=0,u,c,h=!1,f="arraybuffer",g=7e3,m=2e3,v=()=>{if(l)return;P(u);const M=xo(u);let I;if(M<m){I=m-M,setTimeout(v,I);return}m*=2,m>g&&(m=g),n&&n.abort(),n=new r,j()};const S=M=>(a=M,Z),E=M=>(c=M,Z),A=()=>(f="json",Z),w=()=>{if(!l){if(--d>=0){v(),s&&s();return}l=!0,c&&c(),t&&t()}},k=M=>(h=M,Z),j=()=>{u=Te(),n=new r,n.open("get",i);let M=0,I,se=0;const B=()=>(P(u),Math.max(u,Math.max(I||0,se||0)));if(a&&n.addEventListener("progress",x=>{const X=Te();a.updateChunk&&x.loaded>M&&(a.updateChunk(B(),x.loaded-M),M=x.loaded,I=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(l)return;P(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&a){const X=n.response.byteLength-M;X&&a.updateChunk&&a.updateChunk(B(),X)}n.responseType==="json"&&!Object.values(n.response).length?w():(c&&c(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const x=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=Te(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),Z},Z={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:M=>(d=M,Z),withRetryInterval:(M,I)=>(D(M)&&(m=M),D(I)&&(g=I),Z),withTimeout:M=>(o=M,Z),withFinally:E,send:j,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return Z}const pp=100,mp=2e3,vp=500;let gp=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-vp;if(t-e>mp){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const l=a.bytes*n/o;r+=l,a.start=t,a.bytes-=l}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>pp&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class Sp{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=Te(),r=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=l=>{e._complete=1,e._responseData=l,e._downloadTime=Te()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ui=1e4,ir=3,bp=6e4,yp=10,Tp=1,Ep=500;class $p{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new gp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=hn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||D(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{fp(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sp(ir,Ui,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,l=null,d=null,u=!1;const c=()=>{const w=a&&(!u||u===this.rep);return w||t("Not running!"),w},h=(w,k,j)=>{l&&l.abort(),l=Zi(this.urlResolver.resolve(w,!1),k,j,()=>this._retryCallback()).withTimeout(Ui).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ir).withFinally(()=>{l=null}).send()},f=(w,k,j)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},g=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},m=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const j=Te()-1e4;let q=0;for(let G=0;G<this.bufferStates.length;G++){const J=this.bufferStates[G];w=Math.min(w,J.buf),J.ts<j&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${w} drop=${q} jitter=${this.sourceJitter}`);let K=w-Tp;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?g(1.15):K>1?g(1.1):K>.3?g(1.05):g(1)}},S=w=>{let k;const j=()=>k&&k.start?k.start.length:0,q=x=>k.start[x]/1e3,K=x=>k.dur[x]/1e3,G=x=>k.fragIndex+x,J=(x,X)=>({chunkIdx:G(x),startTS:q(x),dur:K(x),discontinuity:X}),Z=()=>{let x=0;if(k&&k.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=X;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=k.dur.length-1;for(;ve>=0&&(fe-=k.dur[ve],!(fe<=0));--ve);x=Math.min(ve,k.dur.length-1-oe),x=Math.max(x,0)}return J(x,!0)},M=x=>{const X=j();if(!(X<=0)){if(D(x)){for(let oe=0;oe<X;oe++)if(q(oe)>x)return J(oe)}return Z()}},I=x=>{const X=j(),oe=x?x.chunkIdx+1:0,fe=oe-k.fragIndex;if(!(X<=0)){if(!x||fe<0||fe-X>yp)return t(`Resync: offset=${fe} bChunks=${X} chunk=`+JSON.stringify(x)),Z();if(!(fe>=X))return J(oe-k.fragIndex,!1)}},se=(x,X,oe)=>{d&&d.abort(),d=Zi(this.urlResolver.resolve(x,!0,this.lowLatency),X,oe,()=>this._retryCallback()).withTimeout(Ui).withRetryCount(ir).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,X)=>{se(w,oe=>{if(!c())return;k=oe;const fe=!!k.lowLatency;fe!==this.lowLatency&&m(fe);let ve=0;for(let He=0;He<k.dur.length;++He)ve+=k.dur[He];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,x(M(X))},()=>this._handleNetworkError())},nextChunk:I}},E=()=>{a=!1,o&&o.abort(),l&&l.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:w=>{const{videoElement:k,logger:j}=this.params;let q=S(e.jidxUrl),K,G,J,Z,M=0,I,se,B;const x=()=>{I&&(clearTimeout(I),I=void 0);const z=Math.max(Ep,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+z,$e=Te(),ke=Math.min(1e4,be-$e);M=$e;const Nt=()=>{d||c()&&q.seek(()=>{c()&&(M=Te(),X(),x())})};ke>0?I=window.setTimeout(()=>{this.paused?x():Nt()},ke):Nt()},X=()=>{let z;for(;z=q.nextChunk(Z);)Z=z,ni(z);const be=q.nextChunk(J);if(be){if(J&&be.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?x():(E(),this._initPlayerWith(e));return}He(be)}else x()},oe=(z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,ke,Nt;const oi=Xe=>{window.setTimeout(()=>{c()&&oe(z,be)},Xe)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),oi(100);else{const Xe=Te(),De=k.currentTime;!this.paused&&k.buffered.length>1&&se===De&&Xe-B>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),se!==De&&(se=De,B=Xe);const Ft=this._getBufferSizeSec();if(Ft>30)j(`Buffered ${Ft} seconds; delaying appendBuffer`),oi(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Xe,buf:Ft}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(di){if(di.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),Nt=this.sourceBuffer.buffered.length,Nt!==0&&($e=this.sourceBuffer.buffered.start(0),ke=De,ke-$e>4&&this.sourceBuffer.remove($e,ke-3)),oi(1e3);else throw di}}},fe=()=>{G&&K&&(j([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(J)]),oe(G,function(){G=null,X()}))},ve=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),He=z=>{c()&&f(ve(z),(be,$e)=>{if(c()){if($e/=1e3,G=be,J=z,n=z.startTS,$e){const ke=Math.min(10,z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}fe()}},()=>this._handleNetworkError())},ni=z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(z),!1)))},Bt=z=>{c()&&(e.cachedHeader=z,oe(z,()=>{K=!0,fe()}))};a=!0,q.seek(z=>{if(c()){if(M=Te(),!z){x();return}Z=z,!Q(w)||z.startTS>w?He(z):(J=z,X())}},w),e.cachedHeader?Bt(e.cachedHeader):h(e.headerUrl,Bt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),D(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return D(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),g=c/this.bitrate,f>10&&g>.8||f>15&&g>.5||f>20&&g>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const g=Te();if(this.chunkRateEstimator.addInterval(h,g,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:g-h,speed:v}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,l=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(l&&c>o&&xo(n)<3e4)return;s(c)}l=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Zi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Ui).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Mt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((l,d)=>{l.video&&r.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=d,o.push(l))}),o.sort(function(l,d){return l.video&&d.video?d.video.height-l.video.height:d.bitrate-l.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},bp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class _o{constructor(){this.onDroopedVideoFramesLimit$=new R,this.subscription=new ie,this.playing=!1,this.tracks=[],this.forceChecker$=new R,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Pt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&Xt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=pi(this.droppedFramesChecker.checkTime).pipe(ce(()=>this.playing),ce(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Ke(this.droppedFramesChecker.checkTime)),s=N(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>zi(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const _r=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},ai=(i,e)=>new Br(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||_r()))},{...s,...e});r.observe(i);const a=C(document,"visibilitychange").pipe($(n=>!document.hidden||_r())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}});var H;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const Ap=[H.PAUSED,H.PLAYING,H.READY],wp=[H.PAUSED,H.PLAYING,H.READY];class kp{constructor(e){this.subscription=new ie,this.videoState=new ue(H.STOPPED),this.representations$=new y([]),this.textTracksManager=new mt,this.droppedFramesManager=new _o,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Zr,this._dashCb=r=>{var a,n,o,l;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,u=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Ss(c.name))!==null&&n!==void 0?n:kt(c.video),g=c.bitrate/1e3,m={...c.video};if(!f)continue;const v={id:h,quality:f,bitrate:g,size:m};u.push({track:v,representation:c})}this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,u=(l=this.representations$.getValue().find(({representation:c})=>c===d))===null||l===void 0?void 0:l.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),D(u)&&this.params.output.currentVideoTrack$.next(u);break}case"bandwidth":{const{size:d,duration:u}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,u);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(l)};`}),n===p.STOPPED){r!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wp.includes(r)&&(d||u)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&l.state===Y.Requested&&Ap.includes(r)){this.seek(l.position-this.liveOffset.getTotalPausedTime());return}switch(r){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Fe(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(n===p.PAUSED)this.videoState.setState(H.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)})}return;case H.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Fe(this.params.source.url,c))}return;default:return U(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:r})};N(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Ot(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe($(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===H.READY&&this.videoState.setState(H.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Re({zeroTime:this.zeroTime$.pipe(ce(D)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ai(this.video,this.params.desiredState.isLooped,t)).add(Ct(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ri(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ai(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&vd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case H.MANIFEST_READY:case H.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return U(r.to)}},t)).add(N(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ce(["init"])).pipe(Ke(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),It(this.video)}createLiveDashPlayer(){const e=new $p({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),l=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),u=!d&&D(l)?l:bs(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=u==null?void 0:u.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,g=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(h||c!==f)&&this.setVideoTrack(u),g&&this.setAutoQuality(d),h||g||c!==f){const m=(n=o.find(({track:v})=>v.id===c))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===H.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Fe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var qe;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(qe||(qe={}));var ns;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ns||(ns={}));var Ie;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ie||(Ie={}));var F;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(F||(F={}));var ei;(function(i){i.MP4="mp4",i.WEBM="webm"})(ei||(ei={}));var os;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(os||(os={}));var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));var mi=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class fn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Ro extends fn{constructor(){super(),this.listeners||fn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Io=class{constructor(){Object.defineProperty(this,"signal",{value:new Ro,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Io.prototype[Symbol.toStringTag]="AbortController",Ro.prototype[Symbol.toStringTag]="AbortSignal");function Co(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Pp(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Co({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,u){let c;u&&u.signal&&(c=u.signal,delete u.signal);const h=new t(d,u);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(l,d)=>{const u=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.signal:void 0;if(u){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(u.aborted)return Promise.reject(c);const h=new Promise((f,g)=>{u.addEventListener("abort",()=>g(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(l,d)])}return n(l,d)},Request:a}}const ys=Co({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Oo=ys?Pp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bi=ys?Oo.fetch:window.fetch;ys?Oo.Request:window.Request;const Zt=ys?Io:window.AbortController;var Rr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Dp=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Lp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",pn=Lp?Dp:window.requestIdleCallback;var sr,rr;const xp=16;let Mo=!1;try{Mo=Mr().browser===Nn.Safari&&parseInt((rr=(sr=navigator.userAgent.match(/Version\/(\d+)/))===null||sr===void 0?void 0:sr[1])!==null&&rr!==void 0?rr:"",10)<=xp}catch(i){console.error(i)}class _p{constructor(e){this.bufferFull$=new R,this.error$=new R,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:_.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Mo&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:_.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:U(t)}}}var mn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Me{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.size32=s<=e.buffer.byteLength?s:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Bo extends Me{}class Rp extends Me{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class Ip extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Cp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Op extends Me{constructor(e,t){super(e,t),this.data=this.content}}class dt extends Me{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class No extends dt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const l=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class Mp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Bp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var wt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(wt||(wt={}));class Np extends dt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=wt.MONOSCOPIC;break;case 1:this.stereoMode=wt.TOP_BOTTOM;break;case 2:this.stereoMode=wt.LEFT_RIGHT;break;case 3:this.stereoMode=wt.STEREO_CUSTOM;break;case 4:this.stereoMode=wt.RIGHT_LEFT;break}this.cursor+=1}}class Fp extends dt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Vp extends dt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Up extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Hp extends dt{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Gp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Yp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class jp extends dt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class qp extends Me{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Wp extends dt{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class zp extends dt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qp extends dt{constructor(e,t){super(e,t),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let s=0;s<this.sampleCount;s++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}var de;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UnknownBox="unknown"})(de||(de={}));const Kp={[de.FtypBox]:Rp,[de.MoovBox]:Ip,[de.MoofBox]:Cp,[de.MdatBox]:Op,[de.SidxBox]:No,[de.TrakBox]:Mp,[de.MdiaBox]:Up,[de.MfhdBox]:jp,[de.TkhdBox]:Hp,[de.TrafBox]:qp,[de.TfhdBox]:Wp,[de.TfdtBox]:zp,[de.TrunBox]:Qp,[de.MinfBox]:Gp,[de.Sv3dBox]:Bp,[de.St3dBox]:Np,[de.PrhdBox]:Fp,[de.ProjBox]:Yp,[de.EquiBox]:Vp,[de.UnknownBox]:Bo};class Dt{constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;){const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(t.push(n),!n.size)break;s+=n.size}return t}createBox(e,t){const s=Kp[e];return s?new s(t,new Dt):new Bo(t,new Dt)}}class ta{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const Jp=new TextDecoder("ascii"),Xp=i=>Jp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Zp=i=>{const e=new No(i,new Dt);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:F.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},em=i=>{const t=new Dt().parse(i),s=new ta(t),r=s.findAll("mdat"),a=s.findAll("moof");if(!(r.length&&a.length))return null;const n=a[0],o=r[r.length-1],l=n.source.byteOffset,u=o.source.byteOffset-n.source.byteOffset+o.size;return new DataView(i.buffer,l,u)},tm=(i,e)=>{const s=new Dt().parse(i),a=new ta(s).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),l=a[a.length-1].children.find(c=>c.type==="trun");let d=0;return l.sampleDuration.length?d=l.sampleDuration.reduce((c,h)=>c+h,0):d=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},im=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Dt().parse(i),r=new ta(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const l=r.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},sm={validateData:Xp,parseInit:im,getIndexRange:()=>{},parseSegments:Zp,parseFeedableSegmentChunk:em,getSegmentEndTime:tm};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var L;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(L||(L={}));const vn={[T.EBML]:{type:L.Master},[T.EBMLVersion]:{type:L.UnsignedInteger},[T.EBMLReadVersion]:{type:L.UnsignedInteger},[T.EBMLMaxIDLength]:{type:L.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:L.UnsignedInteger},[T.DocType]:{type:L.String},[T.DocTypeVersion]:{type:L.UnsignedInteger},[T.DocTypeReadVersion]:{type:L.UnsignedInteger},[T.Void]:{type:L.Binary},[T.Segment]:{type:L.Master},[T.SeekHead]:{type:L.Master},[T.Seek]:{type:L.Master},[T.SeekID]:{type:L.Binary},[T.SeekPosition]:{type:L.UnsignedInteger},[T.Info]:{type:L.Master},[T.TimestampScale]:{type:L.UnsignedInteger},[T.Duration]:{type:L.Float},[T.Tracks]:{type:L.Master},[T.TrackEntry]:{type:L.Master},[T.Video]:{type:L.Master},[T.Projection]:{type:L.Master},[T.ProjectionType]:{type:L.UnsignedInteger},[T.ProjectionPrivate]:{type:L.Master},[T.Chapters]:{type:L.Master},[T.Cluster]:{type:L.Master},[T.Timestamp]:{type:L.UnsignedInteger},[T.SilentTracks]:{type:L.Master},[T.SilentTrackNumber]:{type:L.UnsignedInteger},[T.Position]:{type:L.UnsignedInteger},[T.PrevSize]:{type:L.UnsignedInteger},[T.SimpleBlock]:{type:L.Binary},[T.BlockGroup]:{type:L.Master},[T.EncryptedBlock]:{type:L.Binary},[T.Attachments]:{type:L.Master},[T.Tags]:{type:L.Master},[T.Cues]:{type:L.Master},[T.CuePoint]:{type:L.Master},[T.CueTime]:{type:L.UnsignedInteger},[T.CueTrackPositions]:{type:L.Master},[T.CueTrack]:{type:L.UnsignedInteger},[T.CueClusterPosition]:{type:L.UnsignedInteger},[T.CueRelativePosition]:{type:L.UnsignedInteger},[T.CueDuration]:{type:L.UnsignedInteger},[T.CueBlockNumber]:{type:L.UnsignedInteger},[T.CueCodecState]:{type:L.UnsignedInteger},[T.CueReference]:{type:L.Master},[T.CueRefTime]:{type:L.UnsignedInteger}},Fo=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=ds(i,t),r=s in vn,a=r?vn[s].type:L.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const l=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,u=ds(l),c=d*2**((o-1)*8)+u,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},ds=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{const t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(i,e)=>{switch(e){case L.SignedInteger:return i.getInt8(0);case L.UnsignedInteger:return ds(i);case L.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case L.String:return new TextDecoder("ascii").decode(i);case L.UTF8:return new TextDecoder("utf-8").decode(i);case L.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case L.Master:return i;case L.Binary:return i;default:U(e)}},ti=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Fo(s);if(!e(r))return;r.type===L.Master&&ti(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},rm=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Fo(i);return ti(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=ze(o,n):a===T.DocType?t=ze(o,n):a===T.DocTypeReadVersion&&(s=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Vo=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],am=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],nm=i=>{let e,t,s,r,a=!1,n=!1,o=!1,l,d,u=!1;const c=0;return ti(i,({tag:h,type:f,value:g,valueSize:m})=>{if(h===T.SeekID){const v=ze(g,f);d=ds(v)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=g.byteOffset,t=g.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=ze(g,f):h===T.Duration?r=ze(g,f):h===T.SeekPosition&&d===T.Cues?l=ze(g,f):h===T.Tracks?ti(g,({tag:v,type:S,value:E})=>v===T.ProjectionType?(u=ze(E,S)===1,!1):!0):a&&n&&Vo.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:l,is3dVideo:u,stereoMode:c,projectionType:os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},om=i=>{if(Q(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dm=(i,e)=>{let t=!1,s=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ti(i,({tag:o,type:l,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=ze(d,l));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=ze(d,l));break;default:t&&Vo.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,l)=>{const{time:d,position:u}=o,c=a[l+1];return{status:F.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},lm=i=>{let e=0,t=!1;try{ti(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):am.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},um={validateData:rm,parseInit:nm,getIndexRange:om,parseSegments:dm,parseFeedableSegmentChunk:lm};var cm=Lt,hm=cs,fm=Ue,pm=fm("match"),mm=function(i){var e;return cm(i)&&((e=i[pm])!==void 0?!!e:hm(i)=="RegExp")},vm=gs,gm=String,Sm=function(i){if(vm(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return gm(i)},bm=_t,ym=function(){var i=bm(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Tm=nt,Em=ot,$m=Hr,Am=ym,gn=RegExp.prototype,wm=function(i){var e=i.flags;return e===void 0&&!("flags"in gn)&&!Em(i,"flags")&&$m(gn,i)?Tm(Am,i):e},ia=at,km=ps,Pm=Math.floor,ar=ia("".charAt),Dm=ia("".replace),nr=ia("".slice),Lm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xm=/\$([$&'`]|\d{1,2})/g,_m=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,l=xm;return r!==void 0&&(r=km(r),l=Lm),Dm(a,l,function(d,u){var c;switch(ar(u,0)){case"$":return"$";case"&":return i;case"`":return nr(e,0,t);case"'":return nr(e,n);case"<":c=r[nr(u,1,-1)];break;default:var h=+u;if(h===0)return d;if(h>o){var f=Pm(h/10);return f===0?d:f<=o?s[f-1]===void 0?ar(u,1):s[f-1]+ar(u,1):d}c=s[h-1]}return c===void 0?"":c})},Rm=vs,Im=nt,sa=at,Sn=Fr,Cm=Oe,Om=hs,Mm=mm,qt=Sm,Bm=fs,Nm=wm,Fm=_m,Vm=Ue,Um=Vm("replace"),Hm=TypeError,Uo=sa("".indexOf),Gm=sa("".replace),bn=sa("".slice),Ym=Math.max,yn=function(i,e,t){return t>i.length?-1:e===""?t:Uo(i,e,t)};Rm({target:"String",proto:!0},{replaceAll:function(e,t){var s=Sn(this),r,a,n,o,l,d,u,c,h,f=0,g=0,m="";if(!Om(e)){if(r=Mm(e),r&&(a=qt(Sn(Nm(e))),!~Uo(a,"g")))throw Hm("`.replaceAll` does not allow non-global regexes");if(n=Bm(e,Um),n)return Im(n,e,s,t);if(r)return Gm(qt(s),e,t)}for(o=qt(s),l=qt(e),d=Cm(t),d||(t=qt(t)),u=l.length,c=Ym(1,u),f=yn(o,l,0);f!==-1;)h=d?qt(t(l,f,o)):Fm(l,o,f,[],void 0,t),m+=bn(o,g,f)+h,g=f+u,f=yn(o,l,f+c);return g<o.length&&(m+=bn(o,g)),m}});var jm=Lo,qm=jm("String","replaceAll"),Wm=qm,zm=Wm,Qm=zm,Km=Qm,Tn=Nr(Km);const Jm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},En=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},zt=(i,e)=>{let t=i;t=Tn(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Tn(t,n,(o,l)=>Q(a)?o:Q(l)?a:a.padStart(parseInt(l,10),"0"))}return t},Xm=(i,e)=>{var t,s,r,a,n,o,l,d,u,c,h,f,g,m,v,S,E,A,w,k,j,q,K,G,J,Z,M,I,se,B,x,X,oe,fe,ve,He,ni,Bt,z,be,$e,ke;const oi=new DOMParser().parseFromString(i,"application/xml"),Xe={video:[],audio:[],text:[]},De=oi.children[0],Ft=De.getElementsByTagName("Period")[0],di=(r=(s=(t=De.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",zo=Ft.children,Qo=De.getAttribute("type")==="dynamic",na=De.getAttribute("availabilityStartTime"),Ko=na?new Date(na).getTime():void 0;let vt;const oa=De.getAttribute("mediaPresentationDuration"),da=Ft.getAttribute("duration"),Ts=De.getElementsByTagName("vk:Attrs")[0],la=Ts==null?void 0:Ts.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(oa)vt=En(oa);else if(da){const Le=En(da);D(Le)&&(vt=Le)}else la&&(vt=parseInt(la,10));let Jo=0;const Es=(n=(a=De.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Xo=Es.includes(ns.WEBM_AS_IN_FFMPEG)||Es.includes(ns.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const Le of zo){const wi=Le.getAttribute("mimeType"),Zo=Le.getAttribute("codecs"),ua=(o=Le.getAttribute("contentType"))!==null&&o!==void 0?o:wi==null?void 0:wi.split("/")[0],ed=(d=(l=Le.getAttribute("profiles"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[],ca=Le.querySelectorAll("Representation"),td=Le.querySelector("SegmentTemplate");if(ua===Se.TEXT){for(const pe of ca){const lt=pe.getAttribute("id")||"",ki=Le.getAttribute("lang"),Vt=Le.getAttribute("label"),$s=(h=(c=(u=pe.querySelector("BaseURL"))===null||u===void 0?void 0:u.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",As=new URL($s||di,e).toString(),Pi=lt.includes("_auto");Xe[Se.TEXT].push({id:lt,lang:ki,label:Vt,isAuto:Pi,kind:Se.TEXT,url:As})}continue}for(const pe of ca){const lt=(f=pe.getAttribute("mimeType"))!==null&&f!==void 0?f:wi,ki=(m=(g=pe.getAttribute("codecs"))!==null&&g!==void 0?g:Zo)!==null&&m!==void 0?m:"",Vt=(S=(v=pe.getAttribute("contentType"))!==null&&v!==void 0?v:lt==null?void 0:lt.split("/")[0])!==null&&S!==void 0?S:ua,$s=(A=(E=Le.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],As=parseInt((w=pe.getAttribute("width"))!==null&&w!==void 0?w:"",10),Pi=parseInt((k=pe.getAttribute("height"))!==null&&k!==void 0?k:"",10),ha=parseInt((j=pe.getAttribute("bandwidth"))!==null&&j!==void 0?j:"",10)/1e3,fa=(q=pe.getAttribute("frameRate"))!==null&&q!==void 0?q:"",id=(K=pe.getAttribute("quality"))!==null&&K!==void 0?K:void 0,sd=fa?Jm(fa):void 0,rd=(G=pe.getAttribute("id"))!==null&&G!==void 0?G:(Jo++).toString(10),ad=Vt==="video"?`${Pi}p`:Vt==="audio"?`${ha}Kbps`:ki,nd=`${rd}@${ad}`,od=(M=(Z=(J=pe.querySelector("BaseURL"))===null||J===void 0?void 0:J.textContent)===null||Z===void 0?void 0:Z.trim())!==null&&M!==void 0?M:"",pa=new URL(od||di,e).toString(),dd=[...Es,...ed,...$s];let ws;const ld=pe.querySelector("SegmentBase"),gt=(I=pe.querySelector("SegmentTemplate"))!==null&&I!==void 0?I:td;if(ld){const St=(B=(se=pe.querySelector("SegmentBase Initialization"))===null||se===void 0?void 0:se.getAttribute("range"))!==null&&B!==void 0?B:"",[bt,Ps]=St.split("-").map(Ut=>parseInt(Ut,10)),ut={from:bt,to:Ps},li=(x=pe.querySelector("SegmentBase"))===null||x===void 0?void 0:x.getAttribute("indexRange"),[Ds,Di]=li?li.split("-").map(Ut=>parseInt(Ut,10)):[],ui=li?{from:Ds,to:Di}:void 0;ws={type:Ie.BYTE_RANGE,url:pa,initRange:ut,indexRange:ui}}else if(gt){const St={representationId:(X=pe.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(oe=pe.getAttribute("bandwidth"))!==null&&oe!==void 0?oe:void 0},bt=parseInt((fe=gt.getAttribute("timescale"))!==null&&fe!==void 0?fe:"",10),Ps=(ve=gt.getAttribute("initialization"))!==null&&ve!==void 0?ve:"",ut=gt.getAttribute("media"),li=(ni=parseInt((He=gt.getAttribute("startNumber"))!==null&&He!==void 0?He:"",10))!==null&&ni!==void 0?ni:1,Ds=zt(Ps,St);if(!ut)throw new ReferenceError("No media attribute in SegmentTemplate");const Di=(Bt=gt.querySelectorAll("SegmentTimeline S"))!==null&&Bt!==void 0?Bt:[],ui=[];let Ut=0,Ls="",xs=0;if(Di.length){let Li=li,Be=0;for(const Ht of Di){const Ge=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10),yt=parseInt((be=Ht.getAttribute("r"))!==null&&be!==void 0?be:"",10)||0,xi=parseInt(($e=Ht.getAttribute("t"))!==null&&$e!==void 0?$e:"",10);Be=Number.isFinite(xi)?xi:Be;const _s=Ge/bt*1e3,Rs=Be/bt*1e3;for(let _i=0;_i<yt+1;_i++){const cd=zt(ut,{...St,segmentNumber:Li.toString(10),segmentTime:(Be+_i*Ge).toString(10)}),ma=(Rs!=null?Rs:0)+_i*_s,hd=ma+_s;Li++,ui.push({time:{from:ma,to:hd},url:cd})}Be+=(yt+1)*Ge,Ut+=(yt+1)*_s}xs=Be/bt*1e3,Ls=zt(ut,{...St,segmentNumber:Li.toString(10),segmentTime:Be.toString(10)})}else if(D(vt)){const Be=parseInt((ke=gt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/bt*1e3,Ht=Math.ceil(vt/Be);let Ge=0;for(let yt=1;yt<Ht;yt++){const xi=zt(ut,{...St,segmentNumber:yt.toString(10),segmentTime:Ge.toString(10)});ui.push({time:{from:Ge,to:Ge+Be},url:xi}),Ge+=Be}xs=Ge,Ls=zt(ut,{...St,segmentNumber:Ht.toString(10),segmentTime:Ge.toString(10)})}const ud={time:{from:xs,to:1/0},url:Ls};ws={type:Ie.TEMPLATE,baseUrl:pa,segmentTemplateUrl:ut,initUrl:Ds,totalSegmentsDurationMs:Ut,segments:ui,nextSegmentBeyondManifest:ud,timescale:bt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Vt||!lt)continue;const ks={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[Vt];ks&&Xe[ks].push({id:nd,kind:ks,segmentReference:ws,profiles:dd,duration:vt,bitrate:ha,mime:lt,codecs:ki,width:As,height:Pi,fps:sd,quality:id})}}return{dynamic:Qo,liveAvailabilityStartTime:Ko,duration:vt,container:Xo,representations:Xe}},Zm=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ss(a):void 0)!==null&&n!==void 0?n:kt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},ev=({id:i,bitrate:e})=>({id:i,bitrate:e}),tv=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Ze(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Ze(i,-1)},iv=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),$n=i=>"url"in i,Wt=i=>i.type===Ie.TEMPLATE,Ir=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class An{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new R,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Zt,this.destroyAbortController=new Zt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=we(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 _p(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,mn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),g=this.segments.get(h.id),m=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(g,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(g,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=we(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),g=this.initData.get(c);if(Q(g)||Q(f)?yield this.loadInit(h,"high",!1):g instanceof Promise&&(yield g),f=this.segments.get(c),P(f,"No segments for starting representation"),g=this.initData.get(c),!g||!(g instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(g,this.downloadAbortController.signal);const m=this.getCurrentPosition();D(m)&&(this.isLive||(f.forEach(v=>v.status=F.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=we(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const E of this.representations.keys()){const A=c.find(j=>j.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!Wt(w.segmentReference))return;const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,g=this.representations.get(f);P(g);const m=this.segments.get(f);P(m,"No segments for starting representation");const v=this.initData.get(f);if(P(v,"No init buffer for starting representation"),!(v instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,g),yield this.sourceBufferTaskQueue.append(v,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=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case ei.MP4:this.containerParser=sm;break;case ei.WEBM:this.containerParser=um;break;default:U(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Zt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=mi(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&u>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&mn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=mi(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const u=Ze(o,0);u&&u.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===F.FED&&!o.length&&mi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const l=Ze(s,-1);l&&l.status===F.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===l))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;D(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Wt(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:F.NONE,size:void 0})),l=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=Ze(l,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,u=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(u===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(u+1);this.segments.set(n.id,[...l,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!Wt(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=zt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],l=o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||o.push({status:F.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(l=>l.time.from<=e&&l.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},g)=>{const m=h<=s&&f>=s,v=h>s||m||g===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===F.NONE||c===F.PARTIALLY_EJECTED&&v&&E&&this.sourceBuffer&&!Rr(this.sourceBuffer.buffered,s))&&v&&E});if(r===-1)return[];if(t!==Ie.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=u);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===F.NONE||h.status===F.PARTIALLY_EJECTED)l.push(h);else break}return l}async loadSegments(e,t,s="auto"){t.segmentReference.type===Ie.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=F.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:l,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await we(o,async function*(){const u=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const u=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:l,priority:s,isLowLatency:this.isActiveLowLatency()});if(!u)return;const c=new DataView(u);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}l&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=F.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(u){this.abortActiveSegments([e]),Ir(u)||this.failedDownloads++}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const l of e)l.status=F.DOWNLOADING,this.activeSegments.add({segment:l,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 we(n,async function*(){const l=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Ir(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:Ze(e,0).byte.from,to:Ze(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(l,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.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)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:l}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),u=this.containerParser.parseFeedableSegmentChunk(d);u!=null&&u.byteLength&&(l.status=F.PARTIALLY_FED,o.feedingBytes+=u.byteLength,await this.sourceBufferTaskQueue.append(u),o.fedBytes+=u.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const l=o.segmentReference.type,d=e.byteLength;for(const u of this.activeSegments){const{segment:c}=u,h=l===Ie.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(u.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,v=h?c.byte.to-s:e.byteLength,S=m<r,E=v<=r;if(c.status===F.DOWNLOADING&&S&&E){c.status=F.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(u,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(u.loadedBytes=Math.min(f,r-m),u.loadedBytes>u.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+m+u.feedingBytes,u.loadedBytes-u.feedingBytes),w=u.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(c.status=F.PARTIALLY_FED,u.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)u.fedBytes+=w.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=F.FED,$n(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===F.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=F.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===F.PARTIALLY_FED||e.status===F.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=F.NONE),e.status=F.PARTIALLY_EJECTED):e.status=F.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=pn(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?we(this.destroyAbortController.signal,async function*(){const o=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:l,dataView:d,segments:u}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=u;this.isLive&&Wt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const l=d=>{var u;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=$n(d)?(u=d.size)!==null&&u!==void 0?u:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const u of d){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;u.status===F.FED&&l(u)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const u of d){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;u.status===F.FED&&l(u)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=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===F.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(c)){a=u,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const c of u)c.time.from>e+d&&c.status===F.FED&&l(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=pn(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==F.FED&&a!==F.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),l=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);l||(d.length===1||this.gaps.some(u=>u.from===r.time.from||u.to===r.time.to)?r.status=F.PARTIALLY_EJECTED:r.status=F.NONE)}}}var Cr=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},sv=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?yr.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Jt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Jt||(Jt={}));class rv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Zt,this.subscription=new ie,this.fetchManifest=we(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Cr(a));const n=yield bi(a,{signal:this.abortAllController.signal}).catch(ci);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=we(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Jt.HEADER:Jt.PARAM,range:n,onProgress:o,priority:l="auto",signal:d,measureThroughput:u=!0,isLowLatency:c=!1}={}){var h,f;let g=r;const m=new Headers;if(n)switch(a){case Jt.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case Jt.PARAM:{const I=new URL(g,location.href);I.searchParams.append("bytes",`${n.from}-${n.to}`),g=I.toString();break}default:U(a)}this.requestQuic&&(g=Cr(g));let v=this.abortAllController.signal,S;if(d){const I=new Zt;if(S=N(C(this.abortAllController.signal,"abort"),C(d,"abort")).subscribe(()=>{try{I.abort()}catch(se){ci(se)}}),this.abortAllController.signal.aborted||d.aborted)try{I.abort()}catch(se){ci(se)}v=I.signal}const E=ne(),A=yield bi(g,{priority:l,headers:m,signal:v}).catch(ci),w=ne();if(!A)return S==null||S.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));if(this.onHeadersReceived(A.headers),!o&&!u)return S==null||S.unsubscribe(),A.arrayBuffer();const[k,j]=A.body.tee(),q=k.getReader();u&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(j,c));let K=0,G=new Uint8Array(0),J=!1;const Z=I=>{S==null||S.unsubscribe(),J=!0,ci(I)},M=we(v,async function*({done:I,value:se}){if(K===0&&this.lastRequestFirstBytes$.next(ne()-E),v.aborted){S==null||S.unsubscribe();return}if(!I&&se){const B=new Uint8Array(G.length+se.length);B.set(G),B.set(se,G.length),G=B,K+=se.byteLength,o==null||o(new DataView(G.buffer),K),yield q==null?void 0:q.read().then(M,Z)}}.bind(this));return yield q==null?void 0:q.read().then(M,Z),S==null||S.unsubscribe(),J?null:G.buffer}.bind(this)),this.fetchByteRangeRepresentation=we(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Ie.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,g;r.indexRange&&(f=r.indexRange.from,g=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(g,d))),u=Math.min(u,0);const m=yield this.fetch(r.url,{range:{from:u,to:c},priority:n,measureThroughput:!1});if(!m)return null;const v=new DataView(m,l-u,d-u+1);if(!a.validateData(v))throw new Error("Invalid media file");const S=a.parseInit(v),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(m,E.from-u,E.to-E.from+1);else{const k=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!k)return null;A=new DataView(k)}const w=a.parseSegments(A,S,E);return{init:S,dataView:new DataView(m),segments:w}}.bind(this)),this.fetchTemplateRepresentation=we(this.abortAllController.signal,async function*(r,a){if(r.type!==Ie.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:F.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=sv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var r,a;const{type:n}=e;switch(n){case Ie.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ie.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:U(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ci=i=>{if(!Ir(i))throw i},Qt=1e3,ls=(i,e,t)=>t*e+(1-t)*i,Ho=(i,e)=>i.reduce((t,s)=>t+s,0)/e,av=(i,e,t,s)=>{let r=0,a=t;const n=Ho(i,e),o=e<s?e:s;for(let l=0;l<o;l++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class ra{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new We(`raw_${s}`),this.smoothedSeries$=new We(`smoothed_${s}`),this.reportedSeries$=new We(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Q(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 nv extends ra{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ls(this.slow,e,this.params.emaAlphaSlow),this.fast=ls(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ov extends ra{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Ho(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ls(this.emaSmoothed,e,this.params.emaAlpha);const s=av(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class dv extends ra{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?ls(this.smoothed,e,this.params.emaAlpha):e}}class Or{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new nv({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new ov({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new dv({initial:e,label:"liveEdgeDelay",...t})}}const lv=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Tt=()=>window.ManagedMediaSource||window.MediaSource,Go=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},uv=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wn=["timeupdate","progress","play","seeked","stalled","waiting"];var _e;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(_e||(_e={}));let hv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ie,this.representationSubscription=new ie,this.state$=new ue(_e.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.error$=new R,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new R,this.gapWatchdogStarted=!1,this.destroyController=new Zt,this.initManifest=we(this.destroyController.signal,async function*(t,s,r){var a;this.element=t,this.manifestUrlString=Fe(s,r,me.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(_e.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(_e.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=we(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n})});if(!s)return null;let r;try{r=Xm(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:l})=>{var d,u,c,h;return!!(!((u=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||u===void 0)&&u.call(d,o)&&(!((h=(c=Tt())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${l}"`))||n===Se.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:as(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=we(this.destroyController.signal,async function*(t,s,r){var a;P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(_e.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(C(m,"error").pipe(ce(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:_.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?cv():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Go())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const l={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 An(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,l),this.bufferManagers=[this.videoBufferManager],D(s)&&(this.audioBufferManager=new An(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,l),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(pi(Qt).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=dn(this.manifestUrlString,me.DASH_CMAF_OFFSET_P);this.manifestUrlString=Fe(this.manifestUrlString,S+Qt,me.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(N(...wn.filter(m=>m!=="waiting").map(m=>C(this.element,m))).pipe($(m=>this.element?mi(this.element.buffered,this.element.currentTime*1e3):0),he(),ce(m=>!!m),gi(m=>{var v;(v=this.stallWatchdogSubscription)===null||v===void 0||v.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ce(v=>this.isActiveLowLatency&&!!v)).subscribe(v=>this.liveEstimatedDelay.next(v))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(v=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=v-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),lv(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,E;let A=0;if(v){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(j=>{var q,K;return(K=(q=j.getLiveSegmentsToLoadState(this.manifest))===null||q===void 0?void 0:q.to)!==null&&K!==void 0?K:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let m=0;this.representationSubscription.add(Re({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gd(Qt)).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=dn(this.manifestUrlString,me.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),j=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,q=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,K=this.isActiveLowLatency?S:v;let G=qe.None;if(this.isActiveLowLatency?G=qe.ActiveLowLatency:K<k+q&&K>=k?G=qe.LiveWithTargetOffset:A!==0&&K<k&&(G=qe.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),G===qe.LiveForwardBuffering||G===qe.LiveWithTargetOffset){const J=m-(k+j),Z=this.normolizeLiveOffset(Math.trunc(A+J/E)),M=Math.abs(Z-A);let I;!v||M<=this.tuning.dashCmafLive.offsetCalculationError?I=A:Z>0&&M>this.tuning.dashCmafLive.offsetCalculationError?I=Z:I=0,this.manifestUrlString=Fe(this.manifestUrlString,I,me.DASH_CMAF_OFFSET_P)}G!==qe.None&&G!==qe.ActiveLowLatency&&(m=0,this.updateLive())}))}const d=N(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),u=N(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe($(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(N(this.forceEnded$,Re({allBuffersFull:d,someBufferEnded:u}).pipe(ce(({allBuffersFull:m,someBufferEnded:v})=>m&&v))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(v=>!v.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(v){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(N(...this.bufferManagers.map(m=>m.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(m=>{var v;return(v=this.source)===null||v===void 0?void 0:v.addEventListener("sourceopen",m)}));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),g=this.manifest.representations.video.reduce(h,c);(f||g)&&(this.source.duration=Math.max(f,g)/1e3),this.audioBufferManager&&D(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(_e.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=pi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new rv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Or.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=Fe(this.manifestUrlString,n,me.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.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(_e.RUNNING),this.subscription.add(N(...wn.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&Rr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=Qt,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=pi(Qt).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:_.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){const s={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let l;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?l=e:l=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Rr(this.element.buffered,l)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(l),(o=this.audioBufferManager)===null||o===void 0||o.maintain(l),this.element.currentTime=l/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(_e.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class fv{constructor(e,t){this.fov=e,this.orientation=t}}class pv{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var mv=`#define GLSLIFY 1
|
|
38
|
+
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,vv=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
41
41
|
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 vv{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new hv(this.params.fov,this.params.orientation),this.cameraRotationManager=new fv(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(pv,this.gl.VERTEX_SHADER),s=this.createShader(mv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,l=t+r,c=e-s,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}const Cr=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},gv=(i,e)=>new Mr(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Cr()))},{...s,...e});r.observe(i);const a=C(document,"visibilitychange").pipe($(n=>!document.hidden||Cr())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}});class Go{constructor(e){this.subscription=new ie,this.videoState=new ue(ae.STOPPED),this.elementSize$=new y(void 0),this.elementVisible$=new y(!0),this.textTracksManager=new mt,this.droppedFramesManager=new xo,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new up,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==ae.STOPPED&&n!==p.STOPPED){const l=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:n===p.PAUSED?(this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case ae.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ae.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new vv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=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(Je(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new cv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=Ot(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:_.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe($(d=>d.map(({track:l})=>l)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ce(D),Ae()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add($i(this.video,t.isLooped,r)),this.subscription.add(Ct(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ri(this.video,t.playbackRate,s.playbackRateState$,r)),a(gd(this.video),this.elementSize$),a(gv(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===_e.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),g=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=Zm(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of g){const E=Xm(S);if(E){c.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&ev(f,g,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(c);for(const S of m){const E=tv(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const v=this.selectVideoRepresentation();P(v),this.player.initRepresentations(v.id,(l=this.audioRepresentations.get(v.id))===null||l===void 0?void 0:l.id,this.params.sourceHls)}else d===_e.REPRESENTATIOS_READY&&(this.videoState.setState(ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(N(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==_e.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),g=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=kt(S),A=kt(c);if(E&&A)return es(E,A)&&es(E,g)}).map(S=>S.id)[0]),this.player.switchRepresentation(Se.VIDEO,m).catch(n);const v=this.audioRepresentations.get(c.id);v&&this.player.switchRepresentation(Se.AUDIO,v.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(he(),$(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===p.READY),he());this.subscription.add(N(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(N(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=pi(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,g=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(l&&!u&&(r=(s=this.audioRepresentations.get(l.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),v=Ss(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:g,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?v!=null?v:l:l!=null?l:v;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Mt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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 Sv extends Go{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class bv extends Go{constructor(e){super(e),this.liveOffset=new Xr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Re({interval:fi(Qt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===ae.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(Re({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===ae.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 qe={};var W;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const ci=(i,e)=>new Mr(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class yv{constructor(e){this.subscription=new ie,this.videoState=new ue(W.INITIALIZING),this.textTracksManager=new mt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==W.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:U(t)}break;case p.READY:switch(t){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:U(t)}break;case p.PLAYING:switch(t){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:U(t)}break;case p.PAUSED:switch(t){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case W.PLAYING:this.pause();break;default:U(t)}break;default:U(s)}},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(Je(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:_.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(qe.Hls=r.default,qe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){P(qe.Hls,"hls.js not loaded"),this.hls=new qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){P(qe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Ot(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add($i(this.video,e.isLooped,s)),this.subscription.add(Ct(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ri(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ci(this.hls,qe.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:_.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(W.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),a(ci(this.hls,qe.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,f;const g=c.name||c.height.toString(10),{width:m,height:v}=c,S=(f=gs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:kt({width:m,height:v});if(!S)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:g.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:v},fps:E};return this.trackLevels.set(g,{track:A,level:c}),l.push(A),l},[]))),t.availableVideoTracks$),a(ci(this.hls,qe.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||"",g=c.lang,m="internal";l.push({id:h,url:f,language:g,type:m})}e.internalTextTracks.startTransitionTo(l)}}),a(ci(this.hls,qe.Events.LEVEL_LOADING).pipe($(({url:d})=>Je(d))),t.hostname$),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=ci(this.hls,qe.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(ce(D)).subscribe(t.currentVideoTrack$,s),this.subscription.add(et(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(Q(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,g=this.hls.levels[f];!g||c.bitrate>g.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=N(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(W.PLAYING),await Mt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:t}))||(this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(W.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(W.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const wn="X-Playback-Duration";var kn=async i=>{var e;const t=await Si(i),s=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(wn)?parseInt(t.headers.get(wn),10):void 0};const Tv=i=>{let e=null;if(i.QUALITY&&(e=gs(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kt({width:t,height:s})}return e!=null?e:null},Ev=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){const c=rs(d[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Tv(c);let g;c.BANDWIDTH&&(g=parseInt(c.BANDWIDTH,10)/1e3||void 0),!g&&c["AVERAGE-BANDWIDTH"]&&(g=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[E,A]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(v={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:g,size:v,fps:m})}if(l){const c=rs(l[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,g=c.NAME;h&&f&&n.push({type:"internal",id:f,label:g,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},$v=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let nr=0;const ra=async(i,e=i,t)=>{const r=await(await Si(i)).text();nr+=1;try{const{qualityManifests:a,textTracks:n}=Ev(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(nr<=t.manifestRetryMaxCount)return await $v(zi(nr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ra(i,e,t)}return{qualityManifests:[],textTracks:[]}};var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ee||(ee={}));class Av{constructor(e){var t;this.subscription=new ie,this.videoState=new ue(ee.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.liveOffset=new Xr,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ee.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ee.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ee.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return U(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.INVARIANT,url:this.params.source.url},ra(Fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Je(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&D(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(Je(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ee.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},s)),this.subscription.add(Re({startTime:this.manifestStartTime$.pipe(ce(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?me.DASH_CMAF_OFFSET_P:me.OFFSET_P,u=Fe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),kn(u).then(d=>{var l;if(!Q(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(Q(c)||!isFinite(c))try{Si(u).then(h=>h.text()).then(h=>{var f;const g=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(g){const m=new URL(g,u).toString();kn(m).then(v=>{Q(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class wv{constructor(e){this.subscription=new ie,this.videoState=new ue(re.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===Y.Requested&&this.seek(l.position),s){case re.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return U(s)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.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(Je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ra(Fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ot(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($i(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&D(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(g=>g.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Je(f.url));const g=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(g!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(g),v.playbackRate=g)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!Sd()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(N(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Ce(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&d&&n.searchParams.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(le||(le={}));class kv{constructor(e){this.subscription=new ie,this.videoState=new ue(le.STOPPED),this.trackUrls={},this.textTracksManager=new mt,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==le.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[l.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),a){case le.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add($i(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&D(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const l=this.params.desiredState.playbackRate.getState(),c=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(l!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(l),h.playbackRate=l)}}this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),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:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Rr(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Je(s))}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(s=Object.values(this.trackUrls).find(c=>!Pt(c.track.quality)&&es(c.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&Sr(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Pt(f.track.quality)&&Xt(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=Ss(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 Pn=["stun:videostun.mycdn.me:80"],Pv=1e3,Dv=3,or=()=>null;class Lv{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=or,this.externalStopCallback=or,this.externalErrorCallback=or,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Pn}]};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:_.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Pv)}normalizeOptions(e={}){const t={stunServerList:Pn,maxRetryNumber:Dv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(te||(te={}));class xv{constructor(e){this.videoState=new ue(te.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case te.READY:s===p.PAUSED?(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case te.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new Lv(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,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};N(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=Ot(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===te.READY&&this.videoState.setState(te.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ct(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(p.PAUSED);break;case te.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return U(n.to)}},s)).add(N(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Je(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:Pe.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Dn{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 Ee;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(Ee||(Ee={}));var ft;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ft||(ft={}));var dr,lr,ur,cr,Ui,hr,Hi,fr,Gi,pr,Yi,mr,qi,vr,ji,gr;const Yo=Or().device===bd.Android,pt=document.createElement("video"),_v='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Rv='video/mp4; codecs="hev1.1.6.L93.B0"',qo='video/webm; codecs="vp09.00.10.08"',jo='video/webm; codecs="av01.0.00M.08"',Iv='audio/mp4; codecs="mp4a.40.2"',Cv='audio/webm; codecs="opus"',Et={mms:Ho(),mse:lv(),hls:!!(!((dr=pt.canPlayType)===null||dr===void 0)&&dr.call(pt,"application/x-mpegurl")||!((lr=pt.canPlayType)===null||lr===void 0)&&lr.call(pt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},xe={mp4:!!(!((ur=pt.canPlayType)===null||ur===void 0)&&ur.call(pt,"video/mp4")),webm:!!(!((cr=pt.canPlayType)===null||cr===void 0)&&cr.call(pt,"video/webm")),cmaf:!0},Qe={h264:!!(!((hr=(Ui=Tt())===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||hr===void 0)&&hr.call(Ui,_v)),h265:!!(!((fr=(Hi=Tt())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||fr===void 0)&&fr.call(Hi,Rv)),vp9:!!(!((pr=(Gi=Tt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||pr===void 0)&&pr.call(Gi,qo)),av1:!!(!((mr=(Yi=Tt())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||mr===void 0)&&mr.call(Yi,jo)),aac:!!(!((vr=(qi=Tt())===null||qi===void 0?void 0:qi.isTypeSupported)===null||vr===void 0)&&vr.call(qi,Iv)),opus:!!(!((gr=(ji=Tt())===null||ji===void 0?void 0:ji.isTypeSupported)===null||gr===void 0)&&gr.call(ji,Cv))},hi=(Qe.h264||Qe.h265)&&Qe.aac;let $t;const Ov=async()=>{if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:jo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:qo}})]);$t={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}};try{Ov()}catch(i){console.error(i)}const bi=Et.hls&&xe.mp4,Mv=()=>Object.keys(Qe).filter(i=>Qe[i]),Bv=(i,e=!1,t=!1)=>{const s=Et.mse||Et.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&xe.mp4&&hi;case b.DASH_WEBM:return s&&xe.webm&&Qe.vp9&&Qe.opus;case b.DASH_WEBM_AV1:return s&&xe.webm&&Qe.av1&&Qe.opus;case b.DASH_LIVE:return Et.mse&&xe.mp4&&hi;case b.DASH_LIVE_CMAF:return s&&xe.mp4&&hi&&xe.cmaf;case b.DASH_ONDEMAND:return s&&xe.mp4&&hi;case b.HLS:case b.HLS_ONDEMAND:return bi||e&&Et.mse&&xe.mp4&&hi;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return bi;case b.MPEG:return xe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Et.webrtc&&Et.ws&&Qe.h264&&(xe.mp4||xe.webm);default:return U(r)}})},ct=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case ft.VP9:return[e,t];case ft.AV1:return[t,e];case ft.NONE:return[];case ft.SMOOTH:return $t?$t[t].smooth?[t,e]:$t[e].smooth?[e,t]:[t,e]:[e,t];case ft.POWER_EFFICIENT:return $t?$t[t].powerEfficient?[t,e]:$t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:U(i)}return[e,t]},Nv=({webmCodec:i,androidPreferredFormat:e})=>{if(Yo)switch(e){case Ee.MPEG:return[b.MPEG,...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Ee.HLS:return[b.HLS,b.HLS_ONDEMAND,...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case Ee.DASH:return[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case Ee.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...ct(i),b.HLS,b.HLS_ONDEMAND];case Ee.DASH_ANY_WEBM:return[...ct(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Ee.DASH_SEP:return[b.DASH_SEP,b.MPEG,...ct(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:U(e)}return bi?[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},Fv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[b.DASH_LIVE_CMAF,b.DASH_LIVE]:[b.DASH_LIVE,b.DASH_LIVE_CMAF],r=e?[b.HLS_LIVE_CMAF,b.HLS_LIVE]:[b.HLS_LIVE,b.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(Yo)switch(i){case Ee.DASH:case Ee.DASH_ANY_MPEG:case Ee.DASH_ANY_WEBM:case Ee.DASH_SEP:{o=a;break}case Ee.HLS:case Ee.MPEG:{o=n;break}default:U(i)}else bi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},Ln=i=>i?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE_CMAF]:[b.DASH_WEBM,b.DASH_WEBM_AV1,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Vv=i=>new Mr(e=>{const t=new ie,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:d})=>d!==void 0)),n=new R;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Uv={chunkDuration:5e3,maxParallelRequests:5};class Hv{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new R,this.noAvailableProvidersError$=new R,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new R,warning$:new R,willSeekEvent$:new R,seekedEvent$:new R,loopedEvent$:new R,endedEvent$:new R,firstBytesEvent$:new R,firstFrameEvent$:new R,canplay$:new R,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Bv([...Fv(this.params.tuning),...Nv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>D(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Dn(a);const n=[...Ln(!0),...Ln(!1)];this.chromecastFormatsIterator=new Dn(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(Q(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ye.SCREEN:return this.createScreenProvider(t);case ye.CHROMECAST:return this.createChromecastProvider(t);default:return U(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new Sv({...n,source:o,sourceHls:u})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new bv({...n,source:o})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),bi||!this.params.tuning.useHlsJs?new wv({...n,source:o}):new yv({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Av({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new kv({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new wp({...n,source:o,config:{...Uv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new xv({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Vf({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ye.CHROMECAST:ye.SCREEN}chooseFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return U(e)}}skipFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.next();case ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return U(e)}}handleNoFormatsError(e){switch(e){case ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return U(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return rs(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,s=0;return e.add(N(this.providerOutput.error$,Vv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:_.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ce(({to:a})=>a===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===_.NETWORK,o=r.category===_.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:ye.SCREEN)}})),e}}const Gv=5e3,xn="one_video_throughput",_n="one_video_rtt",st=window.navigator.connection,Rn=()=>{const i=st==null?void 0:st.downlink;if(D(i)&&i!==10)return i*1e3},In=()=>{const i=st==null?void 0:st.rtt;if(D(i)&&i!==3e3)return i},Cn=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class mi{constructor(e){var t,s;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=mi.load(xn)||(e.useBrowserEstimation?Rn():void 0)||Gv,a=(s=(t=mi.load(_n))!==null&&t!==void 0?t:e.useBrowserEstimation?In():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(Cn(r,a,e.rttPenaltyRequestSize)),this.throughput=Ir.getSmoothedValue(r,-1,e),this.rtt=Ir.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Rn();u&&this.throughput.next(u);const d=In();D(d)&&this.rtt.next(d)};st&&"onchange"in st&&this.subscription.add(C(st,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Rs.set(xn,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Rs.set(_n,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Re({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Cn(n,o,e.rttPenaltyRequestSize)),ce(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ne();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(C(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,s=ne()}));break;case 1:case 0:r.add(C(e,"loadstart").subscribe(()=>{t=0,s=ne()}));break}r.add(C(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),u=n-t,d=o-s;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=ne(),n=0,o=ne();const u=l=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,ne()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=ne()}o=ne()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await(s==null?void 0:s.read().then(d,u))}};this.concurrentDownloads.add(e),s==null||s.read().then(d,u)}addRawSpeed(e,t,s=1,r=!1){if(mi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=Rs.get(e);if(D(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const On={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Pe.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Pe.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ft.VP9,androidPreferredFormat:Ee.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Yv=i=>{var e;return{...yd(i,On),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...On.configName]}};var Mn=({seekState:i,position$:e})=>N(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ce(D)),e.pipe(ce(()=>i.getState().state===Y.None))),qv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const jv=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ce(r=>r.length>0),Ae()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class Jv{constructor(e={configName:[]}){if(this.subscription=new ie,this.logger=new Td,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:Y.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraOrientation:new ue({x:0,y:0})},this.info={playbackState$:new y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(ht.NONE),chromecastState$:new y(ge.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.events={inited$:new R,ready$:new R,started$:new R,playing$:new R,paused$:new R,stopped$:new R,willStart$:new R,willResume$:new R,willPause$:new R,willStop$:new R,willDestruct$:new R,watchCoverageRecord$:new R,watchCoverageLive$:new R,managedError$:new R,fatalError$:new R,ended$:new R,looped$:new R,seeked$:new R,willSeek$:new R,firstBytes$:new R,firstFrame$:new R,canplay$:new R,log$:new R},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:op},this.initLogs(),this.tuning=Yv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ad({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),d=`Player.${String(s)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=qv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Hv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Cr()?C(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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ge.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()===ge.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(ce(s=>s.length>0),Ae()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return jv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return D(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(N(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(ce(({from:e})=>e===p.STOPPED),Ae()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState({...n,state:Y.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,u)=>Pt(o)?1:Pt(u)?-1:Xt(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(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).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(Re({hasLiveOffsetByPaused:N(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),he(),$(n=>n===p.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Re({atLiveEdge:Re({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:u})=>{const d=this.getActiveLiveDelay(u);return n&&Math.abs(o)<d/1e3}),he(),vi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Re({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),he(),vi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),he()).subscribe(this.info.volume$)).add(Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(N(e.providerOutput.endedEvent$.pipe(Zi(!0)),e.providerOutput.seekedEvent$.pipe(Zi(!1))).pipe(he()).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:_.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:ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),$(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),$(()=>ne()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ce(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>s.next(!1)));let r=0;const a=N(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),he());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(N(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(N(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===ge.CONNECTED?l=ht.SECOND_SCREEN:u?n?l=ht.PIP:o?l=ht.FULLSCREEN:l=ht.INLINE:l=ht.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 ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(s=>s.length>0),Ae()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=Ss(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(N(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),np(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>ap(s)),this.providerContainer.current$.subscribe(({type:s})=>Fi("provider",s)),t.duration$.subscribe(s=>Fi("duration",s)),t.availableVideoTracks$.pipe(ce(s=>!!s.length),Ae()).subscribe(s=>Fi("tracks",s)),this.events.fatalError$.subscribe(new We("fatalError")),this.events.managedError$.subscribe(new We("managedError")),t.position$.subscribe(new We("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new We("quality")),this.info.currentBuffer$.subscribe(new We("buffer")),t.isBuffering$.subscribe(new We("isBuffering"))].forEach(s=>this.subscription.add(s)),Fi("codecs",Mv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:_.DOM,message:String(r)})})};this.subscription.add(N(C(document,"visibilitychange"),C(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const Xv=`@vkontakte/videoplayer-core@${Ed}`;export{ge as ChromecastState,br as HttpConnectionType,tg as Observable,p as PlaybackState,Jv as Player,Xv as SDK_VERSION,ig as Subject,sg as Subscription,ht as Surface,Ed as VERSION,rg as ValueSubject,b as VideoFormat,ag 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 gv{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new fv(this.params.fov,this.params.orientation),this.cameraRotationManager=new pv(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(mv,this.gl.VERTEX_SHADER),s=this.createShader(vv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,l=t-r,d=e+s,u=t+r,c=e-s,h=t+r;return[a,n,o,l,d,u,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Yo{constructor(e){this.subscription=new ie,this.videoState=new ue(ae.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new mt,this.droppedFramesManager=new _o,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new cp,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(l.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==ae.STOPPED&&n!==p.STOPPED){const u=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(l.position-u,l.forcePrecise)}if(n===p.STOPPED){a!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:n===p.PAUSED?(this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case ae.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ae.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new gv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=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(Je(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=Ot(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:_.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,l)=>this.subscription.add(o.subscribe(l,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe($(d=>d.map(({track:u})=>u)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ce(D),Ae()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ai(this.video,t.isLooped,r)),this.subscription.add(Ct(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ri(this.video,t.playbackRate,s.playbackRateState$,r)),a(Sd(this.video),this.elementSize$),a(ai(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var u;if(d===_e.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),g=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=ev(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of g){const E=Zm(S);if(E){c.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&tv(f,g,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(c);for(const S of m){const E=iv(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const v=this.selectVideoRepresentation();P(v),this.player.initRepresentations(v.id,(u=this.audioRepresentations.get(v.id))===null||u===void 0?void 0:u.id,this.params.sourceHls)}else d===_e.REPRESENTATIOS_READY&&(this.videoState.setState(ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(N(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),u=this.player.state$.getTransition();if(d!==_e.RUNNING||u||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),g=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.params.output.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=kt(S),A=kt(c);if(E&&A)return ts(E,A)&&ts(E,g)}).map(S=>S.id)[0]),this.player.switchRepresentation(Se.VIDEO,m).catch(n);const v=this.audioRepresentations.get(c.id);v&&this.player.switchRepresentation(Se.AUDIO,v.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(he(),$(d=>{var u;return d&&((u=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var u,c;if(d!=null&&d.is3dVideo&&(!((u=this.params.tuning.spherical)===null||u===void 0)&&u.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===p.READY),he());this.subscription.add(N(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(N(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const l=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,u=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=mi(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,g=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(s=this.audioRepresentations.get(u.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),v=bs(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:g,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=l?v!=null?v:u:u!=null?u:v;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Mt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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 Sv extends Yo{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class bv extends Yo{constructor(e){super(e),this.liveOffset=new Zr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Re({interval:pi(Qt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===ae.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(Re({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===ae.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 je={};var W;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const hi=(i,e)=>new Br(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class yv{constructor(e){this.subscription=new ie,this.videoState=new ue(W.INITIALIZING),this.textTracksManager=new mt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==W.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:U(t)}break;case p.READY:switch(t){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:U(t)}break;case p.PLAYING:switch(t){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:U(t)}break;case p.PAUSED:switch(t){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case W.PLAYING:this.pause();break;default:U(t)}break;default:U(s)}},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(Je(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:_.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(je.Hls=r.default,je.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){P(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){P(je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Ot(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ai(this.video,e.isLooped,s)),this.subscription.add(Ct(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ri(this.video,e.playbackRate,r.playbackRateState$,s)),a(ai(this.video),t.elementVisible$),this.subscription.add(hi(this.hls,je.Events.ERROR).subscribe(d=>{var u;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:_.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(u=d.err)===null||u===void 0?void 0:u.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),a(hi(this.hls,je.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((u,c)=>{var h,f;const g=c.name||c.height.toString(10),{width:m,height:v}=c,S=(f=Ss((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:kt({width:m,height:v});if(!S)return u;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:g.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:v},fps:E};return this.trackLevels.set(g,{track:A,level:c}),u.push(A),u},[]))),t.availableVideoTracks$),a(hi(this.hls,je.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const u=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",g=c.lang,m="internal";u.push({id:h,url:f,language:g,type:m})}e.internalTextTracks.startTransitionTo(u)}}),a(hi(this.hls,je.Events.LEVEL_LOADING).pipe($(({url:d})=>Je(d))),t.hostname$),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var u;return(u=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||u===void 0?void 0:u.track},o=hi(this.hls,je.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(ce(D)).subscribe(t.currentVideoTrack$,s),this.subscription.add(et(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var u;if(Q(d))return;const c=(u=this.trackLevels.get(d.id))===null||u===void 0?void 0:u.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,g=this.hls.levels[f];!g||c.bitrate>g.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const l=N(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(W.PLAYING),await Mt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:t}))||(this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(W.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(W.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const kn="X-Playback-Duration";var Pn=async i=>{var e;const t=await bi(i),s=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(kn)?parseInt(t.headers.get(kn),10):void 0};const Tv=i=>{let e=null;if(i.QUALITY&&(e=Ss(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kt({width:t,height:s})}return e!=null?e:null},Ev=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
+
`),a=[],n=[];for(let o=0;o<r.length;o++){const l=r[o],d=l.match(/^#EXT-X-STREAM-INF:(.+)/),u=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!u)){if(d){const c=as(d[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Tv(c);let g;c.BANDWIDTH&&(g=parseInt(c.BANDWIDTH,10)/1e3||void 0),!g&&c["AVERAGE-BANDWIDTH"]&&(g=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[E,A]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(v={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:g,size:v,fps:m})}if(u){const c=as(u[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,g=c.NAME;h&&f&&n.push({type:"internal",id:f,label:g,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},$v=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let or=0;const aa=async(i,e=i,t)=>{const r=await(await bi(i)).text();or+=1;try{const{qualityManifests:a,textTracks:n}=Ev(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(or<=t.manifestRetryMaxCount)return await $v(Qi(or-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),aa(i,e,t)}return{qualityManifests:[],textTracks:[]}};var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ee||(ee={}));class Av{constructor(e){var t;this.subscription=new ie,this.videoState=new ue(ee.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.liveOffset=new Zr,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ee.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ee.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ee.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return U(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.INVARIANT,url:this.params.source.url},aa(Fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Je(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),a(ai(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=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(Je(h.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),l&&l.from===ee.CHANGING_MANIFEST&&this.videoState.setState(l.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,l,d;const u=(d=(l=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||l===void 0?void 0:l.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(u||void 0)},s)),this.subscription.add(Re({startTime:this.manifestStartTime$.pipe(ce(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:u}=(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"],[u,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?me.DASH_CMAF_OFFSET_P:me.OFFSET_P,l=Fe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",l),this.video.load(),Pn(l).then(d=>{var u;if(!Q(d))this.maxSeekBackTime$.next(d);else{const c=(u=this.params.source.maxSeekBackTime)!==null&&u!==void 0?u:this.maxSeekBackTime$.getValue();if(Q(c)||!isFinite(c))try{bi(l).then(h=>h.text()).then(h=>{var f;const g=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(g){const m=new URL(g,l).toString();Pn(m).then(v=>{Q(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class wv{constructor(e){this.subscription=new ie,this.videoState=new ue(re.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n||o||l){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),u.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&u.state===Y.Requested&&this.seek(u.position),s){case re.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return U(s)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.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(Je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),aa(Fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l));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(Ai(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&D(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(g=>g.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Je(f.url));const g=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(g!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(g),v.playbackRate=g)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===Y.Requested&&this.seek(l.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!bd()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(N(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Ce(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},s))}const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,u]of[[o,"mq"],[l,"lq"]]){const c=String(parseFloat(d||""));u&&d&&n.searchParams.set(u,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(le||(le={}));class kv{constructor(e){this.subscription=new ie,this.videoState=new ue(le.STOPPED),this.trackUrls={},this.textTracksManager=new mt,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==le.READY&&!u){this.handleQualityLimitTransition(d.to.max);return}if(a===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(u){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),u.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[u.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),a){case le.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ai(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ri(this.video,t.playbackRate,r.playbackRateState$,s)),a(ai(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,l;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&D(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const u=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(u!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(u),h.playbackRate=u)}}this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),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:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Cr(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Je(s))}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const l=(s=Object.values(this.trackUrls).find(c=>!Pt(c.track.quality)&&ts(c.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,u=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(l&&u&&br(u.quality,l.quality)&&(n=l),!n){const c=Object.values(this.trackUrls).filter(f=>!Pt(f.track.quality)&&Xt(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const l=Object.values(this.trackUrls).map(d=>d.track);n=bs(l,{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 Dn=["stun:videostun.mycdn.me:80"],Pv=1e3,Dv=3,dr=()=>null;class Lv{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=dr,this.externalStopCallback=dr,this.externalErrorCallback=dr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Dn}]};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:_.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Pv)}normalizeOptions(e={}){const t={stunServerList:Dn,maxRetryNumber:Dv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(te||(te={}));class xv{constructor(e){this.videoState=new ue(te.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case te.READY:s===p.PAUSED?(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case te.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new Lv(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,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};N(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=Ot(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ai(this.video),this.params.output.elementVisible$),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)===te.READY&&this.videoState.setState(te.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ct(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(p.PAUSED);break;case te.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return U(n.to)}},s)).add(N(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ke(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Je(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:Pe.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Ln{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 Ee;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(Ee||(Ee={}));var ft;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ft||(ft={}));var lr,ur,cr,hr,Hi,fr,Gi,pr,Yi,mr,ji,vr,qi,gr,Wi,Sr;const jo=Mr().device===yd.Android,pt=document.createElement("video"),_v='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Rv='video/mp4; codecs="hev1.1.6.L93.B0"',qo='video/webm; codecs="vp09.00.10.08"',Wo='video/webm; codecs="av01.0.00M.08"',Iv='audio/mp4; codecs="mp4a.40.2"',Cv='audio/webm; codecs="opus"',Et={mms:Go(),mse:uv(),hls:!!(!((lr=pt.canPlayType)===null||lr===void 0)&&lr.call(pt,"application/x-mpegurl")||!((ur=pt.canPlayType)===null||ur===void 0)&&ur.call(pt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},xe={mp4:!!(!((cr=pt.canPlayType)===null||cr===void 0)&&cr.call(pt,"video/mp4")),webm:!!(!((hr=pt.canPlayType)===null||hr===void 0)&&hr.call(pt,"video/webm")),cmaf:!0},Qe={h264:!!(!((fr=(Hi=Tt())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||fr===void 0)&&fr.call(Hi,_v)),h265:!!(!((pr=(Gi=Tt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||pr===void 0)&&pr.call(Gi,Rv)),vp9:!!(!((mr=(Yi=Tt())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||mr===void 0)&&mr.call(Yi,qo)),av1:!!(!((vr=(ji=Tt())===null||ji===void 0?void 0:ji.isTypeSupported)===null||vr===void 0)&&vr.call(ji,Wo)),aac:!!(!((gr=(qi=Tt())===null||qi===void 0?void 0:qi.isTypeSupported)===null||gr===void 0)&&gr.call(qi,Iv)),opus:!!(!((Sr=(Wi=Tt())===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||Sr===void 0)&&Sr.call(Wi,Cv))},fi=(Qe.h264||Qe.h265)&&Qe.aac;let $t;const Ov=async()=>{if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Wo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:qo}})]);$t={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}};try{Ov()}catch(i){console.error(i)}const yi=Et.hls&&xe.mp4,Mv=()=>Object.keys(Qe).filter(i=>Qe[i]),Bv=(i,e=!1,t=!1)=>{const s=Et.mse||Et.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&xe.mp4&&fi;case b.DASH_WEBM:return s&&xe.webm&&Qe.vp9&&Qe.opus;case b.DASH_WEBM_AV1:return s&&xe.webm&&Qe.av1&&Qe.opus;case b.DASH_LIVE:return Et.mse&&xe.mp4&&fi;case b.DASH_LIVE_CMAF:return s&&xe.mp4&&fi&&xe.cmaf;case b.DASH_ONDEMAND:return s&&xe.mp4&&fi;case b.HLS:case b.HLS_ONDEMAND:return yi||e&&Et.mse&&xe.mp4&&fi;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return yi;case b.MPEG:return xe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Et.webrtc&&Et.ws&&Qe.h264&&(xe.mp4||xe.webm);default:return U(r)}})},ct=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case ft.VP9:return[e,t];case ft.AV1:return[t,e];case ft.NONE:return[];case ft.SMOOTH:return $t?$t[t].smooth?[t,e]:$t[e].smooth?[e,t]:[t,e]:[e,t];case ft.POWER_EFFICIENT:return $t?$t[t].powerEfficient?[t,e]:$t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:U(i)}return[e,t]},Nv=({webmCodec:i,androidPreferredFormat:e})=>{if(jo)switch(e){case Ee.MPEG:return[b.MPEG,...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Ee.HLS:return[b.HLS,b.HLS_ONDEMAND,...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case Ee.DASH:return[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case Ee.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...ct(i),b.HLS,b.HLS_ONDEMAND];case Ee.DASH_ANY_WEBM:return[...ct(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case Ee.DASH_SEP:return[b.DASH_SEP,b.MPEG,...ct(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:U(e)}return yi?[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...ct(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},Fv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[b.DASH_LIVE_CMAF,b.DASH_LIVE]:[b.DASH_LIVE,b.DASH_LIVE_CMAF],r=e?[b.HLS_LIVE_CMAF,b.HLS_LIVE]:[b.HLS_LIVE,b.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(jo)switch(i){case Ee.DASH:case Ee.DASH_ANY_MPEG:case Ee.DASH_ANY_WEBM:case Ee.DASH_SEP:{o=a;break}case Ee.HLS:case Ee.MPEG:{o=n;break}default:U(i)}else yi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},xn=i=>i?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE_CMAF]:[b.DASH_WEBM,b.DASH_WEBM_AV1,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Vv=i=>new Br(e=>{const t=new ie,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:u})=>`${d}-${u}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:d})=>d!==void 0)),n=new R;let o=0,l="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),l=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Uv={chunkDuration:5e3,maxParallelRequests:5};class Hv{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new R,this.noAvailableProvidersError$=new R,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new R,warning$:new R,willSeekEvent$:new R,seekedEvent$:new R,loopedEvent$:new R,endedEvent$:new R,firstBytesEvent$:new R,firstFrameEvent$:new R,canplay$:new R,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),elementVisible$:new y(!0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Bv([...Fv(this.params.tuning),...Nv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>D(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ln(a);const n=[...xn(!0),...xn(!1)];this.chromecastFormatsIterator=new Ln(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(Q(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ye.SCREEN:return this.createScreenProvider(t);case ye.CHROMECAST:return this.createChromecastProvider(t);default:return U(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new Sv({...n,source:o,sourceHls:l})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new bv({...n,source:o})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),yi||!this.params.tuning.useHlsJs?new wv({...n,source:o}):new yv({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Av({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new kv({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new kp({...n,source:o,config:{...Uv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new xv({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Uf({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ye.CHROMECAST:ye.SCREEN}chooseFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return U(e)}}skipFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.next();case ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return U(e)}}handleNoFormatsError(e){switch(e){case ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return U(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return as(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,s=0;return e.add(N(this.providerOutput.error$,Vv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:_.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ce(({to:a})=>a===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===_.NETWORK,o=r.category===_.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:ye.SCREEN)}})),e}}const Gv=5e3,_n="one_video_throughput",Rn="one_video_rtt",st=window.navigator.connection,In=()=>{const i=st==null?void 0:st.downlink;if(D(i)&&i!==10)return i*1e3},Cn=()=>{const i=st==null?void 0:st.rtt;if(D(i)&&i!==3e3)return i},On=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class vi{constructor(e){var t,s;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=vi.load(_n)||(e.useBrowserEstimation?In():void 0)||Gv,a=(s=(t=vi.load(Rn))!==null&&t!==void 0?t:e.useBrowserEstimation?Cn():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(On(r,a,e.rttPenaltyRequestSize)),this.throughput=Or.getSmoothedValue(r,-1,e),this.rtt=Or.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const l=In();l&&this.throughput.next(l);const d=Cn();D(d)&&this.rtt.next(d)};st&&"onchange"in st&&this.subscription.add(C(st,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Is.set(_n,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Is.set(Rn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Re({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>On(n,o,e.rttPenaltyRequestSize)),ce(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ne();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(C(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,s=ne()}));break;case 1:case 0:r.add(C(e,"loadstart").subscribe(()=>{t=0,s=ne()}));break}r.add(C(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),l=n-t,d=o-s;this.addRawSpeed(l,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=ne(),n=0,o=ne();const l=u=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{if(u)!t&&this.addRawSpeed(r,ne()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=ne()}o=ne()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await(s==null?void 0:s.read().then(d,l))}};this.concurrentDownloads.add(e),s==null||s.read().then(d,l)}addRawSpeed(e,t,s=1,r=!1){if(vi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=Is.get(e);if(D(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Mn={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Pe.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Pe.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ft.VP9,androidPreferredFormat:Ee.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Yv=i=>{var e;return{...Td(i,Mn),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Mn.configName]}};var Bn=({seekState:i,position$:e})=>N(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ce(D)),e.pipe(ce(()=>i.getState().state===Y.None))),jv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const qv=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ce(r=>r.length>0),Ae()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class Jv{constructor(e={configName:[]}){if(this.subscription=new ie,this.logger=new Ed,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:Y.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraOrientation:new ue({x:0,y:0})},this.info={playbackState$:new y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(ht.NONE),chromecastState$:new y(ge.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.events={inited$:new R,ready$:new R,started$:new R,playing$:new R,paused$:new R,stopped$:new R,willStart$:new R,willResume$:new R,willPause$:new R,willStop$:new R,willDestruct$:new R,watchCoverageRecord$:new R,watchCoverageLive$:new R,managedError$:new R,fatalError$:new R,ended$:new R,looped$:new R,seeked$:new R,willSeek$:new R,firstBytes$:new R,firstFrame$:new R,canplay$:new R,log$:new R},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:dp},this.initLogs(),this.tuning=Yv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wd({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const l=n.map(c=>JSON.stringify(c,(h,f)=>{const g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_.WTF,message:u,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=jv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Hv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!_r()?C(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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ge.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()===ge.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(ce(s=>s.length>0),Ae()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return qv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return D(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(N(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(ce(({from:e})=>e===p.STOPPED),Ae()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState({...n,state:Y.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,l)=>Pt(o)?1:Pt(l)?-1:Xt(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const l of n)l.fps&&(o[l.quality]=l.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(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).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(Re({hasLiveOffsetByPaused:N(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),he(),$(n=>n===p.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Re({atLiveEdge:Re({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:l})=>{const d=this.getActiveLiveDelay(l);return n&&Math.abs(o)<d/1e3}),he(),gi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Re({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe($(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),he(),gi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),he()).subscribe(this.info.volume$)).add(Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(N(e.providerOutput.endedEvent$.pipe(es(!0)),e.providerOutput.seekedEvent$.pipe(es(!1))).pipe(he()).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:_.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:ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),$(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),$(()=>ne()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ce(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>s.next(!1)));let r=0;const a=N(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),he());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(N(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,l;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:(l=n==null?void 0:n.size)===null||l===void 0?void 0:l.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(N(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===ge.CONNECTED?c=ht.SECOND_SCREEN:!l||!d?c=ht.NONE:n?c=ht.PIP:o?c=ht.FULLSCREEN:c=ht.INLINE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}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 ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(s=>s.length>0),Ae()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=bs(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(N(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),op(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>np(s)),this.providerContainer.current$.subscribe(({type:s})=>Vi("provider",s)),t.duration$.subscribe(s=>Vi("duration",s)),t.availableVideoTracks$.pipe(ce(s=>!!s.length),Ae()).subscribe(s=>Vi("tracks",s)),this.events.fatalError$.subscribe(new We("fatalError")),this.events.managedError$.subscribe(new We("managedError")),t.position$.subscribe(new We("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new We("quality")),this.info.currentBuffer$.subscribe(new We("buffer")),t.isBuffering$.subscribe(new We("isBuffering"))].forEach(s=>this.subscription.add(s)),Vi("codecs",Mv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:_.DOM,message:String(r)})})};this.subscription.add(N(C(document,"visibilitychange"),C(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const Xv=`@vkontakte/videoplayer-core@${$d}`;export{ge as ChromecastState,yr as HttpConnectionType,tg as Observable,p as PlaybackState,Jv as Player,Xv as SDK_VERSION,ig as Subject,sg as Subscription,ht as Surface,$d as VERSION,rg as ValueSubject,b as VideoFormat,ag as VideoQuality};
|